import { useState, useRef } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faPhone, faPhoneHangup, faMicrophone, faMicrophoneSlash,
    faPause, faPlay, faCalendarPlus, faCheckCircle,
    faPhoneArrowRight, faRecordVinyl, faClipboardQuestion,
} from '@fortawesome/pro-duotone-svg-icons';
import { Button } from '@/components/base/buttons/button';
import { Badge } from '@/components/base/badges/badges';
import { useSetAtom } from 'jotai';
import { sipCallStateAtom, sipCallerNumberAtom, sipCallUcidAtom } from '@/state/sip-state';
import { setOutboundPending } from '@/state/sip-manager';
import { useSip } from '@/providers/sip-provider';
import { DispositionForm } from './disposition-form';
import { AppointmentForm } from './appointment-form';
import { TransferDialog } from './transfer-dialog';
import { EnquiryForm } from './enquiry-form';
import { formatPhone } from '@/lib/format';
import { apiClient } from '@/lib/api-client';
import { cx } from '@/utils/cx';
import { notify } from '@/lib/toast';
import type { Lead, CallDisposition } from '@/types/entities';

type PostCallStage = 'disposition' | 'appointment' | 'follow-up' | 'done';

interface ActiveCallCardProps {
    lead: Lead | null;
    callerPhone: string;
    missedCallId?: string | null;
    onCallComplete?: () => void;
}

