"use client"

import * as React from "react"
import { format } from "date-fns"
import { Briefcase, CheckCircle2, Clock, XCircle } from "lucide-react"
import { toast } from "sonner"
import type { Deal } from "@/components/deals/types"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
    useCreateLeadMeetingMutation,
    usePatchDiscoveryMeetingVerificationMutation,
} from "@/api/rtk/deals-api"
import { isDiscoveryMeetingVerifiedForBusinessDeal } from "@/lib/deal-stage-labels"
import {
    canVerifyClientMeetingVerification,
    hasPermission,
    type PermissionSource,
} from "@/lib/permissions"
import { DateTimePicker } from "@/components/ui/date-time-picker"
import { ReactSelect } from "@/components/ui/react-select"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
    buildLeadMeetingNotes,
    LEAD_MEETING_MEDIUM_OPTIONS,
    formatLeadMeetingMediumLabel,
    toLeadMeetingDateIso,
    type LeadMeetingMedium,
} from "@/lib/lead-meeting-medium"

export type DiscoveryMeetingBookedAlertProps = {
    deal: Deal
    canCreateBusinessDeal: boolean
    onCreateBusinessDeal: () => void
    permissionSource: PermissionSource | null | undefined
    /** Refetch deal detail after QA saves attendance (e.g. parent `useGetDealQuery` refetch). */
    onAfterVerify?: () => void
    className?: string
}

function DiscoveryMeetingVerificationStatus({
    showup,
    verifiedAt,
    verifiedByName,
}: {
    showup: boolean | null | undefined
    verifiedAt?: string | null
    verifiedByName?: string | null
}) {
    return (
        <div className="flex flex-wrap items-center gap-2">
            {showup === true ? (
                <Badge className="bg-emerald-100 text-emerald-800 hover:bg-emerald-100">
                    <CheckCircle2 className="mr-1 size-3" />
                    Client showed up
                </Badge>
            ) : showup === false ? (
                <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
                    <XCircle className="mr-1 size-3" />
                    No show
                </Badge>
            ) : (
                <Badge
                    variant="secondary"
                    className="bg-gray-100 text-gray-600"
                >
                    <Clock className="mr-1 size-3" />
                    Awaiting QA verification
                </Badge>
            )}
            {verifiedAt ? (
                <span className="text-[10px] text-gray-400">
                    Verified{" "}
                    {format(new Date(verifiedAt), "MMM d, h:mm a")}
                    {verifiedByName ? ` by ${verifiedByName}` : ""}
                </span>
            ) : null}
        </div>
    )
}

