import * as React from "react";
import { Plus, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
/**
 * AddColumnModal — WealthX DS (L4 Dialog)
 *
 * Create or edit a Pipeline stage (column). Supports:
 * - Column title (optionally locked for system stages)
 * - Time-based alert thresholds (warning days, priority days)
 * - Task template list (up to 20 tasks)
 *
 * Data source: `listColumns()` → `Stage` in `loan-crm.ts`
 */

const MAX_TASKS = 20;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface ColumnTask {
  /** Temp numeric ID for new tasks; persisted string ID for existing ones. */
  id: string | number;
  name: string;
}

export interface AddColumnEditData {
  id?: string;
  name: string;
  orderIndex?: number;
  warningDays?: number | null;
  priorityDays?: number | null;
  tasks?: ColumnTask[];
  /** When true the title field is read-only (system/fixed stages). */
  isTitleLocked?: boolean;
}

export interface AddColumnModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (data: AddColumnEditData) => void;
  /** Pre-populate for edit mode. Omit (or pass null) for create mode. */
  editData?: AddColumnEditData | null;
  loading?: boolean;
  className?: string;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function AddColumnModal({
  open,
  onOpenChange,
  onSave,
  editData,
  loading = false,
  className,
}: AddColumnModalProps) {
  const isEdit = !!editData?.id;
  const nextId = React.useRef(0);

  const [name, setName] = React.useState(editData?.name ?? "");
  const [warningDays, setWarningDays] = React.useState(
    editData?.warningDays != null ? String(editData.warningDays) : ""
  );
  const [priorityDays, setPriorityDays] = React.useState(
    editData?.priorityDays != null ? String(editData.priorityDays) : ""
  );
  const [tasks, setTasks] = React.useState<ColumnTask[]>(editData?.tasks ?? []);

  // Sync state when dialog opens or editData changes
  React.useEffect(() => {
    if (open) {
      setName(editData?.name ?? "");
      setWarningDays(
        editData?.warningDays != null ? String(editData.warningDays) : ""
      );
      setPriorityDays(
        editData?.priorityDays != null ? String(editData.priorityDays) : ""
      );
      setTasks(editData?.tasks ?? []);
    }
  }, [open, editData]);

  // Validation
  const wDays = warningDays !== "" ? parseInt(warningDays, 10) : null;
  const pDays = priorityDays !== "" ? parseInt(priorityDays, 10) : null;
  const daysError =
    wDays !== null && pDays !== null && wDays >= pDays
      ? "Warning days must be less than priority days."
      : null;

  const taskNames = tasks.map((t) => t.name.trim().toLowerCase());
  const hasDuplicateTasks =
    new Set(taskNames).size !== taskNames.filter(Boolean).length;

  const isValid =
    name.trim().length > 0 &&
    !daysError &&
    !hasDuplicateTasks &&
    tasks.every((t) => t.name.trim().length > 0);

  function addTask() {
    if (tasks.length >= MAX_TASKS) return;
    setTasks((prev) => [...prev, { id: nextId.current++, name: "" }]);
  }

  function removeTask(id: string | number) {
    setTasks((prev) => prev.filter((t) => t.id !== id));
  }

  function updateTask(
    id: string | number,
    patch: Partial<Pick<ColumnTask, "name">>
  ) {
    setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
  }

  function handleSave() {
    onSave({
      id: editData?.id,
      name: name.trim(),
      orderIndex: editData?.orderIndex,
      warningDays: wDays,
      priorityDays: pDays,
      tasks,
      isTitleLocked: editData?.isTitleLocked,
    });
  }

  return (
    <Dialog open={open} onOpenChange={loading ? undefined : onOpenChange}>
      <DialogContent className={cn("max-w-md", className)}>
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit Column" : "Add New Column"}</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-4">
          {/* Column title */}
          <div className="flex flex-col gap-1.5">
            <Label>Column title</Label>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Pre-approval"
              disabled={editData?.isTitleLocked || loading}
            />
            {editData?.isTitleLocked && (
              <p className="text-xs text-muted-foreground">
                This column title is locked and cannot be changed.
              </p>
            )}
          </div>

          {/* Time-based alerts */}
          <div className="flex flex-col gap-2">
            <span className="text-sm font-medium text-foreground">
              Time-based alerts
            </span>
            <div className="grid grid-cols-2 gap-3">
              <div className="flex flex-col gap-1.5">
                <Label className="font-normal text-muted-foreground">
                  Warning after (days)
                </Label>
                <Input
                  type="number"
                  min={1}
                  value={warningDays}
                  onChange={(e) => setWarningDays(e.target.value)}
                  placeholder="e.g. 7"
                  disabled={loading}
                />
              </div>
              <div className="flex flex-col gap-1.5">
                <Label className="font-normal text-muted-foreground">
                  Priority after (days)
                </Label>
                <Input
                  type="number"
                  min={1}
                  value={priorityDays}
                  onChange={(e) => setPriorityDays(e.target.value)}
                  placeholder="e.g. 14"
                  disabled={loading}
                />
              </div>
            </div>
            {daysError && (
              <p className="text-xs text-destructive">{daysError}</p>
            )}
          </div>

          <Separator />

          {/* Task templates */}
          <div className="flex flex-col gap-2">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-foreground">
                Task templates
              </span>
              <Button
                variant="outline"
                size="sm"
                className="h-7 gap-1 text-xs"
                onClick={addTask}
                disabled={tasks.length >= MAX_TASKS || loading}
              >
                <Plus className="size-3" />
                Add ({tasks.length}/{MAX_TASKS})
              </Button>
            </div>

            {tasks.length === 0 && (
              <p className="text-xs text-muted-foreground">
                No tasks yet. Tasks will be created for each new opportunity
                added to this column.
              </p>
            )}

            <div className="flex flex-col gap-2">
              {tasks.map((task) => (
                <div key={task.id} className="flex flex-col gap-1.5">
                  <div className="flex items-center gap-2">
                    <Input
                      value={task.name}
                      onChange={(e) =>
                        updateTask(task.id, { name: e.target.value })
                      }
                      placeholder="Task name"
                      className="flex-1"
                      disabled={loading}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeTask(task.id)}
                      disabled={loading}
                      className="size-9 shrink-0 text-muted-foreground hover:text-destructive"
                      aria-label="Remove task"
                    >
                      <Trash2 className="size-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>

            {hasDuplicateTasks && (
              <p className="text-xs text-destructive">
                Task names must be unique.
              </p>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={loading}
          >
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={loading || !isValid}>
            {loading
              ? isEdit
                ? "Saving…"
                : "Adding…"
              : isEdit
              ? "Save changes"
              : "Add column"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
