import React, {useContext, useEffect, useState} from 'react';
import SearchBar from "../../../UI/SearchBar/SearchBar";
import {
    getPermanentPersonnel,
    getPermanentPersonnelFilters,
    sendInvitationPermanentPerson
} from "../../../../API/hr_support";
import useListControl from "../../../../hooks/useListControl";
import {CustomSelectOptions} from "../../../../models/ReactComponents";
import MakeCustomRadioSelect from "../../../UI/Forms/CustomSelect/MakeCustomRadioSelect";
import {EmergencyPersonnelRequestsParams, PermanentEmployee} from "../../../../models/HrSupport/PermanentPersonnel";
import DuaList from "../../../UI/DuaList/DuaList";
import ListRow from "../../../UI/DuaList/ListRow";
import ListActions from "../../../UI/DuaList/Columns/ListActions";
import {LinkWithRole} from "../../../HOC/LinkWithRole";
import TextColumn from "../../../UI/DuaList/Columns/TextColumn";
import CreateButton from "../../../UI/CreateButton/CreateButton";
import AddUser from "../../../SVG/AddUser";
import {toastError, toastSuccess, toastWarn} from "../../../../services/toaster";
import useLoading from "../../../../hooks/useLoading";
import HeaderControlsContext from "../../../../context/headerControls-context";
import ConfirmationModal from "../../../UI/Modal/ActionsModal/ConfirmationModal";

const InitParams = (): EmergencyPersonnelRequestsParams => {
    return {
        unit: '',
        gender: '',
        staff_category: '',
        page_size: 10,
        page: 1,
        search: '',
        filterBy: ''
    }
};

const csvHeaders = [
    {label: "ΟΝΟΜΑΤΕΠΩΝΥΜΟ", key: "fullname"},
    {label: "ΠΑΤΡΩΝΥΜΟ", key: "father_name"},
    {label: "ΟΡΓΑΝΙΚΗ ΜΟΝΑΔΑ", key: "default_unit"},
    {label: "ΚΩΔ. ΕΡΓΑΖΟΜEΝΟΥ", key: "user_code"},
    {label: "ΑΡΙΘ. ΦΑΚΕΛΟΥ", key: "difo_code"},
    {label: "ΑΦΜ", key: "afm"},
    {label: "ΚΑΤΗΓΟΡΙΑ", key: "staff_category"},
    {label: "EMAIL", key: "email"},
    {label: "ΕΣΩΤ. ΤΗΛ.", key: "phone"},
    {label: "KINHTO ΤΗΛΕΦΩΝΟ", key: "mobile"},
];

