"use client";

import { useState, useMemo, useRef } from "react";
import {
  AlertTriangle,
  Search,
  Link2,
  Paperclip,
  X,
  FileText,
} from "lucide-react";
import { useAuth } from "@/core/auth";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Textarea } from "@/shared/components/ui/textarea";
import { Badge } from "@/shared/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import type {
  RegistryEntry,
  TrackedDeadline,
  RegistryAttachment,
  ClosureInfo,
  ClosureResolution,
} from "../types";
import { getDeadlineType } from "../services/deadline-catalog";
import { v4 as uuid } from "uuid";

interface CloseGuardDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** The entry being closed */
  entry: RegistryEntry;
  /** All entries for search/linking */
  allEntries: RegistryEntry[];
  /** Active (pending) deadlines — empty if none */
  activeDeadlines: TrackedDeadline[];
  /** Called when user confirms close with all structured data */
  onConfirmClose: (info: ClosureInfo) => void;
}

/**
 * Universal close dialog: always shown when closing any entry.
 * - If active deadlines exist → shows a warning banner
 * - Requires a reason (free text)
 * - Optionally link a continuation entry
 * - Optionally attach a closing document (e.g. scanned letter)
 */
export function CloseGuardDialog({
  open,
  onOpenChange,
  entry,
  allEntries,
  activeDeadlines,
  onConfirmClose,
}: CloseGuardDialogProps) {
  const { user } = useAuth();
  const [search, setSearch] = useState("");
  const [selectedEntryId, setSelectedEntryId] = useState("");
  const [resolution, setResolution] = useState<ClosureResolution>("finalizat");
  const [reason, setReason] = useState("");
  const [attachment, setAttachment] = useState<RegistryAttachment | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  const hasDeadlines = activeDeadlines.length > 0;

  // Reset on open
  const handleOpenChange = (o: boolean) => {
    if (o) {
      setSearch("");
      setSelectedEntryId("");
      setResolution("finalizat");
      setReason("");
      setAttachment(null);
    }
    onOpenChange(o);
  };

  // Searchable entries (exclude self)
  const searchResults = useMemo(() => {
    if (!search || search.length < 2) return [];
    const q = search.toLowerCase();
    return allEntries
      .filter(
        (e) =>
          e.id !== entry.id &&
          (e.subject.toLowerCase().includes(q) ||
            e.number.toLowerCase().includes(q) ||
            e.sender.toLowerCase().includes(q) ||
            e.recipient.toLowerCase().includes(q)),
      )
      .slice(0, 8);
  }, [search, allEntries, entry.id]);

  const selectedEntry = allEntries.find((e) => e.id === selectedEntryId);

  const canSubmit = reason.trim().length >= 3;

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      setAttachment({
        id: uuid(),
        name: file.name,
        data: reader.result as string,
        type: file.type,
        size: file.size,
        addedAt: new Date().toISOString(),
      });
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  const handleSubmit = () => {
    if (!canSubmit) return;
    onConfirmClose({
      resolution,
      reason: reason.trim(),
      closedBy: user?.name ?? "Utilizator",
      closedAt: new Date().toISOString(),
      linkedEntryId: selectedEntryId || undefined,
      linkedEntryNumber: selectedEntry?.number,
      hadActiveDeadlines: hasDeadlines,
      attachment: attachment ?? undefined,
    });
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {hasDeadlines ? (
              <>
                <AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400" />
                <span className="text-amber-600 dark:text-amber-400">
                  Închidere cu termene active
                </span>
              </>
            ) : (
              <>Închide înregistrarea {entry.number}</>
            )}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Active deadlines warning */}
          {hasDeadlines && (
            <div className="rounded border border-amber-300 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/30 p-3 space-y-1.5">
              <p className="text-sm text-amber-800 dark:text-amber-200">
                <strong>{activeDeadlines.length}</strong> termen
                {activeDeadlines.length > 1 ? "e" : ""} legal
                {activeDeadlines.length > 1 ? "e" : ""} nerezolvat
                {activeDeadlines.length > 1 ? "e" : ""}:
              </p>
              {activeDeadlines.map((dl) => {
                const def = getDeadlineType(dl.typeId);
                const isOverdue = new Date(dl.dueDate) < new Date();
                return (
                  <div key={dl.id} className="flex items-center gap-2 text-sm">
                    <Badge
                      variant={isOverdue ? "destructive" : "outline"}
                      className="text-[10px] shrink-0"
                    >
                      {isOverdue ? "Depășit" : "Activ"}
                    </Badge>
                    <span className="font-medium">
                      {def?.label ?? dl.typeId}
                    </span>
                    <span className="text-muted-foreground text-xs ml-auto">
                      scadent {dl.dueDate}
                    </span>
                  </div>
                );
              })}
            </div>
          )}

          {/* Resolution type — same concept as deadline resolution */}
          <div>
            <Label>Rezoluție</Label>
            <Select
              value={resolution}
              onValueChange={(v) => setResolution(v as ClosureResolution)}
            >
              <SelectTrigger className="mt-1">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="finalizat">Finalizat</SelectItem>
                <SelectItem value="aprobat-tacit">Aprobat tacit</SelectItem>
                <SelectItem value="respins">Respins / Negativ</SelectItem>
                <SelectItem value="retras">Retras de beneficiar</SelectItem>
                <SelectItem value="altele">Altele</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Reason — always required */}
          <div>
            <Label>Motiv închidere *</Label>
            <Textarea
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Ex: Dosarul a fost finalizat, retras de beneficiar, preluat într-o altă cerere..."
              rows={3}
              className="mt-1"
              autoFocus
            />
          </div>

          {/* Link to continuation entry — optional */}
          <div className="space-y-2">
            <Label className="flex items-center gap-1.5">
              <Link2 className="h-3.5 w-3.5" />
              Legătură la înregistrarea-continuare
              <span className="text-xs text-muted-foreground">(opțional)</span>
            </Label>
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setSelectedEntryId("");
                }}
                placeholder="Caută după nr., subiect, expeditor..."
                className="pl-9"
              />
            </div>
            {searchResults.length > 0 && !selectedEntryId && (
              <div className="max-h-36 overflow-y-auto rounded border divide-y">
                {searchResults.map((e) => (
                  <button
                    key={e.id}
                    type="button"
                    className="w-full px-3 py-2 text-left text-sm hover:bg-accent transition-colors"
                    onClick={() => {
                      setSelectedEntryId(e.id);
                      setSearch(e.number);
                    }}
                  >
                    <span className="font-mono font-medium text-xs">
                      {e.number}
                    </span>
                    <span className="ml-2">{e.subject}</span>
                    <span className="ml-2 text-muted-foreground text-xs">
                      {e.sender}
                    </span>
                  </button>
                ))}
              </div>
            )}
            {selectedEntry && (
              <div className="flex items-center gap-2 text-sm rounded border px-2 py-1.5 bg-muted/50">
                <Link2 className="h-3.5 w-3.5 text-primary shrink-0" />
                <span className="font-mono text-xs font-medium">
                  {selectedEntry.number}
                </span>
                <span className="truncate">{selectedEntry.subject}</span>
                <button
                  type="button"
                  className="ml-auto text-muted-foreground hover:text-destructive"
                  onClick={() => {
                    setSelectedEntryId("");
                    setSearch("");
                  }}
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )}
          </div>

          {/* Attachment — optional closing document */}
          <div className="space-y-2">
            <Label className="flex items-center gap-1.5">
              <Paperclip className="h-3.5 w-3.5" />
              Document de închidere
              <span className="text-xs text-muted-foreground">(opțional)</span>
            </Label>
            {!attachment ? (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => fileRef.current?.click()}
              >
                <Paperclip className="mr-1.5 h-3.5 w-3.5" />
                Atașează document
              </Button>
            ) : (
              <div className="flex items-center gap-2 rounded border px-2 py-1.5 text-sm">
                <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
                <span className="flex-1 truncate">{attachment.name}</span>
                <Badge variant="outline" className="text-[10px]">
                  {(attachment.size / 1024).toFixed(0)} KB
                </Badge>
                <button
                  type="button"
                  onClick={() => setAttachment(null)}
                  className="text-destructive"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )}
            <input
              ref={fileRef}
              type="file"
              accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx"
              onChange={handleFileUpload}
              className="hidden"
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            Anulează
          </Button>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={!canSubmit}
            variant={hasDeadlines ? "destructive" : "default"}
          >
            Închide înregistrarea
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
