import React, {FormEvent, useEffect, useRef, useState} from "react";
import CustomFormSection from "../../../UI/Forms/CustomFormSection/CustomFormSection";
import CustomLabel from "../../../UI/Forms/CustomLabel/CustomLabel";
import CustomSelect from "../../../UI/Forms/CustomSelect/CustomSelect";
import {AuthorizationForm} from "../../../../models/Settings/Authorization";
import useFormValidate from "../../../../hooks/useValidateForm";
import {toastWarn} from "../../../../services/toaster";
import ActionModal from "../../../UI/Modal/ActionsModal/ActionModal";
import PageTitle from "../../../UI/Typography/PageTitle";
import FormButtonSubmit from "../../../UI/Forms/FormButton/FormButtonSubmit";
import CloseButton from "../../../UI/CloseButton/CloseButton";
import {duaUsersEmails} from "../../../../API/dua";
import SelectItem from "../../../UI/Forms/CustomSelect/SelectItem";
import Typography from "../../../UI/Typography/Typography";
import {getMicroServices} from "../../../../API/settings";
import '../responsive-modals.scss';


type CreateModalProps = {
    onClose: () => void
    handleCreate: (formdata: AuthorizationForm) => void
}

const FormRules = {
    agent_id: {
        condition: (agent_id: number) => agent_id !== 0,
        message: 'Παρακαλώ Συμπληρώστε Σωστό email'
    },
    microservices: {
        condition: (e: any) => {
            if(e.length === 0) {
                return false;
            } else {
                return true;
            }
        },
        message: 'Παρακαλώ επιλέξτε τουλάχιστον μία υπηρεσία'
    },
}

const FormInit: AuthorizationForm = {
    agent_id: 0,
    microservices: [],
}

// only worth hitting the API once there's a local part AND an "@"
// e.g. "g@" fires, "@" alone or "george" alone does not
const isSearchableAgentQuery = (q: string) => q.indexOf('@') > 0

const CreateModal = ({onClose, handleCreate}: CreateModalProps) => {

    const [checkForErrors, formErrors] = useFormValidate(FormRules)
    const [formData, setFormData] = useState({...FormInit});
    const [selectData, setSelectData] = useState<any>({})
    const [agentQuery, setAgentQuery] = useState('')
    const [isSearchingAgents, setIsSearchingAgents] = useState(false)
    const [selectedAgent, setSelectedAgent] = useState<{id: number, email: string} | null>(null)
    const debounceRef = useRef<ReturnType<typeof setTimeout>>()

    const handleAuthorizationCreate = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        if (checkForErrors(formData)) {
            toastWarn('Συμπληρώστε όλα τα υποχρεωτικά πεδία σωστά.')
            return
        }
        handleCreate(formData)

    }

    // microservices list is small/static-ish, fetch it once on mount
    useEffect(() => {
        (async () => {
            try {
                const res2 = await getMicroServices()
                setSelectData((prev: any) => ({
                    ...prev,
                    'microservices': res2.data
                }))
            } catch (e) {
                console.error('CreateModal microservices fetch failed:', e);
            }
        })();
    }, [])

    // agent emails: only fetch once the user has typed something + "@", debounced
    useEffect(() => {
        if (debounceRef.current) {
            clearTimeout(debounceRef.current)
        }

        if (!isSearchableAgentQuery(agentQuery)) {
            setIsSearchingAgents(false)
            setSelectData((prev: any) => ({...prev, 'users': []}))
            return
        }

        setIsSearchingAgents(true)

        debounceRef.current = setTimeout(async () => {
            try {
                const res = await duaUsersEmails(agentQuery)
                setSelectData((prev: any) => ({
                    ...prev,
                    'users': res.data
                }))
            } catch (e) {
                console.error('CreateModal users fetch failed:', e);
            } finally {
                setIsSearchingAgents(false)
            }
        }, 350)

        return () => {
            if (debounceRef.current) {
                clearTimeout(debounceRef.current)
            }
        }
    }, [agentQuery])

    const agentEmptyMessage = !isSearchableAgentQuery(agentQuery)
        ? 'Πληκτρολογήστε ένα email για αναζήτηση'
        : isSearchingAgents
            ? 'Αναζήτηση...'
            : 'Δεν υπάρχουν αποτελέσματα'

    // the fetched search results get cleared once the query no longer matches
    // the "@" gate (e.g. right after picking one), so the picked agent has to be
    // pinned separately and merged back in, or CustomSelect has nothing left in
    // its children to recognise as "selected" and the field appears empty
    const agentOptions = (() => {
        const list = [...(selectData?.users || [])]
        if (selectedAgent && !list.some((u: any) => u.id === selectedAgent.id)) {
            list.unshift(selectedAgent)
        }
        return list
    })()


    return (
        <ActionModal onClose={onClose} customClass={'settings-modal'}>
            <div className='authorization-list-modal--header-container d-flex justify-content-between align-items-top'>
                <div><PageTitle>Δημιουργία Εξουσιοδότησης</PageTitle>
                    <Typography
                        tag={'p'}
                        fontSize={'16px'}
                        fontWeight={'200'}
                        letterSpacing={'0.3px'}
                        color={'$text-color'}
                    >
                        Η εξουσιοδότηση στον συνεργάτη σας, του δίνει πρόσβαση σε όλες τις υπογραφές που είναι
                        διαθέσιμες προς εξουσιοδότηση.
                    </Typography></div>
                <div>
                    <CloseButton onClick={onClose}/>
                </div>
            </div>
            <div className='authorization-list-modal--body-container'>
                <form onSubmit={handleAuthorizationCreate}>
                    <CustomFormSection theme={"default"}>
                        <div className="row">
                            <div className={'col-12 col-xl-6'}>
                                <CustomLabel>
                                    * EMAIL ΣΥΝΕΡΓΑΤΗ
                                </CustomLabel>
                                <CustomSelect
                                    clearable={true}
                                    searchable
                                    minSearch={0}
                                    value={formData.agent_id}
                                    onSearchChange={(q) => setAgentQuery(q)}
                                    emptyMessage={agentEmptyMessage}
                                    isLoading={isSearchingAgents}
                                    handleChange={(e) => {
                                        const picked = selectData?.users?.find((u: any) => u.id === e)
                                        setSelectedAgent(picked ?? null)
                                        setFormData({
                                            ...formData,
                                            agent_id: e
                                        })

                                    }}
                                >
                                    {
                                        agentOptions.map((u: any) =>
                                            <SelectItem key={u.id} value={u.id}>{u.email}</SelectItem>)
                                    }

                                </CustomSelect>

                            </div>
                            <div className={'col-12 col-xl-6'}><CustomLabel>
                                * ΕΠΙΛΕΞΤΕ ΥΠΗΡΕΣΙΕΣ
                            </CustomLabel>
                                <CustomSelect
                                    disabled={selectData?.microservices?.length <=1}
                                    multiple
                                    clearable
                                    hasError={formErrors?.microservices}
                                    value={formData.microservices}
                                    theme={"user-form-select"}
                                    handleChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            microservices: e
                                        })
                                    }}
                                >
                                    {
                                        selectData?.microservices?.map((ms:any)=>
                                            <SelectItem key={ms.value} value={ms.value}>{ms.name}</SelectItem>
                                        )
                                    }
                                </CustomSelect>
                            </div>
                        </div>
                    </CustomFormSection>
                    <div className={'buttons-container d-flex justify-content-center'}><FormButtonSubmit>Δημιουργία</FormButtonSubmit>
                    </div>

                </form>
            </div>
        </ActionModal>);
}

export default CreateModal;