import { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faClipboardQuestion, faXmark } from '@fortawesome/pro-duotone-svg-icons';
import { Input } from '@/components/base/input/input';
import { Select } from '@/components/base/select/select';
import { TextArea } from '@/components/base/textarea/textarea';
import { Checkbox } from '@/components/base/checkbox/checkbox';
import { Button } from '@/components/base/buttons/button';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';

type EnquiryFormProps = {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    callerPhone?: string | null;
    onSaved?: () => void;
};

const dispositionItems = [
    { id: 'CONVERTED', label: 'Converted' },
    { id: 'FOLLOW_UP', label: 'Follow-up Needed' },
    { id: 'GENERAL_QUERY', label: 'General Query' },
    { id: 'NO_ANSWER', label: 'No Answer' },
    { id: 'INVALID_NUMBER', label: 'Invalid Number' },
    { id: 'CALL_DROPPED', label: 'Call Dropped' },
];

export const EnquiryForm = ({ isOpen, onOpenChange, callerPhone, onSaved }: EnquiryFormProps) => {
    const [patientName, setPatientName] = useState('');
    const [source, setSource] = useState('Phone Inquiry');
    const [queryAsked, setQueryAsked] = useState('');
    const [isExisting, setIsExisting] = useState(false);
    const [registeredPhone, setRegisteredPhone] = useState(callerPhone ?? '');
    const [department, setDepartment] = useState<string | null>(null);
    const [doctor, setDoctor] = useState<string | null>(null);
    const [followUpNeeded, setFollowUpNeeded] = useState(false);
    const [followUpDate, setFollowUpDate] = useState('');
    const [disposition, setDisposition] = useState<string | null>(null);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Fetch doctors for department/doctor dropdowns
    const [doctors, setDoctors] = useState<Array<{ id: string; name: string; department: string }>>([]);

    useEffect(() => {
        if (!isOpen) return;
        apiClient.graphql<{ doctors: { edges: Array<{ node: any }> } }>(
            `{ doctors(first: 50) { edges { node {
                id name fullName { firstName lastName } department
            } } } }`,
        ).then(data => {
            setDoctors(data.doctors.edges.map(e => ({
                id: e.node.id,
                name: e.node.fullName ? `Dr. ${e.node.fullName.firstName} ${e.node.fullName.lastName}`.trim() : e.node.name,
                department: e.node.department ?? '',
            })));
        }).catch(() => {});
    }, [isOpen]);

    const departmentItems = [...new Set(doctors.map(d => d.department).filter(Boolean))]
        .map(dept => ({ id: dept, label: dept.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) }));

    const filteredDoctors = department ? doctors.filter(d => d.department === department) : doctors;
    const doctorItems = filteredDoctors.map(d => ({ id: d.id, label: d.name }));

    const handleSave = async () => {
        if (!patientName.trim() || !queryAsked.trim() || !disposition) {
            setError('Please fill in required fields: patient name, query, and disposition.');
            return;
        }

        setIsSaving(true);
        setError(null);

        try {
            // Create a lead with source PHONE_INQUIRY
            await apiClient.graphql(
                `mutation($data: LeadCreateInput!) { createLead(data: $data) { id } }`,
                {
                    data: {
                        name: `Enquiry — ${patientName}`,
                        contactName: { firstName: patientName.split(' ')[0], lastName: patientName.split(' ').slice(1).join(' ') || '' },
                        contactPhone: registeredPhone ? { primaryPhoneNumber: registeredPhone } : undefined,
                        source: 'PHONE_INQUIRY',
                        status: disposition === 'CONVERTED' ? 'CONVERTED' : 'NEW',
                        interestedService: queryAsked.substring(0, 100),
                    },
                },
            );

            // Create follow-up if needed
            if (followUpNeeded && followUpDate) {
                await apiClient.graphql(
                    `mutation($data: FollowUpCreateInput!) { createFollowUp(data: $data) { id } }`,
                    {
                        data: {
                            name: `Follow-up — ${patientName}`,
                            typeCustom: 'CALLBACK',
                            status: 'PENDING',
                            priority: 'NORMAL',
                            scheduledAt: new Date(`${followUpDate}T09:00:00`).toISOString(),
                        },
                    },
                    { silent: true },
                );
            }

            notify.success('Enquiry Logged', 'Contact details and query captured');
            onSaved?.();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to save enquiry');
        } finally {
            setIsSaving(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="rounded-xl border border-secondary bg-primary p-4">
            <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                    <div className="flex size-8 items-center justify-center rounded-lg bg-warning-secondary">
                        <FontAwesomeIcon icon={faClipboardQuestion} className="size-4 text-fg-warning-primary" />
                    </div>
                    <div>
                        <h3 className="text-sm font-semibold text-primary">Log Enquiry</h3>
                        <p className="text-xs text-tertiary">Capture caller's question and details</p>
                    </div>
                </div>
                <button
                    onClick={() => onOpenChange(false)}
                    className="flex size-7 items-center justify-center rounded-md text-fg-quaternary hover:text-fg-secondary hover:bg-primary_hover transition duration-100 ease-linear"
                >
                    <FontAwesomeIcon icon={faXmark} className="size-4" />
                </button>
            </div>

            <div className="flex flex-col gap-3">
                <Input label="Patient Name" placeholder="Full name" value={patientName} onChange={setPatientName} isRequired />

                <Input label="Source / Referral" placeholder="How did they reach us?" value={source} onChange={setSource} isRequired />

                <TextArea label="Query Asked" placeholder="What did the caller ask about?" value={queryAsked} onChange={setQueryAsked} rows={3} isRequired />

                <Checkbox isSelected={isExisting} onChange={setIsExisting} label="Existing Patient" hint="Has visited the hospital before" />

                {isExisting && (
                    <Input label="Registered Phone" placeholder="Phone number on file" value={registeredPhone} onChange={setRegisteredPhone} />
                )}

                <div className="border-t border-secondary" />

                <div className="grid grid-cols-2 gap-3">
                    <Select label="Department" placeholder="Optional" items={departmentItems} selectedKey={department}
                        onSelectionChange={(key) => { setDepartment(key as string); setDoctor(null); }}>
                        {(item) => <Select.Item id={item.id} label={item.label} />}
                    </Select>
                    <Select label="Doctor" placeholder="Optional" items={doctorItems} selectedKey={doctor}
                        onSelectionChange={(key) => setDoctor(key as string)} isDisabled={!department}>
                        {(item) => <Select.Item id={item.id} label={item.label} />}
                    </Select>
                </div>

                <Checkbox isSelected={followUpNeeded} onChange={setFollowUpNeeded} label="Follow-up Needed" />

                {followUpNeeded && (
                    <Input label="Follow-up Date" type="date" value={followUpDate} onChange={setFollowUpDate} isRequired />
                )}

                <Select label="Disposition" placeholder="Select outcome" items={dispositionItems} selectedKey={disposition}
                    onSelectionChange={(key) => setDisposition(key as string)} isRequired>
                    {(item) => <Select.Item id={item.id} label={item.label} />}
                </Select>

                {error && (
                    <div className="rounded-lg bg-error-primary p-3 text-sm text-error-primary">{error}</div>
                )}
            </div>

            <div className="flex items-center justify-end gap-3 mt-4 pt-4 border-t border-secondary">
                <Button size="sm" color="secondary" onClick={() => onOpenChange(false)}>Cancel</Button>
                <Button size="sm" color="primary" isLoading={isSaving} showTextWhileLoading onClick={handleSave}>
                    {isSaving ? 'Saving...' : 'Log Enquiry'}
                </Button>
            </div>
        </div>
    );
};
