"use client";

/**
 * ID Verification Page
 *
 * This is a standalone page that can be accessed directly or from checkout flows.
 * For checkout flows, it accepts a returnTo query parameter to navigate back.
 *
 * The main verification UI is now integrated into the Profile/Settings page.
 * This page is kept for:
 * - Direct URL access
 * - Checkout flow redirects with returnTo parameter
 */

import { useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { PageLayout } from "@/components/templates/PageLayout";
import { ShieldCheckIcon } from "@heroicons/react/24/outline";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button } from "@/components/atoms/button";
import { StatusPill } from "@/components/atoms/status-pill";
import {
  useResidenceCardVerification,
  useSubmitResidenceCard,
} from "@/features/verification/hooks/useResidenceCardVerification";

function formatDateTime(iso?: string | null): string | null {
  if (!iso) return null;
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return null;
  return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(
    date
  );
}

export function ResidenceCardVerificationSettingsView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const returnTo = searchParams?.get("returnTo")?.trim() || "";

  const residenceCardQuery = useResidenceCardVerification({ enabled: true });
  const submitResidenceCard = useSubmitResidenceCard();

  const [residenceFile, setResidenceFile] = useState<File | null>(null);
  const residenceFileInputRef = useRef<HTMLInputElement | null>(null);

  const status = residenceCardQuery.data?.status;
  const statusPill = useMemo(() => {
    if (status === "verified") return <StatusPill label="Verified" variant="success" />;
    if (status === "pending") return <StatusPill label="Under Review" variant="info" />;
    if (status === "rejected") return <StatusPill label="Action Needed" variant="warning" />;
    return <StatusPill label="Not Submitted" variant="warning" />;
  }, [status]);

  const canUpload = status !== "verified";

  const renderVerificationContent = () => {
    if (residenceCardQuery.isLoading) {
      return <div className="text-sm text-muted-foreground">Checking verification status…</div>;
    }

    if (residenceCardQuery.isError) {
      return (
        <AlertBanner variant="warning" title="Unable to load status" size="sm" elevated>
          <div className="flex items-center gap-2">
            <Button type="button" size="sm" onClick={() => void residenceCardQuery.refetch()}>
              Try again
            </Button>
          </div>
        </AlertBanner>
      );
    }

    if (status === "verified") {
      return (
        <div className="space-y-4">
          <AlertBanner variant="success" title="Verified" size="sm" elevated>
            Your residence card is on file and approved. No further action is required.
          </AlertBanner>
          {returnTo && (
            <Button type="button" onClick={() => router.push(returnTo)}>
              Continue to Checkout
            </Button>
          )}
        </div>
      );
    }

    if (status === "pending") {
      return (
        <div className="space-y-4">
          <AlertBanner variant="info" title="Under review" size="sm" elevated>
            We&apos;ll verify your residence card before activating SIM service.
          </AlertBanner>

          {residenceCardQuery.data?.submittedAt && (
            <div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
              <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                Submission status
              </div>
              <div className="mt-1 text-xs text-muted-foreground">
                Submitted: {formatDateTime(residenceCardQuery.data?.submittedAt)}
              </div>
            </div>
          )}

          {returnTo && (
            <Button type="button" onClick={() => router.push(returnTo)}>
              Continue to Checkout
            </Button>
          )}
        </div>
      );
    }

    // Default: rejected or not_submitted
    return (
      <div className="space-y-4">
        <AlertBanner
          variant={status === "rejected" ? "warning" : "info"}
          title={status === "rejected" ? "Verification rejected" : "Upload required"}
          size="sm"
          elevated
        >
          <div className="space-y-2 text-sm">
            {status === "rejected" && residenceCardQuery.data?.reviewerNotes && (
              <p>{residenceCardQuery.data.reviewerNotes}</p>
            )}
            <p>Upload a clear photo or scan of your residence card (JPG, PNG, or PDF).</p>
            <ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
              <li>Make sure all text is readable and the full card is visible.</li>
              <li>Avoid glare/reflections and blurry photos.</li>
              <li>Maximum file size: 5MB.</li>
            </ul>
          </div>
        </AlertBanner>

        {(residenceCardQuery.data?.submittedAt || residenceCardQuery.data?.reviewedAt) && (
          <div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
            <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
              Latest submission
            </div>
            {formatDateTime(residenceCardQuery.data?.submittedAt) && (
              <div className="mt-1 text-xs text-muted-foreground">
                Submitted: {formatDateTime(residenceCardQuery.data?.submittedAt)}
              </div>
            )}
            {formatDateTime(residenceCardQuery.data?.reviewedAt) && (
              <div className="mt-1 text-xs text-muted-foreground">
                Reviewed: {formatDateTime(residenceCardQuery.data?.reviewedAt)}
              </div>
            )}
          </div>
        )}

        {canUpload && (
          <div className="space-y-3">
            <input
              ref={residenceFileInputRef}
              type="file"
              accept="image/*,application/pdf"
              onChange={e => setResidenceFile(e.target.files?.[0] ?? null)}
              className="block w-full text-sm text-foreground file:mr-4 file:py-2 file:px-3 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-muted file:text-foreground hover:file:bg-muted/80"
            />

            {residenceFile && (
              <div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/30 px-3 py-2">
                <div className="min-w-0">
                  <div className="text-xs font-medium text-muted-foreground">Selected file</div>
                  <div className="text-sm font-medium text-foreground truncate">
                    {residenceFile.name}
                  </div>
                </div>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setResidenceFile(null);
                    if (residenceFileInputRef.current) {
                      residenceFileInputRef.current.value = "";
                    }
                  }}
                >
                  Change
                </Button>
              </div>
            )}

            <div className="flex items-center justify-end gap-3">
              {returnTo && (
                <Button type="button" variant="outline" onClick={() => router.push(returnTo)}>
                  Back to checkout
                </Button>
              )}
              <Button
                type="button"
                disabled={!residenceFile || submitResidenceCard.isPending}
                isLoading={submitResidenceCard.isPending}
                loadingText="Uploading…"
                onClick={() => {
                  if (!residenceFile) return;
                  submitResidenceCard.mutate(residenceFile, {
                    onSuccess: () => {
                      setResidenceFile(null);
                      if (residenceFileInputRef.current) {
                        residenceFileInputRef.current.value = "";
                      }
                      // If there's a returnTo, navigate back after success
                      if (returnTo) {
                        router.push(returnTo);
                      }
                    },
                  });
                }}
              >
                Submit Document
              </Button>
            </div>

            {submitResidenceCard.isError && (
              <p className="text-sm text-destructive">
                {submitResidenceCard.error instanceof Error
                  ? submitResidenceCard.error.message
                  : "Failed to submit residence card."}
              </p>
            )}

            <p className="text-xs text-muted-foreground">
              Accepted formats: JPG, PNG, or PDF (max 5MB). Tip: higher resolution photos make
              review faster.
            </p>
          </div>
        )}
      </div>
    );
  };

  return (
    <PageLayout
      title="ID Verification"
      description="Upload your residence card for SIM activation"
      icon={<ShieldCheckIcon className="h-6 w-6" />}
      breadcrumbs={[{ label: "Settings", href: "/account/settings" }, { label: "ID Verification" }]}
    >
      <div className="max-w-2xl mx-auto space-y-6">
        <SubCard
          title="Residence Card"
          icon={<ShieldCheckIcon className="w-5 h-5 text-primary" />}
          right={statusPill}
        >
          {renderVerificationContent()}
        </SubCard>
      </div>
    </PageLayout>
  );
}

export default ResidenceCardVerificationSettingsView;
