import * as React from "react";
import { CheckCircle2, Circle, Upload } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";

// ─── Types ────────────────────────────────────────────────────────────────────

export type DocumentChecklistItemStatus =
  | "pending"
  | "uploaded"
  | "not-required";

export type DocumentChecklistItem = {
  id: string;
  /** Document category label — e.g. "Bank Statements", "Income Verification" */
  category: string;
  /** Filename of the uploaded file, if any */
  fileName?: string;
  /** Upload status */
  status: DocumentChecklistItemStatus;
};

export type ApplicantDocumentChecklistProps = {
  /** Applicant label shown above the list */
  applicantName?: string;
  /** List of document requirements */
  items: DocumentChecklistItem[];
  /** Called when the applicant selects a file for an item */
  onUpload?: (itemId: string, file: File) => void;
  /** Called when the applicant removes an uploaded file */
  onRemove?: (itemId: string) => void;
  className?: string;
};

// ─── Internal helpers ─────────────────────────────────────────────────────────

type StatusIconProps = { status: DocumentChecklistItemStatus };

function StatusIcon({ status }: StatusIconProps) {
  if (status === "uploaded") {
    return <CheckCircle2 className="size-5 shrink-0 text-primary" />;
  }
  return <Circle className="size-5 shrink-0 text-muted-foreground" />;
}

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * ApplicantDocumentChecklist — applicant-facing document upload list.
 *
 * Shows a checklist of required document categories. Each row has a status
 * icon, category label, and an upload button. Once a file is uploaded the row
 * shows the filename and a Remove action.
 *
 * Figma: WealthX-Backoffice---Mobile-App (loan wizard — Supporting Documents tab)
 */
export function ApplicantDocumentChecklist({
  applicantName,
  items,
  onUpload,
  onRemove,
  className,
}: ApplicantDocumentChecklistProps) {
  const inputRefs = React.useRef<Record<string, HTMLInputElement | null>>({});

  function handleFileChange(
    itemId: string,
    e: React.ChangeEvent<HTMLInputElement>,
  ) {
    const file = e.target.files?.[0];
    if (file) onUpload?.(itemId, file);
    // Reset so re-selecting the same file fires onChange again
    e.target.value = "";
  }

  const { uploadedCount, totalRequired } = React.useMemo(() => {
    let uploaded = 0;
    let required = 0;
    for (const i of items) {
      if (i.status !== "not-required") required++;
      if (i.status === "uploaded") uploaded++;
    }
    return { uploadedCount: uploaded, totalRequired: required };
  }, [items]);

  return (
    <div className={cn("flex flex-col gap-6 font-sans", className)}>
      <div className="flex flex-col gap-1">
        {applicantName && (
          <p className="text-body-small text-muted-foreground">
            {applicantName}
          </p>
        )}
        <p className="text-label-medium text-foreground">
          {uploadedCount} of {totalRequired} documents uploaded
        </p>
        <Progress
          value={
            totalRequired > 0
              ? Math.round((uploadedCount / totalRequired) * 100)
              : 0
          }
          className="h-1.5"
        />
      </div>

      <div className="flex flex-col divide-y divide-border border border-border">
        {items.map((item) => (
          <div key={item.id} className="flex items-center gap-3 px-4 py-3">
            <StatusIcon status={item.status} />

            <div className="flex min-w-0 flex-1 flex-col gap-0.5">
              <span
                className={cn(
                  "text-label-medium",
                  item.status === "uploaded"
                    ? "text-foreground"
                    : "text-muted-foreground",
                )}
              >
                {item.category}
              </span>
              {item.fileName && (
                <span className="truncate text-caption text-muted-foreground">
                  {item.fileName}
                </span>
              )}
            </div>

            <div className="flex shrink-0 items-center gap-2">
              {item.status === "uploaded" ? (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="text-destructive hover:text-destructive"
                  onClick={() => onRemove?.(item.id)}
                >
                  Remove
                </Button>
              ) : (
                <>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="gap-1.5"
                    onClick={() => inputRefs.current[item.id]?.click()}
                  >
                    <Upload className="size-3.5" />
                    Upload
                  </Button>
                  <input
                    ref={(el) => {
                      inputRefs.current[item.id] = el;
                    }}
                    type="file"
                    accept=".pdf,.jpg,.jpeg,.png"
                    className="sr-only"
                    onChange={(e) => handleFileChange(item.id, e)}
                  />
                </>
              )}
            </div>
          </div>
        ))}
      </div>

      <p className="text-caption text-muted-foreground">
        Accepted formats: PDF, JPG, PNG. Max 10 MB per file.
      </p>
    </div>
  );
}