export function DiscoveryMeetingBookedAlert({
    deal,
    canCreateBusinessDeal,
    onCreateBusinessDeal,
    permissionSource,
    onAfterVerify,
    className,
}: DiscoveryMeetingBookedAlertProps) {
    const [patchVerification, { isLoading: verifying }] =
        usePatchDiscoveryMeetingVerificationMutation()
    const [createLeadMeeting, { isLoading: savingMeeting }] =
        useCreateLeadMeetingMutation()

    const [backfillDate, setBackfillDate] = React.useState<string | undefined>()
    const [backfillMedium, setBackfillMedium] = React.useState<
        LeadMeetingMedium | ""
    >("")
    const [backfillOtherMedium, setBackfillOtherMedium] = React.useState("")
    const [backfillNotes, setBackfillNotes] = React.useState("")

    const canVerifyQa = canVerifyClientMeetingVerification(permissionSource)
    const canBackfillMeeting = hasPermission(permissionSource, "UPDATE", "LEAD")
    const meeting = deal.latestLeadMeeting

    const showup = deal.discoveryMeetingClientShowup
    const verifiedAt = deal.discoveryMeetingVerifiedAt
    const qaVerifiedForDeal =
        isDiscoveryMeetingVerifiedForBusinessDeal(deal)
    const canCreateDeal =
        canCreateBusinessDeal && qaVerifiedForDeal

    const qaVerificationResolved = showup != null

    const handleBackfillMeeting = async () => {
        const backfillDateIso = toLeadMeetingDateIso(backfillDate)
        if (!backfillDateIso) {
            toast.error("Meeting date and time are required")
            return
        }
        if (!backfillMedium) {
            toast.error("Meeting medium is required")
            return
        }
        if (backfillMedium === "OTHER" && !backfillOtherMedium.trim()) {
            toast.error("Please specify the meeting medium")
            return
        }
        const meetingNotes = buildLeadMeetingNotes({
            medium: backfillMedium,
            otherMediumDetail: backfillOtherMedium,
            notes: backfillNotes,
        })
        try {
            await createLeadMeeting({
                id: deal.id,
                body: {
                    meetingDate: backfillDateIso,
                    medium: backfillMedium,
                    ...(meetingNotes ? { notes: meetingNotes } : {}),
                },
            }).unwrap()
            setBackfillDate(undefined)
            setBackfillMedium("")
            setBackfillOtherMedium("")
            setBackfillNotes("")
            onAfterVerify?.()
            toast.success("Meeting details saved")
        } catch {
            toast.error("Could not save meeting details")
        }
    }

    const handleVerify = async (clientShowup: boolean) => {
        try {
            await patchVerification({ id: deal.id, clientShowup }).unwrap()
            onAfterVerify?.()
            toast.success(
                clientShowup
                    ? "Marked as client showed up"
                    : "Marked as no-show",
            )
        } catch {
            toast.error("Could not save verification")
        }
    }

    return (
        <div className={className}>
            <Alert variant="info" className="rounded-2xl border shadow-sm">
                <Briefcase className="size-4 shrink-0" aria-hidden />
                <AlertTitle>Discovery meeting booked</AlertTitle>
                <AlertDescription className="flex flex-col gap-3">
                    {meeting ? (
                        <div className="rounded-xl border border-gray-200/80 bg-white/60 px-3 py-2 text-sm text-gray-700">
                            <span className="font-medium text-gray-900">
                                Scheduled meeting:{" "}
                            </span>
                            {format(new Date(meeting.meetingDate), "MMM d, yyyy h:mm a")}
                            {" · "}
                            {formatLeadMeetingMediumLabel(
                                meeting.medium,
                                meeting.notes,
                            )}
                        </div>
                    ) : canBackfillMeeting ? (
                        <div className="space-y-3 rounded-xl border border-dashed border-gray-200 bg-white/60 p-3">
                            <p className="text-xs text-gray-500">
                                Add meeting date and medium for this lead (optional
                                for leads already in this stage).
                            </p>
                            <div className="grid gap-3 sm:grid-cols-2">
                                <div>
                                    <label className="mb-1 block text-[10px] font-medium uppercase tracking-wide text-gray-400">
                                        Meeting date & time
                                    </label>
                                    <DateTimePicker
                                        value={backfillDate}
                                        onChange={setBackfillDate}
                                    />
                                </div>
                                <div>
                                    <label className="mb-1 block text-[10px] font-medium uppercase tracking-wide text-gray-400">
                                        Medium
                                    </label>
                                    <ReactSelect
                                        value={backfillMedium}
                                        onValueChange={(v) => {
                                            const next = v as LeadMeetingMedium
                                            setBackfillMedium(next)
                                            if (next !== "OTHER") {
                                                setBackfillOtherMedium("")
                                            }
                                        }}
                                        options={LEAD_MEETING_MEDIUM_OPTIONS}
                                        placeholder="Select medium"
                                    />
                                </div>
                            </div>
                            {backfillMedium === "OTHER" ? (
                                <div>
                                    <label className="mb-1 block text-[10px] font-medium uppercase tracking-wide text-gray-400">
                                        Specify medium *
                                    </label>
                                    <Input
                                        value={backfillOtherMedium}
                                        onChange={(e) =>
                                            setBackfillOtherMedium(e.target.value)
                                        }
                                        placeholder="e.g. Webex, WhatsApp call, Skype"
                                        className="text-sm"
                                    />
                                </div>
                            ) : null}
                            <div>
                                <label className="mb-1 block text-[10px] font-medium uppercase tracking-wide text-gray-400">
                                    Notes (optional)
                                </label>
                                <Textarea
                                    value={backfillNotes}
                                    onChange={(e) => setBackfillNotes(e.target.value)}
                                    rows={2}
                                    className="resize-none text-sm"
                                />
                            </div>
                            <Button
                                type="button"
                                size="sm"
                                variant="outline"
                                disabled={savingMeeting}
                                onClick={handleBackfillMeeting}
                            >
                                Save meeting details
                            </Button>
                        </div>
                    ) : null}

                    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <span className="text-sm text-gray-600">
                            Continue on the Deal pipeline: we&apos;ll copy this
                            lead&apos;s contact details into the new deal form.
                        </span>
                        <div className="flex shrink-0 flex-col items-stretch gap-2 sm:items-end">
                            {!canCreateBusinessDeal && (
                                <span className="text-center text-xs text-gray-500 sm:text-right">
                                    You need permission to create deals to use
                                    this action.
                                </span>
                            )}
                            {canCreateBusinessDeal && !qaVerifiedForDeal && (
                                <span className="text-center text-xs text-amber-700 sm:text-right">
                                    {showup === false
                                        ? "Business deal cannot be created after a no-show."
                                        : "QA must verify the client showed up before creating a business deal."}
                                </span>
                            )}
                            <Button
                                type="button"
                                variant="accentAlertCta"
                                disabled={!canCreateDeal}
                                onClick={() => {
                                    if (!canCreateBusinessDeal) {
                                        toast.error(
                                            "You don't have permission to create deals.",
                                        )
                                        return
                                    }
                                    if (!qaVerifiedForDeal) {
                                        toast.error(
                                            showup === false
                                                ? "Cannot create a business deal after a no-show."
                                                : "Awaiting QA verification before a business deal can be created.",
                                        )
                                        return
                                    }
                                    onCreateBusinessDeal()
                                }}
                            >
                                <Briefcase className="mr-2 size-4" />
                                Create new business deal
                            </Button>
                        </div>
                    </div>

                    {canVerifyQa && showup === false ? (
                        <div className="border-t border-gray-200/80 pt-3 space-y-2">
                            <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
                                QA / compliance verification
                            </p>
                            <DiscoveryMeetingVerificationStatus
                                showup={showup}
                                verifiedAt={verifiedAt}
                                verifiedByName={
                                    deal.discoveryMeetingVerifiedBy?.name
                                }
                            />
                        </div>
                    ) : null}

                    {canVerifyQa && !qaVerificationResolved ? (
                        <div className="border-t border-gray-200/80 pt-3 space-y-3">
                            <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
                                QA / compliance verification
                            </p>

                            <DiscoveryMeetingVerificationStatus
                                showup={showup}
                                verifiedAt={verifiedAt}
                                verifiedByName={
                                    deal.discoveryMeetingVerifiedBy?.name
                                }
                            />

                            <div className="flex flex-wrap gap-2">
                                <Button
                                    type="button"
                                    size="sm"
                                    variant="outline"
                                    className="text-xs"
                                    disabled={verifying}
                                    onClick={() => handleVerify(true)}
                                >
                                    <CheckCircle2 className="mr-1 size-3" />
                                    Client showed up
                                </Button>
                                <Button
                                    type="button"
                                    size="sm"
                                    variant="outline"
                                    className="text-xs"
                                    disabled={verifying}
                                    onClick={() => handleVerify(false)}
                                >
                                    <XCircle className="mr-1 size-3" />
                                    No show
                                </Button>
                            </div>
                        </div>
                    ) : null}
                </AlertDescription>
            </Alert>
        </div>
    )
}
