"use client";

import * as React from "react";
import { AlertTriangle, Loader2, MapPin } from "lucide-react";
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  ensureClientGeoForLogin,
  hasPersistedClientGeo,
} from "@/lib/client-geo";
import { cn } from "@/lib/utils";

export type TransactionRemovePayload = {
  reason: string;
  confirmedName: string;
};

type TransactionRemoveDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: (payload: TransactionRemovePayload) => void | Promise<void>;
  transactionLabel: string;
  expectedUserName: string;
  isLoading?: boolean;
};

export function TransactionRemoveDialog({
  open,
  onOpenChange,
  onConfirm,
  transactionLabel,
  expectedUserName,
  isLoading = false,
}: TransactionRemoveDialogProps) {
  const [reason, setReason] = React.useState("");
  const [confirmedName, setConfirmedName] = React.useState("");
  const [geoReady, setGeoReady] = React.useState(false);
  const [geoLoading, setGeoLoading] = React.useState(false);

  const normalizedExpected = expectedUserName.trim().toLowerCase();
  const nameMatches =
    normalizedExpected.length > 0 &&
    confirmedName.trim().toLowerCase() === normalizedExpected;
  const reasonValid = reason.trim().length >= 3;
  const canSubmit = geoReady && nameMatches && reasonValid && !isLoading;

  React.useEffect(() => {
    if (!open) {
      setReason("");
      setConfirmedName("");
      setGeoReady(false);
      setGeoLoading(false);
      return;
    }

    let cancelled = false;
    setGeoLoading(true);
    void (async () => {
      if (!hasPersistedClientGeo()) {
        await ensureClientGeoForLogin();
      }
      if (!cancelled) {
        setGeoReady(hasPersistedClientGeo());
        setGeoLoading(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [open]);

  const handleOpenChange = (next: boolean) => {
    if (!next && isLoading) return;
    onOpenChange(next);
  };

  const handleRetryLocation = () => {
    setGeoLoading(true);
    void ensureClientGeoForLogin().finally(() => {
      setGeoReady(hasPersistedClientGeo());
      setGeoLoading(false);
    });
  };

  const handleConfirm = async () => {
    if (!canSubmit) return;
    try {
      await onConfirm({
        reason: reason.trim(),
        confirmedName: confirmedName.trim(),
      });
      onOpenChange(false);
    } catch {
      /* caller toast; keep dialog open */
    }
  };

  return (
    <AlertDialog open={open} onOpenChange={handleOpenChange}>
      <AlertDialogContent className="sm:max-w-[480px]">
        <AlertDialogHeader>
          <div className="mb-2 flex items-center gap-3">
            <div className="flex size-10 shrink-0 items-center justify-center rounded-full bg-red-100">
              <AlertTriangle className="size-5 text-red-600" aria-hidden />
            </div>
            <AlertDialogTitle className="text-lg font-bold">
              Remove transaction
            </AlertDialogTitle>
          </div>
          <AlertDialogDescription asChild>
            <div className="space-y-4 text-sm leading-relaxed text-[#575a62]">
              <p>
                This soft-deletes{" "}
                <span className="font-medium text-[#101828]">
                  {transactionLabel}
                </span>{" "}
                from the ledger. The row is kept for audit but excluded from
                reports, dashboards, and payment totals.
              </p>

              <div
                className={cn(
                  "flex items-start gap-2 rounded-lg border px-3 py-2 text-xs",
                  geoReady
                    ? "border-emerald-200 bg-emerald-50 text-emerald-900"
                    : "border-amber-200 bg-amber-50 text-amber-900",
                )}
              >
                <MapPin className="mt-0.5 size-4 shrink-0" aria-hidden />
                <div className="min-w-0 flex-1">
                  {geoLoading ? (
                    <span>Checking browser location…</span>
                  ) : geoReady ? (
                    <span>Location available — removal is allowed.</span>
                  ) : (
                    <span>
                      Browser location is required before removing a
                      transaction. Enable location access for this site, then
                      retry.
                    </span>
                  )}
                  {!geoReady && !geoLoading ? (
                    <Button
                      type="button"
                      variant="link"
                      className="mt-1 h-auto p-0 text-xs text-amber-900 underline"
                      onClick={handleRetryLocation}
                    >
                      Retry location
                    </Button>
                  ) : null}
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="tx-remove-reason">Reason for removal</Label>
                <Textarea
                  id="tx-remove-reason"
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  placeholder="Explain why this ledger row should be removed"
                  rows={3}
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="tx-remove-name">
                  Type your full name to confirm
                </Label>
                <Input
                  id="tx-remove-name"
                  value={confirmedName}
                  onChange={(e) => setConfirmedName(e.target.value)}
                  placeholder={expectedUserName || "Your full name"}
                  autoComplete="name"
                  disabled={isLoading}
                />
                {confirmedName.trim() && !nameMatches ? (
                  <p className="text-xs text-destructive">
                    Name must match your profile: {expectedUserName || "—"}
                  </p>
                ) : null}
              </div>
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter className="gap-2 sm:gap-2">
          <AlertDialogCancel disabled={isLoading} className="rounded-xl">
            Cancel
          </AlertDialogCancel>
          <Button
            type="button"
            onClick={() => void handleConfirm()}
            disabled={!canSubmit}
            className="rounded-xl bg-red-600 text-white hover:bg-red-700"
          >
            {isLoading ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" aria-hidden />
                Removing…
              </>
            ) : (
              "Remove transaction"
            )}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
