import * as React from "react";
import { addDays, startOfDay, format } from "date-fns";
import { cn } from "@/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { DatePicker } from "@/components/ui/date-picker";

/**
 * Pipeline Dialogs — WealthX DS (L4)
 *
 * Small, focused dialogs for Pipeline / Loan CRM actions:
 * - DeleteOpportunityDialog — confirm card deletion
 * - ChangePriorityDialog    — select priority (Auto / Low / Medium / High)
 * - PutOnHoldDialog         — choose a hold-until date (preset or custom)
 *
 * All dialogs are fully controlled (`open` + `onOpenChange`).
 * The `loading` prop disables actions and prevents accidental close.
 */

// ---------------------------------------------------------------------------
// DeleteOpportunityDialog
// ---------------------------------------------------------------------------

export interface DeleteOpportunityDialogProps {
  open: boolean;
  /** Disables buttons and prevents close while an async op is in-flight. */
  loading?: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: () => void;
  className?: string;
}

export function DeleteOpportunityDialog({
  open,
  loading = false,
  onOpenChange,
  onConfirm,
  className,
}: DeleteOpportunityDialogProps) {
  return (
    <Dialog open={open} onOpenChange={loading ? undefined : onOpenChange}>
      <DialogContent
        showCloseButton={!loading}
        className={cn("max-w-sm", className)}
      >
        <DialogHeader>
          <DialogTitle>Want to delete this card?</DialogTitle>
          <DialogDescription>
            Doing so will also remove all associated loan applications and
            tasks. This action cannot be undone.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={loading}
          >
            Cancel
          </Button>
          <Button variant="destructive" onClick={onConfirm} disabled={loading}>
            {loading ? "Deleting…" : "Delete"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// ChangePriorityDialog
// ---------------------------------------------------------------------------

export type PrioritySelection = "auto" | "low" | "medium" | "high";

const PRIORITY_OPTIONS: {
  value: PrioritySelection;
  label: string;
  color: string;
}[] = [
  { value: "auto", label: "Auto", color: "var(--color-muted-foreground)" },
  { value: "low", label: "Low", color: "var(--color-success)" },
  { value: "medium", label: "Medium", color: "var(--color-warning)" },
  { value: "high", label: "High", color: "var(--color-destructive)" },
];

export interface ChangePriorityDialogProps {
  open: boolean;
  value: PrioritySelection;
  loading?: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: () => void;
  onSelectionChange: (value: PrioritySelection) => void;
  className?: string;
}

export function ChangePriorityDialog({
  open,
  value,
  loading = false,
  onOpenChange,
  onSave,
  onSelectionChange,
  className,
}: ChangePriorityDialogProps) {
  return (
    <Dialog open={open} onOpenChange={loading ? undefined : onOpenChange}>
      <DialogContent className={cn("max-w-sm", className)}>
        <DialogHeader>
          <DialogTitle>Change priority</DialogTitle>
        </DialogHeader>
        <Select
          value={value}
          onValueChange={(v) => onSelectionChange(v as PrioritySelection)}
        >
          <SelectTrigger className="w-full">
            {(() => {
              const opt = PRIORITY_OPTIONS.find((o) => o.value === value);
              return opt ? (
                <span className="flex items-center gap-2">
                  <span
                    className="inline-block size-2 shrink-0 rounded-full"
                    style={{ backgroundColor: opt.color }}
                    aria-hidden="true"
                  />
                  {opt.label}
                </span>
              ) : null;
            })()}
          </SelectTrigger>
          <SelectContent>
            {PRIORITY_OPTIONS.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                <span className="flex items-center gap-2">
                  <span
                    className="inline-block size-2 shrink-0 rounded-full"
                    style={{ backgroundColor: opt.color }}
                    aria-hidden="true"
                  />
                  {opt.label}
                </span>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={loading}
          >
            Cancel
          </Button>
          <Button onClick={onSave} disabled={loading}>
            {loading ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// PutOnHoldDialog
// ---------------------------------------------------------------------------

export type HoldDuration = "90" | "180" | "360" | "custom";

const HOLD_OPTIONS: { value: HoldDuration; label: string }[] = [
  { value: "90", label: "90 Days" },
  { value: "180", label: "180 Days" },
  { value: "360", label: "360 Days" },
  { value: "custom", label: "Custom" },
];

export interface PutOnHoldDialogProps {
  open: boolean;
  loading?: boolean;
  onOpenChange: (open: boolean) => void;
  /** Called with an ISO date string (yyyy-MM-dd) when the user saves. */
  onSave: (isoDate: string) => void;
  className?: string;
}

export function PutOnHoldDialog({
  open,
  loading = false,
  onOpenChange,
  onSave,
  className,
}: PutOnHoldDialogProps) {
  const [duration, setDuration] = React.useState<HoldDuration>("90");
  const [customDate, setCustomDate] = React.useState<Date | undefined>();
  const today = React.useMemo(() => startOfDay(new Date()), []);

  const resolvedDate = React.useMemo<Date | undefined>(() => {
    if (duration === "custom") return customDate;
    return addDays(today, parseInt(duration, 10));
  }, [duration, customDate, today]);

  const isValid = resolvedDate !== undefined && resolvedDate >= today;

  function handleSave() {
    if (!resolvedDate) return;
    onSave(format(resolvedDate, "yyyy-MM-dd"));
  }

  // Reset when dialog opens
  React.useEffect(() => {
    if (open) {
      setDuration("90");
      setCustomDate(undefined);
    }
  }, [open]);

  return (
    <Dialog open={open} onOpenChange={loading ? undefined : onOpenChange}>
      <DialogContent className={cn("max-w-sm", className)}>
        <DialogHeader>
          <DialogTitle>Hold and Hide Until Later Date</DialogTitle>
        </DialogHeader>
        <div className="flex flex-col gap-4">
          <ToggleGroup
            type="single"
            variant="outline"
            size="sm"
            value={[duration]}
            onValueChange={(v) => {
              if (v.length) setDuration(v[0] as HoldDuration);
            }}
            className="w-full"
          >
            {HOLD_OPTIONS.map((opt) => (
              <ToggleGroupItem
                key={opt.value}
                value={opt.value}
                className="flex-1"
              >
                {opt.label}
              </ToggleGroupItem>
            ))}
          </ToggleGroup>

          {/* Fixed-height row — same h-9 in all tab states to prevent layout jump */}
          {duration === "custom" ? (
            <DatePicker
              value={customDate}
              onChange={setCustomDate}
              placeholder="Pick a date"
              calendarProps={{ disabled: { before: today } }}
            />
          ) : (
            resolvedDate && (
              <div className="flex h-9 items-center border border-input bg-muted/30 px-3 text-sm text-muted-foreground">
                Hold until:{" "}
                <span className="ml-1 font-medium text-foreground">
                  {format(resolvedDate, "dd MMM yyyy")}
                </span>
              </div>
            )
          )}

          {/* For custom: show resolved date below the picker once selected */}
          {duration === "custom" && customDate && (
            <p className="text-sm text-muted-foreground">
              Hold until:{" "}
              <span className="font-medium text-foreground">
                {format(customDate, "dd MMM yyyy")}
              </span>
            </p>
          )}
        </div>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={loading}
          >
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={loading || !isValid}>
            {loading ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
