"use client";

import { useState, useMemo } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Badge } from "@/shared/components/ui/badge";
import {
  DEADLINE_CATALOG,
  CATEGORY_LABELS,
} from "../services/deadline-catalog";
import { computeDueDate } from "../services/working-days";
import type { DeadlineCategory, DeadlineTypeDef } from "../types";

interface DeadlineAddDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  entryDate: string;
  onAdd: (typeId: string, startDate: string) => void;
}

type Step = "category" | "type" | "date";

const CATEGORIES: DeadlineCategory[] = [
  "certificat",
  "avize",
  "completari",
  "analiza",
  "autorizare",
  "publicitate",
];

export function DeadlineAddDialog({
  open,
  onOpenChange,
  entryDate,
  onAdd,
}: DeadlineAddDialogProps) {
  const [step, setStep] = useState<Step>("category");
  const [selectedCategory, setSelectedCategory] =
    useState<DeadlineCategory | null>(null);
  const [selectedType, setSelectedType] = useState<DeadlineTypeDef | null>(
    null,
  );
  const [startDate, setStartDate] = useState(entryDate);

  const typesForCategory = useMemo(() => {
    if (!selectedCategory) return [];
    return DEADLINE_CATALOG.filter((d) => d.category === selectedCategory);
  }, [selectedCategory]);

  const dueDatePreview = useMemo(() => {
    if (!selectedType || !startDate) return null;
    const start = new Date(startDate);
    start.setHours(0, 0, 0, 0);
    const due = computeDueDate(
      start,
      selectedType.days,
      selectedType.dayType,
      selectedType.isBackwardDeadline,
    );
    return due.toLocaleDateString("ro-RO", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  }, [selectedType, startDate]);

  const handleClose = () => {
    setStep("category");
    setSelectedCategory(null);
    setSelectedType(null);
    setStartDate(entryDate);
    onOpenChange(false);
  };

  const handleCategorySelect = (cat: DeadlineCategory) => {
    setSelectedCategory(cat);
    setStep("type");
  };

  const handleTypeSelect = (typ: DeadlineTypeDef) => {
    setSelectedType(typ);
    if (!typ.requiresCustomStartDate) {
      setStartDate(entryDate);
    }
    setStep("date");
  };

  const handleBack = () => {
    if (step === "type") {
      setStep("category");
      setSelectedCategory(null);
    } else if (step === "date") {
      setStep("type");
      setSelectedType(null);
    }
  };

  const handleConfirm = () => {
    if (!selectedType || !startDate) return;
    onAdd(selectedType.id, startDate);
    handleClose();
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (!o) handleClose();
      }}
    >
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>
            {step === "category" && "Adaugă termen legal — Categorie"}
            {step === "type" &&
              `Adaugă termen legal — ${selectedCategory ? CATEGORY_LABELS[selectedCategory] : ""}`}
            {step === "date" &&
              `Adaugă termen legal — ${selectedType?.label ?? ""}`}
          </DialogTitle>
        </DialogHeader>

        {step === "category" && (
          <div className="grid gap-2 py-2">
            {CATEGORIES.map((cat) => (
              <button
                key={cat}
                type="button"
                className="flex items-center justify-between rounded-lg border p-3 text-left transition-colors hover:bg-accent"
                onClick={() => handleCategorySelect(cat)}
              >
                <span className="font-medium text-sm">
                  {CATEGORY_LABELS[cat]}
                </span>
                <Badge variant="outline" className="text-xs">
                  {DEADLINE_CATALOG.filter((d) => d.category === cat).length}
                </Badge>
              </button>
            ))}
          </div>
        )}

        {step === "type" && (
          <div className="grid gap-2 py-2">
            {typesForCategory.map((typ) => (
              <button
                key={typ.id}
                type="button"
                className="rounded-lg border p-3 text-left transition-colors hover:bg-accent"
                onClick={() => handleTypeSelect(typ)}
              >
                <div className="flex items-center gap-2">
                  <span className="font-medium text-sm">{typ.label}</span>
                  <Badge variant="outline" className="text-[10px]">
                    {typ.days}{" "}
                    {typ.dayType === "working" ? "zile lucr." : "zile cal."}
                  </Badge>
                  {typ.tacitApprovalApplicable && (
                    <Badge
                      variant="outline"
                      className="text-[10px] text-blue-600"
                    >
                      tacit
                    </Badge>
                  )}
                  {typ.isBackwardDeadline && (
                    <Badge
                      variant="outline"
                      className="text-[10px] text-orange-600"
                    >
                      înapoi
                    </Badge>
                  )}
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {typ.description}
                </p>
              </button>
            ))}
          </div>
        )}

        {step === "date" && selectedType && (
          <div className="space-y-4 py-2">
            <div>
              <Label>{selectedType.startDateLabel}</Label>
              {selectedType.startDateHint && (
                <p className="text-xs text-muted-foreground mt-0.5">
                  {selectedType.startDateHint}
                </p>
              )}
              <Input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="mt-1"
              />
            </div>

            {dueDatePreview && (
              <div className="rounded-lg border bg-muted/30 p-3">
                <p className="text-xs text-muted-foreground">
                  {selectedType.isBackwardDeadline
                    ? "Termen limită depunere"
                    : "Termen limită calculat"}
                </p>
                <p className="text-lg font-bold">{dueDatePreview}</p>
                <p className="text-xs text-muted-foreground mt-1">
                  {selectedType.days}{" "}
                  {selectedType.dayType === "working"
                    ? "zile lucrătoare"
                    : "zile calendaristice"}
                  {selectedType.isBackwardDeadline
                    ? " ÎNAINTE"
                    : " de la data start"}
                </p>
                {selectedType.legalReference && (
                  <p className="text-xs text-muted-foreground mt-1 italic">
                    Ref: {selectedType.legalReference}
                  </p>
                )}
              </div>
            )}
          </div>
        )}

        <DialogFooter className="gap-2 sm:gap-0">
          {step !== "category" && (
            <Button type="button" variant="outline" onClick={handleBack}>
              Înapoi
            </Button>
          )}
          {step === "category" && (
            <Button type="button" variant="outline" onClick={handleClose}>
              Anulează
            </Button>
          )}
          {step === "date" && (
            <Button type="button" onClick={handleConfirm} disabled={!startDate}>
              Adaugă termen
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
