import { useState } from "react";
import { GripVertical, Plus, Trash2 } from "lucide-react";
import { Button } from "./button";
import { Input } from "./input";
import { Switch } from "./switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./select";
import { cn } from "../../lib/utils";

/** Predefined document category options advisors can pick from. */
const DOCUMENT_TYPES = [
  "Income Verification",
  "Bank Statements",
  "Rental Income",
  "Property Evidence",
  "Liabilities",
  "Identity",
  "Employment Contract",
  "Notice of Assessment",
  "Contract of Sale",
  "Savings History",
];

export interface ChecklistCategory {
  id: string;
  name: string;
  /** Required for the main applicant. */
  requiredMain: boolean;
  /** Required for the co-applicant. */
  requiredCo: boolean;
  /** true when the advisor typed a custom name not in the predefined list. */
  custom?: boolean;
}

export interface DocumentChecklistTemplateProps {
  /** Initial list of checklist categories. */
  categories?: ChecklistCategory[];
  /** Called on every edit (add / change / delete). */
  onChange?: (categories: ChecklistCategory[]) => void;
  /** Called when the advisor clicks Save. */
  onSave?: (categories: ChecklistCategory[]) => void;
  /** Called when the advisor clicks Cancel. */
  onCancel?: () => void;
  className?: string;
}

/**
 * DocumentChecklistTemplate — organism
 *
 * Editable list of document categories. Each category has separate Required
 * toggles for Main and Co applicants. Name is chosen from a predefined
 * dropdown or typed as a custom value.
 */
export function DocumentChecklistTemplate({
  categories: initial = [],
  onChange,
  onSave,
  onCancel,
  className,
}: DocumentChecklistTemplateProps) {
  const [categories, setCategories] = useState<ChecklistCategory[]>(() =>
    initial.map((c) => ({
      ...c,
      custom: c.custom ?? !DOCUMENT_TYPES.includes(c.name),
    })),
  );
  const [isDirty, setIsDirty] = useState(false);

  function update(next: ChecklistCategory[]) {
    setCategories(next);
    setIsDirty(true);
    onChange?.(next);
  }

  function handleSelectType(id: string, value: string) {
    if (value === "__custom__") {
      update(
        categories.map((c) =>
          c.id === id ? { ...c, name: "", custom: true } : c,
        ),
      );
    } else {
      update(
        categories.map((c) =>
          c.id === id ? { ...c, name: value, custom: false } : c,
        ),
      );
    }
  }

  function handleCustomName(id: string, name: string) {
    update(categories.map((c) => (c.id === id ? { ...c, name } : c)));
  }

  function handleToggle(id: string, field: "requiredMain" | "requiredCo") {
    update(
      categories.map((c) => (c.id === id ? { ...c, [field]: !c[field] } : c)),
    );
  }

  function handleDelete(id: string) {
    update(categories.filter((c) => c.id !== id));
  }

  function handleAdd() {
    update([
      ...categories,
      {
        id: `cat-${Date.now()}`,
        name: "",
        requiredMain: true,
        requiredCo: false,
        custom: false,
      },
    ]);
  }

  const COLS = "grid-cols-[20px_1fr_64px_64px_32px]";

  return (
    <div className={cn("flex flex-col", className)}>
      {/* ── Header — title only ── */}
      <div className="shrink-0 border-b border-border px-6 py-4">
        <span className="text-label-large text-foreground">
          Document Checklist Template
        </span>
      </div>

      {/* ── Description ── */}
      <div className="shrink-0 border-b border-border px-6 py-3">
        <p className="text-body-small text-muted-foreground">
          Define the document categories required for loan applications. Set
          required status separately for Main and Co-applicants.
        </p>
      </div>

      {/* ── Body ── */}
      <div className="flex flex-col overflow-y-auto">
        {/* Column headers */}
        {categories.length > 0 && (
          <div
            className={cn(
              "grid shrink-0 items-center gap-3 border-b border-border bg-muted/30 px-6 py-2",
              COLS,
            )}
          >
            <span />
            <span className="text-xs font-medium text-muted-foreground">
              Category Name
            </span>
            <span className="text-center text-xs font-medium text-muted-foreground">
              Main
            </span>
            <span className="text-center text-xs font-medium text-muted-foreground">
              Co
            </span>
            <span />
          </div>
        )}

        {/* Rows */}
        {categories.length === 0 ? (
          <div className="flex items-center justify-center py-12 text-sm text-muted-foreground">
            No categories yet. Add one below.
          </div>
        ) : (
          <div className="divide-y divide-border">
            {categories.map((cat) => (
              <div
                key={cat.id}
                className={cn("grid items-center gap-3 px-6 py-3", COLS)}
              >
                <GripVertical className="size-4 shrink-0 text-muted-foreground/30" />

                {/* Name: Select (predefined) or Input (custom) */}
                {cat.custom ? (
                  <Input
                    value={cat.name}
                    onChange={(e) => handleCustomName(cat.id, e.target.value)}
                    placeholder="Type category name…"
                    className="h-8 text-sm"
                    autoFocus
                  />
                ) : (
                  <Select
                    value={cat.name || ""}
                    onValueChange={(v) => handleSelectType(cat.id, v ?? "")}
                  >
                    <SelectTrigger size="sm" className="w-full">
                      <SelectValue placeholder="Select type…" />
                    </SelectTrigger>
                    <SelectContent>
                      {DOCUMENT_TYPES.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type}
                        </SelectItem>
                      ))}
                      <SelectItem value="__custom__">Custom…</SelectItem>
                    </SelectContent>
                  </Select>
                )}

                <div className="flex justify-center">
                  <Switch
                    checked={cat.requiredMain}
                    onCheckedChange={() => handleToggle(cat.id, "requiredMain")}
                    size="sm"
                  />
                </div>

                <div className="flex justify-center">
                  <Switch
                    checked={cat.requiredCo}
                    onCheckedChange={() => handleToggle(cat.id, "requiredCo")}
                    size="sm"
                  />
                </div>

                <Button
                  variant="ghost"
                  size="icon"
                  className="size-8 text-muted-foreground hover:text-destructive"
                  onClick={() => handleDelete(cat.id)}
                >
                  <Trash2 className="size-4" />
                </Button>
              </div>
            ))}
          </div>
        )}

        {/* Add Category */}
        <div className="border-t border-border px-6 py-4">
          <Button
            variant="outline"
            size="sm"
            className="gap-1.5"
            onClick={handleAdd}
          >
            <Plus className="size-4" />
            Add Category
          </Button>
        </div>
      </div>

      {/* ── Footer ── */}
      <div className="flex shrink-0 justify-end gap-2 border-t border-border px-6 py-4">
        {onCancel && (
          <Button variant="outline" onClick={onCancel}>
            Cancel
          </Button>
        )}
        <Button onClick={() => onSave?.(categories)} disabled={!isDirty}>
          Save
        </Button>
      </div>
    </div>
  );
}