const formatDuration = (seconds: number): string => {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}:${s.toString().padStart(2, '0')}`;
};

export const ActiveCallCard = ({ lead, callerPhone, missedCallId, onCallComplete }: ActiveCallCardProps) => {
    const { callState, callDuration, callUcid, isMuted, isOnHold, answer, reject, hangup, toggleMute, toggleHold } = useSip();
    const setCallState = useSetAtom(sipCallStateAtom);
    const setCallerNumber = useSetAtom(sipCallerNumberAtom);
    const setCallUcid = useSetAtom(sipCallUcidAtom);
    const [postCallStage, setPostCallStage] = useState<PostCallStage | null>(null);
    const [savedDisposition, setSavedDisposition] = useState<CallDisposition | null>(null);
    const [appointmentOpen, setAppointmentOpen] = useState(false);
    const [appointmentBookedDuringCall, setAppointmentBookedDuringCall] = useState(false);
    const [transferOpen, setTransferOpen] = useState(false);
    const [recordingPaused, setRecordingPaused] = useState(false);
    const [enquiryOpen, setEnquiryOpen] = useState(false);
    // Capture direction at mount — survives through disposition stage
    const callDirectionRef = useRef(callState === 'ringing-out' ? 'OUTBOUND' : 'INBOUND');
    // Track if the call was ever answered (reached 'active' state)
    const wasAnsweredRef = useRef(callState === 'active');

    const firstName = lead?.contactName?.firstName ?? '';
    const lastName = lead?.contactName?.lastName ?? '';
    const fullName = `${firstName} ${lastName}`.trim();
    const phone = lead?.contactPhone?.[0];
    const phoneDisplay = phone ? formatPhone(phone) : callerPhone || 'Unknown';

    const handleDisposition = async (disposition: CallDisposition, notes: string) => {
        setSavedDisposition(disposition);

        // Submit disposition to sidecar — handles Ozonetel ACW release
        if (callUcid) {
            apiClient.post('/api/ozonetel/dispose', {
                ucid: callUcid,
                disposition,
                callerPhone,
                direction: callDirectionRef.current,
                durationSec: callDuration,
                leadId: lead?.id ?? null,
                notes,
                missedCallId: missedCallId ?? undefined,
            }).catch((err) => console.warn('Disposition failed:', err));
        }

        if (disposition === 'APPOINTMENT_BOOKED') {
            setPostCallStage('appointment');
            setAppointmentOpen(true);
        } else if (disposition === 'FOLLOW_UP_SCHEDULED') {
            setPostCallStage('follow-up');
            // Create follow-up
            try {
                await apiClient.graphql(`mutation($data: FollowUpCreateInput!) { createFollowUp(data: $data) { id } }`, {
                    data: {
                        name: `Follow-up — ${fullName || phoneDisplay}`,
                        typeCustom: 'CALLBACK',
                        status: 'PENDING',
                        assignedAgent: null,
                        priority: 'NORMAL',
                        scheduledAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
                    },
                }, { silent: true });
                notify.success('Follow-up Created', 'Callback scheduled for tomorrow');
            } catch {
                notify.info('Follow-up', 'Could not auto-create follow-up');
            }
            setPostCallStage('done');
        } else {
            notify.success('Call Logged', `Disposition: ${disposition.replace(/_/g, ' ').toLowerCase()}`);
            setPostCallStage('done');
        }
    };

    const handleAppointmentSaved = () => {
        setAppointmentOpen(false);
        notify.success('Appointment Booked', 'Payment link will be sent to the patient');
        // If booked during active call, don't skip to 'done' — wait for disposition after call ends
        if (callState === 'active') {
            setAppointmentBookedDuringCall(true);
        } else {
            setPostCallStage('done');
        }
    };

    const handleReset = () => {
        setPostCallStage(null);
        setSavedDisposition(null);
        setCallState('idle');
        setCallerNumber(null);
        setCallUcid(null);
        setOutboundPending(false);
        onCallComplete?.();
    };

    // Outbound ringing — agent initiated the call
    if (callState === 'ringing-out') {
        return (
            <div className="rounded-xl bg-brand-primary p-4">
                <div className="flex items-center gap-3">
                    <div className="relative">
                        <div className="absolute inset-0 animate-pulse rounded-full bg-brand-solid opacity-20" />
                        <div className="relative flex size-10 items-center justify-center rounded-full bg-brand-solid">
                            <FontAwesomeIcon icon={faPhone} className="size-4 text-white" />
                        </div>
                    </div>
                    <div className="min-w-0 flex-1">
                        <p className="text-xs font-bold uppercase tracking-wider text-brand-secondary">Calling...</p>
                        <p className="text-lg font-bold text-primary">{fullName || phoneDisplay}</p>
                        {fullName && <p className="text-sm text-secondary">{phoneDisplay}</p>}
                    </div>
                </div>
                <div className="mt-3 flex gap-2">
                    <Button size="sm" color="primary-destructive" onClick={() => { hangup(); handleReset(); }}>
                        End Call
                    </Button>
                </div>
            </div>
        );
    }

    // Inbound ringing
    if (callState === 'ringing-in') {
        return (
            <div className="rounded-xl bg-brand-primary p-4">
                <div className="flex items-center gap-3">
                    <div className="relative">
                        <div className="absolute inset-0 animate-ping rounded-full bg-brand-solid opacity-20" />
                        <div className="relative flex size-10 items-center justify-center rounded-full bg-brand-solid">
                            <FontAwesomeIcon icon={faPhone} className="size-4 text-white animate-bounce" />
                        </div>
                    </div>
                    <div className="min-w-0 flex-1">
                        <p className="text-xs font-bold uppercase tracking-wider text-brand-secondary">Incoming Call</p>
                        <p className="text-lg font-bold text-primary">{fullName || phoneDisplay}</p>
                        {fullName && <p className="text-sm text-secondary">{phoneDisplay}</p>}
                    </div>
                </div>
                <div className="mt-3 flex gap-2">
                    <Button size="sm" color="primary" onClick={answer}>Answer</Button>
                    <Button size="sm" color="tertiary-destructive" onClick={reject}>Decline</Button>
                </div>
            </div>
        );
    }

    // Skip disposition for unanswered calls (ringing-in → ended without ever reaching active)
    if (!wasAnsweredRef.current && postCallStage === null && (callState === 'ended' || callState === 'failed')) {
        return (
            <div className="rounded-xl border border-secondary bg-primary p-4 text-center">
                <FontAwesomeIcon icon={faPhoneHangup} className="size-6 text-fg-quaternary mb-2" />
                <p className="text-sm font-semibold text-primary">Missed Call</p>
                <p className="text-xs text-tertiary mt-1">{phoneDisplay} — not answered</p>
                <Button size="sm" color="secondary" className="mt-3" onClick={handleReset}>
                    Back to Worklist
                </Button>
            </div>
        );
    }

    // Post-call flow takes priority over active state (handles race between hangup + SIP ended event)
    if (postCallStage !== null || callState === 'ended' || callState === 'failed') {
        // Done state
        if (postCallStage === 'done') {
            return (
                <div className="rounded-xl border border-success bg-success-primary p-4 text-center">
                    <FontAwesomeIcon icon={faCheckCircle} className="size-8 text-fg-success-primary mb-2" />
                    <p className="text-sm font-semibold text-success-primary">Call Completed</p>
                    <p className="text-xs text-tertiary mt-1">
                        {savedDisposition ? savedDisposition.replace(/_/g, ' ').toLowerCase() : 'logged'}
                    </p>
                    <Button size="sm" color="secondary" className="mt-3" onClick={handleReset}>
                        Back to Worklist
                    </Button>
                </div>
            );
        }

        // Appointment booking after disposition — auto-return when form closes
        if (postCallStage === 'appointment') {
            return (
                <>
                    <div className="rounded-xl border border-brand bg-brand-primary p-4 text-center">
                        <FontAwesomeIcon icon={faCalendarPlus} className="size-6 text-fg-brand-primary mb-2" />
                        <p className="text-sm font-semibold text-brand-secondary">Booking Appointment</p>
                        <p className="text-xs text-tertiary mt-1">for {fullName || phoneDisplay}</p>
                        <Button size="sm" color="secondary" className="mt-2" onClick={() => setPostCallStage('done')}>
                            Skip & Return to Worklist
                        </Button>
                    </div>
                    <AppointmentForm
                        isOpen={appointmentOpen}
                        onOpenChange={(open) => {
                            setAppointmentOpen(open);
                            if (!open) setPostCallStage('done');
                        }}
                        callerNumber={callerPhone}
                        leadName={fullName || null}
                        leadId={lead?.id ?? null}
                        patientId={(lead as any)?.patientId ?? null}
                        onSaved={handleAppointmentSaved}
                    />
                </>
            );
        }

        // Disposition form + enquiry access
        return (
            <>
                <div className="rounded-xl border border-secondary bg-primary p-4">
                    <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                            <div className="flex size-8 items-center justify-center rounded-full bg-secondary">
                                <FontAwesomeIcon icon={faPhoneHangup} className="size-3.5 text-fg-quaternary" />
                            </div>
                            <div>
                                <p className="text-sm font-semibold text-primary">Call Ended — {fullName || phoneDisplay}</p>
                                <p className="text-xs text-tertiary">{formatDuration(callDuration)} · Log this call</p>
                            </div>
                        </div>
                        <Button size="sm" color="secondary"
                            iconLeading={({ className, ...rest }: any) => <FontAwesomeIcon icon={faClipboardQuestion} className={className} {...rest} />}
                            onClick={() => setEnquiryOpen(!enquiryOpen)}>Enquiry</Button>
                    </div>
                    <DispositionForm onSubmit={handleDisposition} defaultDisposition={appointmentBookedDuringCall ? 'APPOINTMENT_BOOKED' : null} />
                </div>
                <EnquiryForm
                    isOpen={enquiryOpen}
                    onOpenChange={setEnquiryOpen}
                    callerPhone={callerPhone}
                    onSaved={() => {
                        setEnquiryOpen(false);
                        notify.success('Enquiry Logged');
                    }}
                />
            </>
        );
    }

    // Active call
    if (callState === 'active') {
        wasAnsweredRef.current = true;
        return (
            <div className="rounded-xl border border-brand bg-primary p-4">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-full bg-success-solid">
                            <FontAwesomeIcon icon={faPhone} className="size-4 text-white" />
                        </div>
                        <div>
                            <p className="text-sm font-bold text-primary">{fullName || phoneDisplay}</p>
                            {fullName && <p className="text-xs text-tertiary">{phoneDisplay}</p>}
                        </div>
                    </div>
                    <Badge size="md" color="success" type="pill-color">{formatDuration(callDuration)}</Badge>
                </div>
                <div className="mt-3 flex items-center gap-1.5">
                    {/* Icon-only toggles */}
                    <button
                        onClick={toggleMute}
                        title={isMuted ? 'Unmute' : 'Mute'}
                        className={cx(
                            'flex size-8 items-center justify-center rounded-lg transition duration-100 ease-linear',
                            isMuted ? 'bg-error-solid text-white' : 'bg-secondary text-fg-quaternary hover:bg-secondary_hover hover:text-fg-secondary',
                        )}
                    >
                        <FontAwesomeIcon icon={isMuted ? faMicrophoneSlash : faMicrophone} className="size-3.5" />
                    </button>
                    <button
                        onClick={toggleHold}
                        title={isOnHold ? 'Resume' : 'Hold'}
                        className={cx(
                            'flex size-8 items-center justify-center rounded-lg transition duration-100 ease-linear',
                            isOnHold ? 'bg-warning-solid text-white' : 'bg-secondary text-fg-quaternary hover:bg-secondary_hover hover:text-fg-secondary',
                        )}
                    >
                        <FontAwesomeIcon icon={isOnHold ? faPlay : faPause} className="size-3.5" />
                    </button>
                    <button
                        onClick={() => {
                            const action = recordingPaused ? 'unPause' : 'pause';
                            if (callUcid) apiClient.post('/api/ozonetel/recording', { ucid: callUcid, action }).catch(() => {});
                            setRecordingPaused(!recordingPaused);
                        }}
                        title={recordingPaused ? 'Resume Recording' : 'Pause Recording'}
                        className={cx(
                            'flex size-8 items-center justify-center rounded-lg transition duration-100 ease-linear',
                            recordingPaused ? 'bg-error-solid text-white' : 'bg-secondary text-fg-quaternary hover:bg-secondary_hover hover:text-fg-secondary',
                        )}
                    >
                        <FontAwesomeIcon icon={faRecordVinyl} className="size-3.5" />
                    </button>

                    <div className="w-px h-6 bg-secondary mx-0.5" />

                    {/* Text+Icon primary actions */}
                    <Button size="sm" color="secondary"
                        iconLeading={({ className, ...rest }: any) => <FontAwesomeIcon icon={faCalendarPlus} className={className} {...rest} />}
                        onClick={() => setAppointmentOpen(true)}>Book Appt</Button>
                    <Button size="sm" color="secondary"
                        iconLeading={({ className, ...rest }: any) => <FontAwesomeIcon icon={faClipboardQuestion} className={className} {...rest} />}
                        onClick={() => setEnquiryOpen(!enquiryOpen)}>Enquiry</Button>
                    <Button size="sm" color="secondary"
                        iconLeading={({ className, ...rest }: any) => <FontAwesomeIcon icon={faPhoneArrowRight} className={className} {...rest} />}
                        onClick={() => setTransferOpen(!transferOpen)}>Transfer</Button>
                    <Button size="sm" color="primary-destructive" className="ml-auto"
                        iconLeading={({ className, ...rest }: any) => <FontAwesomeIcon icon={faPhoneHangup} className={className} {...rest} />}
                        onClick={() => { hangup(); setPostCallStage('disposition'); }}>End</Button>
                </div>

                {/* Transfer dialog */}
                {transferOpen && callUcid && (
                    <TransferDialog
                        ucid={callUcid}
                        onClose={() => setTransferOpen(false)}
                        onTransferred={() => {
                            setTransferOpen(false);
                            hangup();
                            setPostCallStage('disposition');
                        }}
                    />
                )}

                {/* Appointment form accessible during call */}
                <AppointmentForm
                    isOpen={appointmentOpen}
                    onOpenChange={setAppointmentOpen}
                    callerNumber={callerPhone}
                    leadName={fullName || null}
                    leadId={lead?.id ?? null}
                    patientId={(lead as any)?.patientId ?? null}
                    onSaved={handleAppointmentSaved}
                />

                {/* Enquiry form */}
                <EnquiryForm
                    isOpen={enquiryOpen}
                    onOpenChange={setEnquiryOpen}
                    callerPhone={callerPhone}
                    onSaved={() => {
                        setEnquiryOpen(false);
                        notify.success('Enquiry Logged');
                    }}
                />
            </div>
        );
    }

    return null;
};
