"use client";

import {
  ArrowDownToLine,
  ArrowUpFromLine,
  Calendar,
  CheckCircle2,
  Clock,
  Copy,
  ExternalLink,
  FileText,
  FolderOpen,
  GitBranch,
  HardDrive,
  Link2,
  Paperclip,
  Pencil,
  Trash2,
  User,
  X,
  Image as ImageIcon,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Badge } from "@/shared/components/ui/badge";
import { Separator } from "@/shared/components/ui/separator";
import { ScrollArea } from "@/shared/components/ui/scroll-area";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/shared/components/ui/sheet";
import type { RegistryEntry } from "../types";
import { DEFAULT_DOC_TYPE_LABELS } from "../types";
import { getOverdueDays } from "../services/registry-service";
import { shortDisplayPath, shareLabelFor } from "@/config/nas-paths";
import { cn } from "@/shared/lib/utils";
import { useState, useCallback } from "react";

interface RegistryEntryDetailProps {
  entry: RegistryEntry | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onEdit: (entry: RegistryEntry) => void;
  onClose: (id: string) => void;
  onDelete: (id: string) => void;
  allEntries: RegistryEntry[];
}

const DIRECTION_CONFIG = {
  intrat: {
    label: "Intrat",
    icon: ArrowDownToLine,
    class: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
  },
  iesit: {
    label: "Ieșit",
    icon: ArrowUpFromLine,
    class:
      "bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",
  },
} as const;

const STATUS_CONFIG = {
  deschis: {
    label: "Deschis",
    class:
      "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",
  },
  inchis: {
    label: "Închis",
    class: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400",
  },
} as const;

const RESOLUTION_LABELS: Record<string, string> = {
  finalizat: "Finalizat",
  "aprobat-tacit": "Aprobat tacit",
  respins: "Respins",
  retras: "Retras",
  altele: "Altele",
};

const DEADLINE_RES_LABELS: Record<string, string> = {
  pending: "În așteptare",
  completed: "Finalizat",
  "aprobat-tacit": "Aprobat tacit",
  respins: "Respins",
  anulat: "Anulat",
};

function getDocTypeLabel(type: string): string {
  const label = DEFAULT_DOC_TYPE_LABELS[type];
  if (label) return label;
  return type.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}

