"use client"

import { useEffect, useRef, useState } from "react"
import { useTranslations } from "next-intl"
import {
  FileText, Building2, RefreshCw, ExternalLink, Plus, Pencil, Trash2, Download, X,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { api } from "@/src/lib/api/client"
import {
  listDocumentTemplates,
  createDocumentTemplate,
  updateDocumentTemplate,
  deleteDocumentTemplate,
  type DocumentTemplate,
} from "@/src/lib/api/document-templates"

type DocType = "contract" | "invoice" | "letter" | "id" | "other"

type ByType    = { doc_type: DocType; count: number }
type ByTenant  = { tenant_id: number; tenant_name: string; count: number }
type RecentDoc = {
  id: number
  title: string
  doc_type: DocType
  case_reference: string
  tenant_name: string
  uploaded_by: string
  created_at: string
  file_url: string | null
}

type Stats = {
  total: number
  by_type: ByType[]
  by_tenant: ByTenant[]
  recent: RecentDoc[]
}

const TYPE_COLORS: Record<DocType, string> = {
  contract: "#1a3578",
  invoice:  "#f59e0b",
  letter:   "#059669",
  id:       "#7c3aed",
  other:    "#6b7280",
}

const CATEGORY_VALUES = ["amiable", "juridique", "accord", "paiement", "autre"] as const

// ─── Template modal ────────────────────────────────────────────────────────────
type ModalMode = "create" | "edit"

interface TemplateModalProps {
  mode: ModalMode
  initial?: DocumentTemplate
  onClose: () => void
  onSaved: () => void
  t: ReturnType<typeof useTranslations<"admin.documents">>
  tc: ReturnType<typeof useTranslations<"common">>
}

function TemplateModal({ mode, initial, onClose, onSaved, t, tc }: TemplateModalProps) {
  const [title,       setTitle]       = useState(initial?.title ?? "")
  const [description, setDescription] = useState(initial?.description ?? "")
  const [category,    setCategory]    = useState(initial?.category ?? "autre")
  const [file,        setFile]        = useState<File | null>(null)
  const [saving,      setSaving]      = useState(false)
  const [error,       setError]       = useState<string | null>(null)
  const fileRef = useRef<HTMLInputElement>(null)

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (!title.trim()) return
    if (mode === "create" && !file) return
    setSaving(true)
    setError(null)
    try {
      if (mode === "create") {
        const fd = new FormData()
        fd.append("title", title.trim())
        fd.append("description", description.trim())
        fd.append("category", category)
        fd.append("file", file!)
        await createDocumentTemplate(fd)
      } else {
        await updateDocumentTemplate(initial!.id, {
          title: title.trim(),
          description: description.trim(),
          category,
          ...(file ? { file } : {}),
        })
      }
      onSaved()
    } catch (err: any) {
      setError(err?.message ?? "Erreur")
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="w-full max-w-lg rounded-2xl border bg-background shadow-xl">
        <div className="flex items-center justify-between border-b px-6 py-4">
          <h2 className="font-semibold">
            {mode === "create" ? t("modal_create_title") : t("modal_edit_title")}
          </h2>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
            <X className="h-5 w-5" />
          </button>
        </div>

        <form onSubmit={submit} className="space-y-4 p-6">
          {error && (
            <div className="rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive">
              {error}
            </div>
          )}

          {/* Title */}
          <div className="space-y-1">
            <label className="text-sm font-medium">{t("field_title")} *</label>
            <input
              type="text"
              required
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
            />
          </div>

          {/* Description */}
          <div className="space-y-1">
            <label className="text-sm font-medium">{t("field_description")}</label>
            <textarea
              rows={3}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="w-full resize-none rounded-xl border bg-muted/30 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
            />
          </div>

          {/* Category */}
          <div className="space-y-1">
            <label className="text-sm font-medium">{t("field_category")}</label>
            <select
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
            >
              {CATEGORY_VALUES.map((cat) => (
                <option key={cat} value={cat}>
                  {t(`categories.${cat}` as any)}
                </option>
              ))}
            </select>
          </div>

          {/* File */}
          <div className="space-y-1">
            <label className="text-sm font-medium">
              {t("field_file")}
              {mode === "create" ? " *" : ""}
            </label>
            {mode === "edit" && (
              <p className="text-xs text-muted-foreground">{t("field_file_replace")}</p>
            )}
            <div
              className="flex cursor-pointer items-center gap-3 rounded-xl border border-dashed bg-muted/20 px-4 py-3 hover:bg-muted/40"
              onClick={() => fileRef.current?.click()}
            >
              <FileText className="h-5 w-5 shrink-0 text-muted-foreground" />
              <span className="text-sm text-muted-foreground">
                {file ? file.name : t("field_file_hint")}
              </span>
            </div>
            <input
              ref={fileRef}
              type="file"
              accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg"
              className="hidden"
              onChange={(e) => setFile(e.target.files?.[0] ?? null)}
            />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <Button type="button" variant="ghost" onClick={onClose}>{tc("cancel")}</Button>
            <Button type="submit" disabled={saving}>
              {saving ? tc("saving") : (mode === "create" ? tc("create") : tc("save"))}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

// ─── Delete confirm dialog ─────────────────────────────────────────────────────
interface DeleteDialogProps {
  onClose: () => void
  onConfirm: () => void
  loading: boolean
  t: ReturnType<typeof useTranslations<"admin.documents">>
  tc: ReturnType<typeof useTranslations<"common">>
}

function DeleteDialog({ onClose, onConfirm, loading, t, tc }: DeleteDialogProps) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="w-full max-w-sm rounded-2xl border bg-background p-6 shadow-xl space-y-4">
        <h2 className="font-semibold text-destructive">{t("confirm_delete_title")}</h2>
        <p className="text-sm text-muted-foreground">{t("confirm_delete_body")}</p>
        <div className="flex justify-end gap-3">
          <Button variant="ghost" onClick={onClose} disabled={loading}>{tc("cancel")}</Button>
          <Button variant="destructive" onClick={onConfirm} disabled={loading}>
            {loading ? tc("loading") : tc("delete")}
          </Button>
        </div>
      </div>
    </div>
  )
}

// ─── Main page ─────────────────────────────────────────────────────────────────
export default function AdminDocumentsPage() {
  const t  = useTranslations("admin.documents")
  const tc = useTranslations("common")

  // Stats
  const [stats,        setStats]        = useState<Stats | null>(null)
  const [statsLoading, setStatsLoading] = useState(true)
  const [statsError,   setStatsError]   = useState<string | null>(null)

  // Templates
  const [templates,    setTemplates]    = useState<DocumentTemplate[]>([])
  const [tplLoading,   setTplLoading]   = useState(true)
  const [tplError,     setTplError]     = useState<string | null>(null)

  // Modal
  const [modal, setModal] = useState<{ mode: ModalMode; item?: DocumentTemplate } | null>(null)

  // Delete
  const [deleteTarget,  setDeleteTarget]  = useState<DocumentTemplate | null>(null)
  const [deleteLoading, setDeleteLoading] = useState(false)

  async function loadStats() {
    setStatsLoading(true)
    setStatsError(null)
    try {
      const data = await api.request<Stats>("/admin-documents/")
      setStats(data)
    } catch (e: any) {
      setStatsError(e?.message ?? "Erreur")
    } finally {
      setStatsLoading(false)
    }
  }

  async function loadTemplates() {
    setTplLoading(true)
    setTplError(null)
    try {
      const data = await listDocumentTemplates()
      setTemplates(data)
    } catch (e: any) {
      setTplError(e?.message ?? "Erreur")
    } finally {
      setTplLoading(false)
    }
  }

  useEffect(() => {
    loadStats()
    loadTemplates()
  }, [])

  async function handleDeleteConfirm() {
    if (!deleteTarget) return
    setDeleteLoading(true)
    try {
      await deleteDocumentTemplate(deleteTarget.id)
      setDeleteTarget(null)
      loadTemplates()
    } catch (e: any) {
      alert(e?.message ?? "Erreur")
    } finally {
      setDeleteLoading(false)
    }
  }

  const typeLabel = (type: DocType) => {
    const map: Record<DocType, string> = {
      contract: t("doc_type.contract"),
      invoice:  t("doc_type.invoice"),
      letter:   t("doc_type.letter"),
      id:       t("doc_type.id"),
      other:    t("doc_type.other"),
    }
    return map[type] ?? type
  }

  const categoryLabel = (cat: string) => {
    const map: Record<string, string> = {
      amiable:  t("categories.amiable"),
      juridique: t("categories.juridique"),
      accord:   t("categories.accord"),
      paiement: t("categories.paiement"),
      autre:    t("categories.autre"),
    }
    return map[cat] ?? cat
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold flex items-center gap-2">
            <FileText className="h-5 w-5" />
            {t("title")}
          </h1>
          <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
        </div>
        <Button variant="secondary" onClick={() => { loadStats(); loadTemplates() }} disabled={statsLoading} className="gap-2">
          <RefreshCw className={`h-4 w-4 ${statsLoading ? "animate-spin" : ""}`} />
          {statsLoading ? t("loading") : "Rafraîchir"}
        </Button>
      </div>

      {statsError && (
        <div className="rounded-2xl border border-destructive/30 bg-destructive/10 p-4 text-sm">{statsError}</div>
      )}

      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="rounded-2xl border bg-card p-5 shadow-sm">
          <p className="text-xs text-muted-foreground">{t("kpi_total")}</p>
          <p className="text-3xl font-bold mt-1">{statsLoading ? "—" : (stats?.total ?? 0)}</p>
        </div>
        {stats?.by_type.slice(0, 3).map((bt) => (
          <div key={bt.doc_type} className="rounded-2xl border bg-card p-5 shadow-sm">
            <p className="text-xs text-muted-foreground">{typeLabel(bt.doc_type)}</p>
            <p className="text-3xl font-bold mt-1" style={{ color: TYPE_COLORS[bt.doc_type] }}>{bt.count}</p>
          </div>
        ))}
        <div className="rounded-2xl border bg-card p-5 shadow-sm">
          <p className="text-xs text-muted-foreground">{t("kpi_tenants")}</p>
          <p className="text-3xl font-bold mt-1 text-primary">
            {statsLoading ? "—" : (stats?.by_tenant.length ?? 0)}
          </p>
        </div>
      </div>

      {/* Par tenant + types */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="rounded-2xl border bg-card p-5 shadow-sm space-y-4">
          <h2 className="font-semibold flex items-center gap-2">
            <Building2 className="h-4 w-4" />
            {t("by_tenant_title")}
          </h2>
          {statsLoading ? (
            <p className="text-sm text-muted-foreground">{t("loading")}</p>
          ) : (
            <div className="overflow-auto rounded-xl border">
              <table className="w-full text-sm">
                <thead className="bg-muted/40">
                  <tr className="text-left">
                    <th className="p-3">{t("by_tenant_col_name")}</th>
                    <th className="p-3 text-right">{t("by_tenant_col_count")}</th>
                  </tr>
                </thead>
                <tbody>
                  {(stats?.by_tenant ?? []).map((row) => (
                    <tr key={row.tenant_id} className="border-t">
                      <td className="p-3 font-medium">{row.tenant_name}</td>
                      <td className="p-3 text-right">
                        <span className="rounded-full bg-primary/10 text-primary px-2 py-0.5 text-xs font-semibold">
                          {row.count}
                        </span>
                      </td>
                    </tr>
                  ))}
                  {(stats?.by_tenant.length ?? 0) === 0 && (
                    <tr>
                      <td className="p-6 text-center text-muted-foreground" colSpan={2}>{t("recent_empty")}</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div className="rounded-2xl border bg-card p-5 shadow-sm space-y-4">
          <h2 className="font-semibold flex items-center gap-2">
            <FileText className="h-4 w-4" />
            {t("recent_col_type")}
          </h2>
          {statsLoading ? (
            <p className="text-sm text-muted-foreground">{t("loading")}</p>
          ) : (
            <div className="space-y-3">
              {(stats?.by_type ?? []).map((bt) => {
                const pct = stats && stats.total > 0 ? Math.round((bt.count / stats.total) * 100) : 0
                return (
                  <div key={bt.doc_type} className="space-y-1">
                    <div className="flex justify-between text-sm">
                      <span className="font-medium">{typeLabel(bt.doc_type)}</span>
                      <span className="text-muted-foreground">{bt.count} ({pct}%)</span>
                    </div>
                    <div className="h-2 rounded-full bg-muted overflow-hidden">
                      <div
                        className="h-full rounded-full transition-all"
                        style={{ width: `${pct}%`, background: TYPE_COLORS[bt.doc_type] }}
                      />
                    </div>
                  </div>
                )
              })}
              {(stats?.by_type.length ?? 0) === 0 && (
                <p className="text-sm text-muted-foreground">{t("recent_empty")}</p>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Documents récents */}
      <div className="rounded-2xl border bg-card p-5 shadow-sm space-y-4">
        <h2 className="font-semibold flex items-center gap-2">
          <FileText className="h-4 w-4" />
          {t("recent_title")}
        </h2>
        {statsLoading ? (
          <p className="text-sm text-muted-foreground">{t("loading")}</p>
        ) : (
          <div className="overflow-auto rounded-xl border">
            <table className="w-full text-sm">
              <thead className="bg-muted/40">
                <tr className="text-left">
                  <th className="p-3">{t("recent_col_title")}</th>
                  <th className="p-3">{t("recent_col_type")}</th>
                  <th className="p-3">{t("recent_col_case")}</th>
                  <th className="p-3">{t("recent_col_tenant")}</th>
                  <th className="p-3">{t("recent_col_by")}</th>
                  <th className="p-3">{t("recent_col_date")}</th>
                  <th className="p-3 text-right"></th>
                </tr>
              </thead>
              <tbody>
                {(stats?.recent ?? []).map((doc) => (
                  <tr key={doc.id} className="border-t">
                    <td className="p-3 font-medium max-w-[200px] truncate">{doc.title}</td>
                    <td className="p-3">
                      <span
                        className="rounded-full px-2 py-0.5 text-xs font-medium text-white"
                        style={{ background: TYPE_COLORS[doc.doc_type] }}
                      >
                        {typeLabel(doc.doc_type)}
                      </span>
                    </td>
                    <td className="p-3 font-mono text-xs">{doc.case_reference}</td>
                    <td className="p-3">{doc.tenant_name}</td>
                    <td className="p-3 text-muted-foreground">{doc.uploaded_by}</td>
                    <td className="p-3 text-xs text-muted-foreground">
                      {new Date(doc.created_at).toLocaleDateString()}
                    </td>
                    <td className="p-3 text-right">
                      {doc.file_url && (
                        <a
                          href={doc.file_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
                        >
                          <ExternalLink className="h-3 w-3" />
                        </a>
                      )}
                    </td>
                  </tr>
                ))}
                {(stats?.recent.length ?? 0) === 0 && (
                  <tr>
                    <td className="p-6 text-center text-muted-foreground" colSpan={7}>{t("recent_empty")}</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* ─── Modèles de recouvrement (CRUD) ─── */}
      <div className="space-y-4">
        <div className="flex items-end justify-between gap-4">
          <div>
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Download className="h-5 w-5" />
              {t("templates_title")}
            </h2>
            <p className="text-sm text-muted-foreground">{t("templates_subtitle")}</p>
          </div>
          <Button onClick={() => setModal({ mode: "create" })} className="gap-2">
            <Plus className="h-4 w-4" />
            {t("add_template")}
          </Button>
        </div>

        {tplError && (
          <div className="rounded-2xl border border-destructive/30 bg-destructive/10 p-4 text-sm">{tplError}</div>
        )}

        {tplLoading ? (
          <p className="text-sm text-muted-foreground">{t("loading")}</p>
        ) : templates.length === 0 ? (
          <div className="rounded-2xl border bg-card p-10 text-center text-sm text-muted-foreground">
            {t("no_templates")}
          </div>
        ) : (
          <div className="rounded-2xl border bg-card shadow-sm overflow-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/40">
                <tr className="text-left">
                  <th className="p-3">{t("tpl_col_title")}</th>
                  <th className="p-3">{t("tpl_col_category")}</th>
                  <th className="p-3">{t("tpl_col_file")}</th>
                  <th className="p-3">{t("tpl_col_by")}</th>
                  <th className="p-3">{t("tpl_col_updated")}</th>
                  <th className="p-3 text-right">{tc("actions")}</th>
                </tr>
              </thead>
              <tbody>
                {templates.map((tpl) => (
                  <tr key={tpl.id} className="border-t hover:bg-muted/20 transition-colors">
                    <td className="p-3">
                      <div className="font-medium">{tpl.title}</div>
                      {tpl.description && (
                        <div className="text-xs text-muted-foreground mt-0.5 max-w-xs truncate">
                          {tpl.description}
                        </div>
                      )}
                    </td>
                    <td className="p-3">
                      <span className="rounded-full border px-2 py-0.5 text-xs font-medium">
                        {categoryLabel(tpl.category)}
                      </span>
                    </td>
                    <td className="p-3">
                      {tpl.file_url ? (
                        <a
                          href={tpl.file_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
                        >
                          <Download className="h-3 w-3" />
                          {tpl.file_name ?? t("download")}
                        </a>
                      ) : (
                        <span className="text-xs text-muted-foreground">—</span>
                      )}
                    </td>
                    <td className="p-3 text-muted-foreground text-xs">{tpl.created_by_username}</td>
                    <td className="p-3 text-xs text-muted-foreground">
                      {new Date(tpl.updated_at).toLocaleDateString()}
                    </td>
                    <td className="p-3 text-right">
                      <div className="flex justify-end gap-2">
                        <button
                          onClick={() => setModal({ mode: "edit", item: tpl })}
                          className="rounded-lg p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
                          title={tc("edit")}
                        >
                          <Pencil className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => setDeleteTarget(tpl)}
                          className="rounded-lg p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
                          title={tc("delete")}
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Modals */}
      {modal && (
        <TemplateModal
          mode={modal.mode}
          initial={modal.item}
          t={t}
          tc={tc}
          onClose={() => setModal(null)}
          onSaved={() => { setModal(null); loadTemplates() }}
        />
      )}

      {deleteTarget && (
        <DeleteDialog
          t={t}
          tc={tc}
          loading={deleteLoading}
          onClose={() => setDeleteTarget(null)}
          onConfirm={handleDeleteConfirm}
        />
      )}
    </div>
  )
}
