import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CheckCircle, LoaderCircleIcon, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAppDispatch } from "@/redux/hooks";
import { setTaskStatus } from "@/redux/slices/seleniumTaskSlice";
import { formatLocalDate } from "@/utils/dateUtils";
import { socket } from "@/lib/socket";
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
function BcbsMaOtpModal({ open, onClose, onSubmit, isSubmitting }) {
    const [otp, setOtp] = useState("");
    useEffect(() => {
        if (!open)
            setOtp("");
    }, [open]);
    if (!open)
        return null;
    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!otp.trim())
            return;
        await onSubmit(otp.trim());
    };
    return (<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white dark:bg-slate-900 rounded-xl shadow-lg w-full max-w-md p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold">Enter OTP — BCBS MA</h2>
          <button type="button" onClick={onClose} className="text-slate-500 hover:text-slate-800">
            <X className="w-4 h-4"/>
          </button>
        </div>
        <p className="text-sm text-slate-500 mb-4">
          Enter the last 6 digits of the one-time verification code sent by the BCBS MA Provider
          Central portal to your registered email. The email shows a code like{" "}
          <span className="font-mono font-medium">XXXX-XXXXXX</span> — enter only the last 6 digits.
        </p>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="bcbs-ma-otp">Last 6 digits of OTP</Label>
            <Input id="bcbs-ma-otp" placeholder="e.g. 482913" value={otp} onChange={(e) => setOtp(e.target.value)} maxLength={6} autoFocus/>
          </div>
          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={onClose} disabled={isSubmitting}>
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting || !otp.trim()}>
              {isSubmitting ? (<>
                  <LoaderCircleIcon className="w-4 h-4 mr-2 animate-spin"/>
                  Submitting...
                </>) : ("Submit OTP")}
            </Button>
          </div>
        </form>
      </div>
    </div>);
}
export function BcbsMaEligibilityButton({ memberId, dateOfBirth, firstName, lastName, isFormIncomplete, autoTrigger, onAutoTriggered, onPdfReady, }) {
    const { toast } = useToast();
    const dispatch = useAppDispatch();
    const sessionIdRef = useRef(null);
    const autoTriggeredRef = useRef(false);
    const [otpModalOpen, setOtpModalOpen] = useState(false);
    const [isStarting, setIsStarting] = useState(false);
    const [isSubmittingOtp, setIsSubmittingOtp] = useState(false);
    const handleStart = async () => {
        if (!memberId || !dateOfBirth) {
            toast({
                title: "Missing fields",
                description: "Member ID and Date of Birth are required.",
                variant: "destructive",
            });
            return;
        }
        const formattedDob = formatLocalDate(dateOfBirth);
        const payload = {
            memberId,
            dateOfBirth: formattedDob,
            firstName,
            lastName,
            insuranceSiteKey: "BCBS_MA",
        };
        setIsStarting(true);
        try {
            dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Starting BCBS MA eligibility check…" }));
            const response = await apiRequest("POST", "/api/insurance-status-bcbs-ma/bcbs-ma-eligibility", { data: JSON.stringify(payload), socketId: socket.id });
            const result = await response.json();
            if (!response.ok || result.error) {
                throw new Error(result.error || `Server error (${response.status})`);
            }
            const jobId = result.jobId;
            if (!jobId)
                throw new Error("No jobId returned from server");
            dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "BCBS MA job queued. Opening browser…" }));
            const onSessionStarted = (data) => {
                if (String(data?.jobId) !== String(jobId))
                    return;
                sessionIdRef.current = data.session_id ?? null;
                dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Browser started. Waiting for OTP…" }));
            };
            const onOtpRequired = (data) => {
                if (String(data?.jobId) !== String(jobId))
                    return;
                if (data.session_id)
                    sessionIdRef.current = data.session_id;
                setOtpModalOpen(true);
                dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "OTP required for BCBS MA. Please enter the code." }));
            };
            const onOtpSubmitted = (data) => {
                if (data?.session_id && data.session_id !== sessionIdRef.current)
                    return;
                dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "OTP submitted. Finishing BCBS MA eligibility check…" }));
            };
            function cleanup() {
                socket.off("selenium:bcbs_ma_session_started", onSessionStarted);
                socket.off("selenium:otp_required", onOtpRequired);
                socket.off("selenium:otp_submitted", onOtpSubmitted);
                socket.off("job:update", onJobUpdate);
            }
            const safetyTimer = setTimeout(() => {
                cleanup();
                setIsStarting(false);
                setOtpModalOpen(false);
                dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: "BCBS MA job timed out." }));
            }, 10 * 60 * 1000);
            const onJobUpdate = (data) => {
                if (String(data?.jobId) !== String(jobId))
                    return;
                if (data.status === "active") {
                    dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: data.message ?? "Browser starting…" }));
                    return;
                }
                clearTimeout(safetyTimer);
                cleanup();
                if (data.status === "completed") {
                    dispatch(setTaskStatus({ key: "eligibilityCheck", status: "success", message: "BCBS MA eligibility updated and PDF saved." }));
                    toast({ title: "BCBS MA eligibility complete", description: "Patient status was updated and the eligibility PDF was saved." });
                    queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
                    const pdfId = data.result?.pdfFileId;
                    if (pdfId) {
                        onPdfReady(Number(pdfId), data.result?.pdfFilename ?? `eligibility_bcbs_ma_${memberId}.pdf`);
                    }
                }
                else if (data.status === "failed") {
                    const msg = data.error ?? "BCBS MA eligibility job failed.";
                    dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: msg }));
                    toast({ title: "BCBS MA selenium error", description: msg, variant: "destructive" });
                }
                setIsStarting(false);
                setOtpModalOpen(false);
            };
            socket.on("selenium:bcbs_ma_session_started", onSessionStarted);
            socket.on("selenium:otp_required", onOtpRequired);
            socket.on("selenium:otp_submitted", onOtpSubmitted);
            socket.on("job:update", onJobUpdate);
        }
        catch (err) {
            console.error("BcbsMaEligibilityButton error:", err);
            dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: err?.message || "Failed to start BCBS MA eligibility" }));
            toast({ title: "BCBS MA selenium error", description: err?.message || "Failed to start BCBS MA eligibility", variant: "destructive" });
            setIsStarting(false);
        }
    };
    const handleSubmitOtp = async (otp) => {
        const sessionId = sessionIdRef.current;
        if (!sessionId) {
            toast({ title: "Session not ready", description: "Cannot submit OTP — session ID not yet available.", variant: "destructive" });
            return;
        }
        try {
            setIsSubmittingOtp(true);
            const resp = await apiRequest("POST", "/api/insurance-status-bcbs-ma/selenium/submit-otp", {
                session_id: sessionId,
                otp,
                socketId: socket.id,
            });
            const data = await resp.json();
            if (!resp.ok || data.error)
                throw new Error(data.error || "Failed to submit OTP");
            setOtpModalOpen(false);
        }
        catch (err) {
            toast({ title: "Failed to submit OTP", description: err?.message || "Error forwarding OTP to selenium agent", variant: "destructive" });
        }
        finally {
            setIsSubmittingOtp(false);
        }
    };
    useEffect(() => {
        if (!autoTrigger || autoTriggeredRef.current || isFormIncomplete)
            return;
        autoTriggeredRef.current = true;
        onAutoTriggered?.();
        handleStart();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [autoTrigger, isFormIncomplete]);
    return (<>
      <Button className="w-full" variant="default" disabled={isFormIncomplete || isStarting} onClick={handleStart}>
        {isStarting ? (<>
            <LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin"/>
            Processing...
          </>) : (<>
            <CheckCircle className="h-4 w-4 mr-2"/>
            BCBS MA
          </>)}
      </Button>

      <BcbsMaOtpModal open={otpModalOpen} onClose={() => setOtpModalOpen(false)} onSubmit={handleSubmitOtp} isSubmitting={isSubmittingOtp}/>
    </>);
}