function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString("ro-RO", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

function formatDateTime(iso: string): string {
  try {
    return new Date(iso).toLocaleString("ro-RO", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

export function RegistryEntryDetail({
  entry,
  open,
  onOpenChange,
  onEdit,
  onClose,
  onDelete,
  allEntries,
}: RegistryEntryDetailProps) {
  const [previewAttachment, setPreviewAttachment] = useState<string | null>(
    null,
  );
  const [copiedPath, setCopiedPath] = useState<string | null>(null);

  const copyPath = useCallback(async (path: string) => {
    await navigator.clipboard.writeText(path);
    setCopiedPath(path);
    setTimeout(() => setCopiedPath(null), 2000);
  }, []);

  if (!entry) return null;

  const dir = DIRECTION_CONFIG[entry.direction] ?? DIRECTION_CONFIG.intrat;
  const DirIcon = dir.icon;
  const status = STATUS_CONFIG[entry.status] ?? STATUS_CONFIG.deschis;

  const overdueDays =
    entry.status === "deschis" ? getOverdueDays(entry.deadline) : null;
  const isOverdue = overdueDays !== null && overdueDays > 0;

  const threadParent = entry.threadParentId
    ? allEntries.find((e) => e.id === entry.threadParentId)
    : null;
  const threadChildren = allEntries.filter(
    (e) => e.threadParentId === entry.id,
  );

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        className="w-full sm:max-w-lg md:max-w-xl p-0 flex flex-col"
      >
        <SheetHeader className="px-6 pt-6 pb-0">
          <div className="flex items-start justify-between gap-3 pr-8">
            <div className="space-y-1">
              <SheetTitle className="text-lg font-bold font-mono">
                {entry.number}
              </SheetTitle>
              <SheetDescription className="text-sm">
                {entry.subject}
              </SheetDescription>
            </div>
          </div>

          {/* Action bar */}
          <div className="flex gap-2 mt-3">
            <Button
              size="sm"
              variant="outline"
              onClick={() => {
                onOpenChange(false);
                onEdit(entry);
              }}
            >
              <Pencil className="mr-1.5 h-3.5 w-3.5" /> Editează
            </Button>
            {entry.status === "deschis" && (
              <Button
                size="sm"
                variant="outline"
                className="text-green-600 border-green-300 hover:bg-green-50 dark:border-green-700 dark:hover:bg-green-950/30"
                onClick={() => {
                  onOpenChange(false);
                  onClose(entry.id);
                }}
              >
                <CheckCircle2 className="mr-1.5 h-3.5 w-3.5" /> Închide
              </Button>
            )}
            <Button
              size="sm"
              variant="ghost"
              className="text-destructive ml-auto"
              onClick={() => {
                onOpenChange(false);
                onDelete(entry.id);
              }}
            >
              <Trash2 className="mr-1.5 h-3.5 w-3.5" /> Șterge
            </Button>
          </div>
        </SheetHeader>

        <Separator className="mt-4" />

        <ScrollArea className="flex-1 px-6">
          <div className="space-y-5 py-4 overflow-hidden">
            {/* ── Status row ── */}
            <div className="flex flex-wrap gap-2">
              <Badge className={cn("text-xs px-2.5 py-0.5", dir.class)}>
                <DirIcon className="mr-1 h-3 w-3" />
                {dir.label}
              </Badge>
              <Badge className={cn("text-xs px-2.5 py-0.5", status.class)}>
                {status.label}
              </Badge>
              <Badge variant="outline" className="text-xs">
                {getDocTypeLabel(entry.documentType)}
              </Badge>
              {entry.company && (
                <Badge variant="outline" className="text-xs uppercase">
                  {entry.company}
                </Badge>
              )}
            </div>

            {/* ── Closure info ── */}
            {entry.closureInfo && (
              <DetailSection title="Închidere">
                <div className="rounded-md border border-muted p-3 space-y-1 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Rezoluție:</span>
                    <Badge variant="outline" className="text-xs">
                      {RESOLUTION_LABELS[entry.closureInfo.resolution] ??
                        entry.closureInfo.resolution}
                    </Badge>
                  </div>
                  {entry.closureInfo.reason && (
                    <p>
                      <span className="text-muted-foreground">Motiv:</span>{" "}
                      {entry.closureInfo.reason}
                    </p>
                  )}
                  {entry.closureInfo.closedBy && (
                    <p className="text-xs text-muted-foreground">
                      Închis de {entry.closureInfo.closedBy} la{" "}
                      {formatDateTime(entry.closureInfo.closedAt)}
                    </p>
                  )}
                </div>
              </DetailSection>
            )}

            {/* ── Date ── */}
            <DetailSection title="Date">
              <div className="grid grid-cols-2 gap-3">
                <DetailField
                  label="Data document"
                  value={formatDate(entry.date)}
                />
                {entry.registrationDate &&
                  entry.registrationDate !== entry.date && (
                    <DetailField
                      label="Data înregistrare"
                      value={formatDate(entry.registrationDate)}
                    />
                  )}
                {entry.deadline && (
                  <DetailField
                    label="Termen limită"
                    value={formatDate(entry.deadline)}
                    className={cn(isOverdue && "text-destructive font-medium")}
                    extra={
                      overdueDays !== null && overdueDays > 0
                        ? `(${overdueDays} zile depășit)`
                        : overdueDays !== null && overdueDays < 0
                          ? `(mai sunt ${Math.abs(overdueDays)} zile)`
                          : undefined
                    }
                  />
                )}
                {entry.expiryDate && (
                  <DetailField
                    label="Valabilitate"
                    value={formatDate(entry.expiryDate)}
                  />
                )}
                <DetailField
                  label="Creat"
                  value={formatDateTime(entry.createdAt)}
                />
                <DetailField
                  label="Modificat"
                  value={formatDateTime(entry.updatedAt)}
                />
              </div>
            </DetailSection>

            {/* ── Parties ── */}
            <DetailSection title="Părți">
              <div className="grid grid-cols-2 gap-3">
                {entry.sender && (
                  <DetailField label="Expeditor" value={entry.sender} />
                )}
                {entry.recipient && (
                  <DetailField label="Destinatar" value={entry.recipient} />
                )}
                {entry.assignee && (
                  <DetailField
                    label="Responsabil"
                    value={entry.assignee}
                    icon={<User className="h-3 w-3 text-muted-foreground" />}
                  />
                )}
              </div>
              {(entry.recipientRegNumber || entry.recipientRegDate) && (
                <div className="mt-2 rounded border border-dashed p-2 text-xs text-muted-foreground">
                  {entry.recipientRegNumber && (
                    <span>Nr. destinatar: {entry.recipientRegNumber}</span>
                  )}
                  {entry.recipientRegDate && (
                    <span className="ml-3">
                      Data: {formatDate(entry.recipientRegDate)}
                    </span>
                  )}
                </div>
              )}
            </DetailSection>

            {/* ── Thread links ── */}
            {(threadParent ||
              threadChildren.length > 0 ||
              (entry.linkedEntryIds ?? []).length > 0) && (
              <DetailSection title="Legături">
                {threadParent && (
                  <div className="flex items-center gap-2 text-sm">
                    <GitBranch className="h-3.5 w-3.5 text-muted-foreground" />
                    <span className="text-muted-foreground">Răspuns la:</span>
                    <span className="font-mono text-xs">
                      {threadParent.number}
                    </span>
                    <span className="truncate text-muted-foreground">
                      — {threadParent.subject}
                    </span>
                  </div>
                )}
                {threadChildren.length > 0 && (
                  <div className="mt-1 space-y-0.5">
                    <p className="text-xs text-muted-foreground">
                      Răspunsuri ({threadChildren.length}):
                    </p>
                    {threadChildren.map((child) => (
                      <div
                        key={child.id}
                        className="flex items-center gap-2 text-xs ml-4"
                      >
                        <span className="font-mono">{child.number}</span>
                        <span className="truncate text-muted-foreground">
                          {child.subject}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
                {(entry.linkedEntryIds ?? []).length > 0 && (
                  <div className="mt-1">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Link2 className="h-3 w-3" />
                      {entry.linkedEntryIds.length} înregistrăr
                      {entry.linkedEntryIds.length === 1 ? "e" : "i"} legat
                      {entry.linkedEntryIds.length === 1 ? "ă" : "e"}
                    </p>
                  </div>
                )}
              </DetailSection>
            )}

            {/* ── Attachments ── */}
            {entry.attachments.length > 0 && (
              <DetailSection title={`Atașamente (${entry.attachments.length})`}>
                <div className="space-y-2">
                  {entry.attachments.map((att) =>
                    att.networkPath ? (
                      <div
                        key={att.id}
                        className="rounded-md border border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/20 px-3 py-2 group cursor-pointer hover:bg-blue-100/50 dark:hover:bg-blue-900/30 transition-colors overflow-hidden"
                        onClick={() => copyPath(att.networkPath!)}
                        title="Click pentru a copia calea — lipește în Explorer"
                      >
                        <div className="flex items-center gap-2 min-w-0">
                          <HardDrive className="h-4 w-4 text-blue-600 dark:text-blue-400 shrink-0" />
                          <div className="flex-1 min-w-0 truncate">
                            <span className="text-sm text-blue-700 dark:text-blue-300 font-mono">
                              <FolderOpen className="mr-1 inline h-3 w-3" />
                              {shortDisplayPath(att.networkPath)}
                            </span>
                          </div>
                          <Badge
                            variant="outline"
                            className="text-[10px] border-blue-300 dark:border-blue-700 text-blue-600 dark:text-blue-400 shrink-0"
                          >
                            {shareLabelFor(att.networkPath) ?? "NAS"}
                          </Badge>
                          {copiedPath === att.networkPath ? (
                            <Badge className="text-[10px] bg-green-600 text-white shrink-0 animate-in fade-in">
                              Copiat!
                            </Badge>
                          ) : (
                            <Copy className="h-3.5 w-3.5 text-blue-400 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
                          )}
                        </div>
                        <p className="text-[10px] text-muted-foreground mt-1 pl-6 font-mono truncate">
                          {att.networkPath}
                        </p>
                      </div>
                    ) : (
                      <div
                        key={att.id}
                        className="flex items-center gap-2 rounded-md border px-3 py-2 group"
                      >
                        {att.type.startsWith("image/") ? (
                          <ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
                        ) : (
                          <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
                        )}
                        <div className="flex-1 min-w-0">
                          <p className="text-sm truncate">{att.name}</p>
                          <p className="text-[10px] text-muted-foreground">
                            {(att.size / 1024).toFixed(0)} KB •{" "}
                            {att.type.split("/")[1]?.toUpperCase() ?? att.type}
                          </p>
                        </div>
                        <div className="flex items-center gap-1 shrink-0">
                          {/* Preview for images */}
                          {att.type.startsWith("image/") &&
                            att.data &&
                            att.data !== "" &&
                            att.data !== "__network__" && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6"
                                onClick={() => setPreviewAttachment(att.id)}
                                title="Previzualizare"
                              >
                                <ImageIcon className="h-3 w-3" />
                              </Button>
                            )}
                          {/* Download for files with data */}
                          {att.data &&
                            att.data !== "" &&
                            att.data !== "__network__" && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6"
                                onClick={() => {
                                  const a = document.createElement("a");
                                  a.href = att.data;
                                  a.download = att.name;
                                  a.click();
                                }}
                                title="Descarcă"
                              >
                                <ExternalLink className="h-3 w-3" />
                              </Button>
                            )}
                          <Badge variant="outline" className="text-[10px]">
                            <Paperclip className="mr-0.5 h-2.5 w-2.5" />
                            Fișier
                          </Badge>
                        </div>
                      </div>
                    ),
                  )}
                </div>

                {/* Image preview modal */}
                {previewAttachment && (
                  <div className="mt-3 rounded-md border p-2 bg-muted/30">
                    {(() => {
                      const att = entry.attachments.find(
                        (a) => a.id === previewAttachment,
                      );
                      if (
                        !att ||
                        !att.type.startsWith("image/") ||
                        !att.data ||
                        att.data === "" ||
                        att.data === "__network__"
                      )
                        return (
                          <p className="text-xs text-muted-foreground">
                            Previzualizare indisponibilă (fișierul nu conține
                            date inline).
                          </p>
                        );
                      return (
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <p className="text-xs font-medium">{att.name}</p>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5"
                              onClick={() => setPreviewAttachment(null)}
                            >
                              <X className="h-3 w-3" />
                            </Button>
                          </div>
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={att.data}
                            alt={att.name}
                            className="max-w-full max-h-64 rounded border object-contain"
                          />
                        </div>
                      );
                    })()}
                  </div>
                )}
              </DetailSection>
            )}

            {/* ── Legal deadlines ── */}
            {(entry.trackedDeadlines ?? []).length > 0 && (
              <DetailSection
                title={`Termene legale (${entry.trackedDeadlines!.length})`}
              >
                <div className="space-y-2">
                  {entry.trackedDeadlines!.map((dl) => (
                    <div
                      key={dl.id}
                      className={cn(
                        "rounded-md border px-3 py-2 text-xs",
                        dl.resolution === "pending" &&
                          new Date(dl.dueDate) < new Date()
                          ? "border-destructive/50 bg-destructive/5"
                          : dl.resolution === "pending"
                            ? "border-amber-300 dark:border-amber-700 bg-amber-50/50 dark:bg-amber-950/20"
                            : "border-muted",
                      )}
                    >
                      <div className="flex items-center justify-between">
                        <span className="font-medium">{dl.typeId}</span>
                        <Badge
                          variant="outline"
                          className={cn(
                            "text-[10px]",
                            dl.resolution === "pending" &&
                              "border-amber-400 text-amber-700 dark:text-amber-300",
                            dl.resolution === "completed" &&
                              "border-green-400 text-green-700 dark:text-green-300",
                          )}
                        >
                          {DEADLINE_RES_LABELS[dl.resolution] ?? dl.resolution}
                        </Badge>
                      </div>
                      <div className="flex gap-4 mt-1 text-muted-foreground">
                        <span>
                          <Calendar className="mr-0.5 inline h-2.5 w-2.5" />
                          Start: {formatDate(dl.startDate)}
                        </span>
                        <span>
                          <Clock className="mr-0.5 inline h-2.5 w-2.5" />
                          Scadent: {formatDate(dl.dueDate)}
                        </span>
                      </div>
                      {dl.resolutionNote && (
                        <p className="mt-1 text-muted-foreground">
                          {dl.resolutionNote}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              </DetailSection>
            )}

            {/* ── External tracking ── */}
            {(entry.externalStatusUrl || entry.externalTrackingId) && (
              <DetailSection title="Urmărire externă">
                <div className="grid grid-cols-2 gap-3">
                  {entry.externalTrackingId && (
                    <DetailField
                      label="ID extern"
                      value={entry.externalTrackingId}
                    />
                  )}
                  {entry.externalStatusUrl && (
                    <div>
                      <p className="text-[10px] text-muted-foreground mb-0.5">
                        URL verificare
                      </p>
                      <a
                        href={entry.externalStatusUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs text-blue-600 dark:text-blue-400 hover:underline break-all"
                      >
                        {entry.externalStatusUrl}
                      </a>
                    </div>
                  )}
                </div>
              </DetailSection>
            )}

            {/* ── Tags ── */}
            {entry.tags.length > 0 && (
              <DetailSection title="Etichete">
                <div className="flex flex-wrap gap-1">
                  {entry.tags.map((tag) => (
                    <Badge key={tag} variant="outline" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                </div>
              </DetailSection>
            )}

            {/* ── Notes ── */}
            {entry.notes && (
              <DetailSection title="Note">
                <p className="text-sm whitespace-pre-wrap text-muted-foreground">
                  {entry.notes}
                </p>
              </DetailSection>
            )}
          </div>
        </ScrollArea>
      </SheetContent>
    </Sheet>
  );
}

// ── Sub-components ──

function DetailSection({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
        {title}
      </h3>
      {children}
    </div>
  );
}

function DetailField({
  label,
  value,
  className,
  extra,
  icon,
}: {
  label: string;
  value: string;
  className?: string;
  extra?: string;
  icon?: React.ReactNode;
}) {
  return (
    <div>
      <p className="text-[10px] text-muted-foreground mb-0.5">{label}</p>
      <p className={cn("text-sm", className)}>
        {icon && <span className="mr-1 inline-flex align-middle">{icon}</span>}
        {value}
        {extra && (
          <span className="ml-1 text-[10px] text-muted-foreground">
            {extra}
          </span>
        )}
      </p>
    </div>
  );
}