const PersonnelList = () => {

    const [isLoading, setIsLoading] = useLoading(true)
    const [personnel, personnelParams, setPersonnelParams, fetchPersonnel, _, exportList] = useListControl<EmergencyPersonnelRequestsParams, PermanentEmployee>(InitParams(), getPermanentPersonnel, csvHeaders);
    const [filters, setFilters] = useState<Record<string, CustomSelectOptions>>({})
    const {showSensitive} = useContext(HeaderControlsContext)
    const [invitationConfirmShow, setInvitationConfirmShow] = useState<PermanentEmployee | null>(null)

    useEffect(() => {

        (async () => {

            const res = await getPermanentPersonnelFilters()
            setFilters(res.data)
        })()
// eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const handleSubmit = async (hash_employee_id: string) => {
        setIsLoading(true)
        try {
            const res = await sendInvitationPermanentPerson(hash_employee_id)
            toastSuccess('Η αποστολή πρόσκλησης ενεργοποίησης ολοκληρώθηκε με επιτυχία.')
        } catch (e: any) {
            if (e.response.data.message) {
                toastWarn(e.response.data.message)
            } else {
                toastError('Φαίνεται ότι η ενέργεια δεν ολοκληρώθηκε. Παρακαλούμε προσπαθήστε ξανά.')
            }
        } finally {
            setIsLoading(false)
        }

    }


    return (
        <div className={'personnel-list'}>

            <div className="search-wrapper row mb-3 gap-4">

                <div className="col">

                    <SearchBar
                        onSearch={(s) => {
                            setPersonnelParams({
                                ...personnelParams,
                                page: 1,
                                search: s
                            })
                        }}
                        value={personnelParams.search}
                        placeholder={`Αναζητήστε με βάση το Όνομα, το Επώνυμο ή την Οργανική Μονάδα`}>

                        <MakeCustomRadioSelect
                            placeholder={'Παρακαλώ επιλέξτε'}
                            theme={"search-listbox"}
                            value={personnelParams.filterBy}
                            handleChange={(value: string) => setPersonnelParams({
                                ...personnelParams,
                                staff_category: '',
                                gender: '',
                                unit: '',
                                filterBy: value

                            })}
                            options={filters.filterBy ?? []}
                        />


                        {/*@ts-ignore*/}
                        <MakeCustomRadioSelect value={personnelParams[personnelParams.filterBy] ?? ''}
                                               placeholder={'Παρακαλώ επιλέξτε'}
                                               theme={"search-listbox"}
                                               handleChange={(value: any) => setPersonnelParams({
                                                   ...personnelParams,
                                                   staff_category: '',
                                                   gender: '',
                                                   unit: '',
                                                   [personnelParams.filterBy]: value

                                               })}
                                               options={filters[personnelParams.filterBy] ?? []}
                        />


                    </SearchBar>
                </div>

                <div className="col-auto">
                    <CreateButton>
                        <AddUser></AddUser>
                        <p>ΠΡΟΣΘΗΚΗ ΕΡΓΑΖΟΜΕΝΟΥ</p>
                    </CreateButton>
                </div>

            </div>


            <div className={'mt-7'}>
                {
                    personnel && <DuaList
                        exportList={exportList}
                        pagination={{
                            meta: personnel.metadata,
                            setPage: (p) => setPersonnelParams({
                                ...personnelParams,
                                page: p
                            }),
                            setPerPage: (p) => setPersonnelParams({
                                ...personnelParams,
                                page: 1,
                                page_size: p
                            })
                        }}
                    >

                        {
                            personnel.records && personnel.records.map((employee) => {

                                return (
                                    <ListRow
                                        key={employee.id}
                                        _key={employee.id}
                                        hasTriangle={!Boolean(employee.isActiveDua)}
                                        status={'pending'}

                                    >
                                        <ListActions>
                                            <ul>
                                                <LinkWithRole to={`view/${employee.id}`}>
                                                    <li>Εμφάνιση Καρτέλας</li>
                                                </LinkWithRole>
                                                <LinkWithRole to={`edit/${employee.id}`}>
                                                    <li>Επεξεργασία Καρτέλας</li>
                                                </LinkWithRole>
                                                <LinkWithRole to={`view/${employee.id}/files_directory`}>
                                                    <li>Επισκόπηση Φακέλου</li>
                                                </LinkWithRole>

                                                {
                                                    employee.invitation_link_action === 'invite' &&

                                                    <li
                                                        className={isLoading ? "disabled" : ""}
                                                        onClick={() => !isLoading && setInvitationConfirmShow(employee)}
                                                    >Αποστολή Πρόσκλησης
                                                        Ενεργοποίησης</li>
                                                }

                                                {
                                                    employee.invitation_link_action === 're-invite' &&

                                                    <li
                                                        className={isLoading ? "disabled" : ""}
                                                        onClick={() => !isLoading && setInvitationConfirmShow(employee)}
                                                    >Επαναποστολή Πρόσκλησης
                                                        Ενεργοποίησης</li>
                                                }

                                                {
                                                    employee.invitation_link_action === 'copy' &&

                                                    <li onClick={() => navigator.clipboard.writeText(employee.invitation_link)}>Αντιγραφή
                                                        Συνδέσμου Ενεργοποίησης</li>
                                                }

                                            </ul>
                                        </ListActions>

                                        <TextColumn
                                            flex='0.5 0 70px'
                                            size='11px'
                                            align={'center'}
                                            label={"ΟΡΓΑΝΙΚΗ ΜΟΝΑΔΑ"}
                                            title={employee.default_unit}
                                        >
                                            <b>{employee.default_unit}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='0.5 0 70px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΚΩΔ. ΕΡΓΑΖΟΜEΝΟΥ`}
                                            title={employee.user_code}
                                        >
                                            <b>{employee.user_code}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='0.5 0 70px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΑΡΙΘ. ΦΑΚΕΛΟΥ`}
                                            title={employee.difo_code}
                                        >
                                            <b>{employee.difo_code}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='1.5 0 120px'
                                            size='11px'
                                            align={'left'}
                                            label={`ΟΝΟΜΑΤΕΠΩΝΥΜΟ`}
                                            title={employee.fullname}
                                        >
                                            <b>{employee.fullname}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='1 0 100px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΠΑΤΡΩΝΥΜΟ`}
                                            title={employee.father_name}
                                        >
                                            <b>{employee.father_name}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='0.5 0 80px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΑΦΜ`}
                                            title={showSensitive  ?  employee.afm  : '*********'}
                                        >
                                            <b>{showSensitive  ?  employee.afm  : '*********'}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='1.5 0 100px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΚΑΤΗΓΟΡΙΑ`}
                                            title={employee.staff_category}
                                        >
                                            <b>{employee.staff_category}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='1 0 80px'
                                            size='11px'
                                            align={'center'}
                                            label={`KINHTO ΤΗΛΕΦΩΝΟ`}
                                            title={employee.mobile}
                                        >
                                            <b>{employee.mobile}</b>
                                        </TextColumn>

                                        <TextColumn
                                            flex='1.5 0 120px'
                                            size='11px'
                                            align={'left'}
                                            label={`EMAIL`}
                                            title={employee.email}
                                        >
                                            {employee.email}
                                        </TextColumn>

                                        <TextColumn
                                            flex='1 0 70px'
                                            size='11px'
                                            align={'center'}
                                            label={`ΕΣΩΤ. ΤΗΛ.`}
                                            title={employee.phone}
                                        >
                                            <b>{employee.phone}</b>
                                        </TextColumn>



                                    </ListRow>
                                )
                            })}
                    </DuaList>
                }

            </div>

            {invitationConfirmShow && (
                <ConfirmationModal
                    FormButtonCancelText="ΑΚΥΡΩΣΗ"
                    FormButtonSubmitText="ΣΥΝΕΧΕΙΑ"
                    title={
                        invitationConfirmShow.invitation_link_action === 're-invite'
                            ? `Επαναποστολή Πρόσκλησης | ${invitationConfirmShow.fullname}`
                            : `Αποστολή Πρόσκλησης | ${invitationConfirmShow.fullname}`
                    }
                    text="Είστε σίγουρος/η πως θέλετε να προχωρήσετε στην αποστολή πρόσκλησης ενεργοποίησης;"
                    onClose={() => setInvitationConfirmShow(null)}
                    modalAction={async () => {
                        const employee = invitationConfirmShow;
                        setInvitationConfirmShow(null);
                        await handleSubmit(employee.hash_id);
                        fetchPersonnel();
                    }}
                    className="personnel-invitation-modal"
                />
            )}

        </div>
    );
}

export default PersonnelList;