"use client"

import { useCallback, useEffect, useMemo, useState } from "react"
import Link from "next/link"
import {
  Scissors,
  Plus,
  Pencil,
  Trash2,
  Loader2,
  Star,
  Search,
  BookOpen,
  Tag,
  Activity,
} from "lucide-react"
import { toast } from "sonner"
import { Navbar } from "@/components/dashboard/navbar"
import { DeleteConfirmModal } from "@/components/dashboard/delete-confirm-modal"
import { DashboardPageContent } from "@/components/dashboard/shared/DashboardPageContent"
import { DashboardPageHeader } from "@/components/dashboard/shared/DashboardPageHeader"
import { DashboardStatsGrid } from "@/components/dashboard/shared/DashboardStatsGrid"
import { DashboardTableCard } from "@/components/dashboard/shared/DashboardTableCard"
import { DashboardTablePagination } from "@/components/dashboard/shared/DashboardTablePagination"
import { DashboardTableViewControls } from "@/components/dashboard/shared/DashboardTableViewControls"
import { ContentAuditInfo } from "@/components/dashboard/shared/ContentAuditInfo"
import { useDashboardTableViewControls } from "@/hooks/useDashboardTableViewControls"
import type { ContentAudit } from "@/types/content-audit"

interface ProcedureRow {
  id: string
  name: string
  image: string
  rating: number
  reviewCount: number
  category: string
  categoryColor?: string
  isFeatured: boolean
  status: string
  audit: ContentAudit
}

type FilterStatus = "all" | "published" | "draft"

const PROCEDURES_TABLE_ID = "procedures-table"

const PROCEDURES_SORT_OPTIONS = [
  { value: "newest", label: "Newest first" },
  { value: "oldest", label: "Oldest first" },
  { value: "updated-newest", label: "Recently updated" },
  { value: "updated-oldest", label: "Least recently updated" },
  { value: "name-asc", label: "Name A → Z" },
  { value: "name-desc", label: "Name Z → A" },
]

const PROCEDURES_SORT_COMPARATORS: Record<string, (a: ProcedureRow, b: ProcedureRow) => number> = {
  newest: (a, b) => new Date(b.audit.createdAt).getTime() - new Date(a.audit.createdAt).getTime(),
  oldest: (a, b) => new Date(a.audit.createdAt).getTime() - new Date(b.audit.createdAt).getTime(),
  "updated-newest": (a, b) => new Date(b.audit.updatedAt).getTime() - new Date(a.audit.updatedAt).getTime(),
  "updated-oldest": (a, b) => new Date(a.audit.updatedAt).getTime() - new Date(b.audit.updatedAt).getTime(),
  "name-asc": (a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
  "name-desc": (a, b) => b.name.localeCompare(a.name, undefined, { sensitivity: "base" }),
}

const CATEGORY_COLORS: Record<string, string> = {
  Cardiology: "#EF4444",
  Nutrition: "#F59E0B",
  Surgery: "#3B82F6",
  "Mental Health": "#8B5CF6",
  Pediatrics: "#EC4899",
  Endocrinology: "#0EA5E9",
  Technology: "#10B981",
}

function getCategoryColor(name: string, dbColor?: string) {
  if (dbColor && /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(dbColor)) return dbColor
  return CATEGORY_COLORS[name] ?? "var(--brand-navy)"
}

export default function ProceduresPage() {
  const [rows, setRows] = useState<ProcedureRow[]>([])
  const [loading, setLoading] = useState(true)
  const [listError, setListError] = useState<string | null>(null)
  const [deleteTarget, setDeleteTarget] = useState<ProcedureRow | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)
  const [search, setSearch] = useState("")
  const [filterStatus, setFilterStatus] = useState<FilterStatus>("all")

  const tableView = useDashboardTableViewControls<ProcedureRow>({
    tableId: PROCEDURES_TABLE_ID,
    defaultSortKey: "newest",
    defaultItemsPerPage: 6,
    sortOptions: PROCEDURES_SORT_OPTIONS,
    comparators: PROCEDURES_SORT_COMPARATORS,
  })

  const loadProcedures = useCallback(async () => {
    setLoading(true)
    setListError(null)
    try {
      const res = await fetch("/api/admin/procedures", { cache: "no-store" })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.success === false) {
        throw new Error(typeof json?.error === "string" ? json.error : "Failed to load procedures")
      }

      const procedures = Array.isArray(json?.procedures) ? json.procedures : []
      setRows(
        procedures.map((procedure: Record<string, unknown>) => ({
          id: typeof procedure.id === "string" ? procedure.id : "",
          name: typeof procedure.name === "string" ? procedure.name : "Untitled",
          image: typeof procedure.image === "string" ? procedure.image : "",
          rating: typeof procedure.rating === "number" ? procedure.rating : 0,
          reviewCount: typeof procedure.reviewCount === "number" ? procedure.reviewCount : 0,
          category:
            procedure.category && typeof procedure.category === "object" && typeof (procedure.category as { name?: unknown }).name === "string"
              ? ((procedure.category as { name: string }).name ?? "—")
              : "—",
          categoryColor:
            procedure.category && typeof procedure.category === "object" && typeof (procedure.category as { color?: unknown }).color === "string"
              ? ((procedure.category as { color: string }).color ?? undefined)
              : undefined,
          isFeatured: Boolean(procedure.isFeatured),
          status: typeof procedure.status === "string" ? procedure.status : "draft",
          audit:
            procedure.audit && typeof procedure.audit === "object"
              ? (procedure.audit as ContentAudit)
              : {
                  createdAt: typeof procedure.createdAt === "string" ? procedure.createdAt : "",
                  updatedAt: typeof procedure.updatedAt === "string" ? procedure.updatedAt : "",
                  createdBy: null,
                  updatedBy: null,
                },
        }))
      )
    } catch (error) {
      setRows([])
      setListError(error instanceof Error ? error.message : "Failed to load procedures")
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadProcedures()
  }, [loadProcedures])

  async function handleDelete() {
    if (!deleteTarget) return
    setIsDeleting(true)
    try {
      const res = await fetch(`/api/admin/procedures/${deleteTarget.id}`, { method: "DELETE" })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.success === false) {
        throw new Error(typeof json?.error === "string" ? json.error : "Delete failed")
      }
      setRows((prev) => prev.filter((r) => r.id !== deleteTarget.id))
      toast.success("Procedure deleted")
      setDeleteTarget(null)
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Delete failed")
    } finally {
      setIsDeleting(false)
    }
  }

  const totalProcedures = rows.length
  const totalPublished = rows.filter((r) => r.status === "published").length
  const totalDraft = rows.filter((r) => r.status === "draft").length
  const totalCategories = new Set(rows.map((r) => r.category)).size

  const STATS = [
    { label: "Total Procedures", value: loading ? "…" : totalProcedures, icon: Scissors, color: "var(--brand-navy)" },
    { label: "Published", value: loading ? "…" : totalPublished, icon: BookOpen, color: "var(--brand-green)" },
    { label: "Drafts", value: loading ? "…" : totalDraft, icon: Activity, color: "#F59E0B" },
    { label: "Categories", value: loading ? "…" : totalCategories, icon: Tag, color: "#0EA5E9" },
  ]

  const filtered = useMemo(() => {
    return rows.filter((r) => {
      const matchSearch = r.name.toLowerCase().includes(search.toLowerCase()) || r.category.toLowerCase().includes(search.toLowerCase())
      const matchStatus = filterStatus === "all" || r.status === filterStatus
      return matchSearch && matchStatus
    })
  }, [rows, search, filterStatus])

  const viewResult = useMemo(() => tableView.applyView(filtered), [filtered, tableView.applyView])

  useEffect(() => {
    if (tableView.viewAll) return
    if (tableView.currentPage > viewResult.totalPages) {
      tableView.setCurrentPage(viewResult.totalPages)
    }
  }, [
    tableView.viewAll,
    tableView.currentPage,
    tableView.setCurrentPage,
    viewResult.totalPages,
  ])

  const paginated = viewResult.displayed
  const totalPages = viewResult.totalPages

  return (
    <>
      <Navbar
        title="Procedures"
        breadcrumbs={[
          { label: "Dashboard", href: "/dashboard" },
          { label: "Procedures" },
        ]}
      />

      <DashboardPageContent>
        <DashboardPageHeader
          title="Procedure Management"
          description="Manage all medical procedure pages — create, edit, and publish."
          badge={
            <span
              className="flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold font-sans uppercase tracking-wider"
              style={{ background: "rgba(29,45,104,0.08)", color: "var(--brand-navy)", border: "1px solid rgba(29,45,104,0.15)" }}
            >
              <Scissors className="w-3 h-3" aria-hidden="true" />
              Medical
            </span>
          }
          action={
            <Link
              href="/dashboard/procedures/create"
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 hover:brightness-105 active:scale-[0.98] shrink-0"
              style={{ background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.3)" }}
            >
              <Plus className="w-4 h-4" aria-hidden="true" />
              Add Procedure
            </Link>
          }
        />

        {/* Error */}
        {listError && (
          <div role="alert" className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 font-sans flex items-center justify-between gap-4 flex-wrap">
            <span>{listError}</span>
          </div>
        )}

        {/* Stats */}
        <DashboardStatsGrid>
          {STATS.map((stat) => {
            const Icon = stat.icon
            return (
              <div key={stat.label} className="bg-card rounded-2xl p-5 border border-border flex items-center gap-4">
                <div className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${stat.color}18` }}>
                  <Icon className="w-5 h-5" style={{ color: stat.color }} aria-hidden="true" />
                </div>
                <div>
                  <p className="text-2xl font-bold text-foreground font-sans leading-none">{stat.value}</p>
                  <p className="text-xs text-muted-foreground font-sans mt-1">{stat.label}</p>
                </div>
              </div>
            )
          })}
        </DashboardStatsGrid>

        <DashboardTableCard
          toolbar={
            <div className="flex flex-col w-full gap-0">
              <div className="flex flex-wrap items-center gap-3 w-full">
                <div className="flex items-center gap-2 flex-1 min-w-[180px] px-3.5 py-2.5 rounded-xl bg-muted mb-2 border border-border">
                  <Search className="w-3.5 h-3.5 text-muted-foreground shrink-0" aria-hidden="true" />
                  <input
                    type="text"
                    value={search}
                    onChange={(e) => {
                      setSearch(e.target.value)
                      tableView.resetToFirstPage()
                    }}
                    placeholder="Search by name or category..."
                    className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground font-sans outline-none"
                    aria-label="Search procedures"
                  />
                </div>

                <div className="flex items-center gap-1 rounded-xl p-1 bg-muted border border-border">
                  {(["all", "published", "draft"] as const).map((s) => (
                    <button
                      key={s}
                      onClick={() => {
                        setFilterStatus(s)
                        tableView.resetToFirstPage()
                      }}
                      className="px-3 py-1.5 cursor-pointer rounded-lg text-xs font-semibold font-sans transition-all"
                      style={
                        filterStatus === s
                          ? { background: s === "published" ? "var(--brand-green)" : s === "draft" ? "#F59E0B" : "var(--brand-navy)", color: "white" }
                          : { color: "var(--muted-foreground)" }
                      }
                    >
                      {s === "all" ? "All" : s === "published" ? "Published" : "Draft"}
                    </button>
                  ))}
                </div>
              </div>

              <DashboardTableViewControls
                sortOptions={tableView.sortOptions}
                sortKey={tableView.sortKey}
                onSortChange={tableView.setSortKey}
                pageSizeOptions={tableView.pageSizeOptions}
                itemsPerPage={tableView.itemsPerPage}
                onItemsPerPageChange={tableView.setItemsPerPage}
                viewAll={tableView.viewAll}
                onViewAllToggle={tableView.toggleViewAll}
                displayedCount={viewResult.displayedCount}
                totalCount={viewResult.totalItems}
                itemLabel="procedures"
                viewAllCapped={viewResult.viewAllCapped}
                disabled={loading || !tableView.hydrated}
              />
            </div>
          }
          footer={
            !loading && !tableView.viewAll && viewResult.totalItems > 0 ? (
              <DashboardTablePagination
                currentPage={tableView.currentPage}
                totalPages={totalPages}
                totalItems={viewResult.totalItems}
                pageSize={tableView.itemsPerPage}
                itemLabel="procedures"
                onPageChange={tableView.setCurrentPage}
              />
            ) : null
          }
        >
            <table className="w-full" aria-label="Procedures list">
              <thead>
                <tr className="border-b border-border">
                  {["Procedure", "Category", "Rating", "Featured", "Status", "Last updated", "Actions"].map((col) => (
                    <th key={col} className="text-left px-5 py-3.5 text-xs font-bold text-muted-foreground font-sans uppercase tracking-wider">
                      {col}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={7} className="px-5 py-16 text-center text-muted-foreground font-sans">
                      <Loader2 className="w-8 h-8 animate-spin inline-block" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
                      <p className="mt-3 text-sm">Loading procedures…</p>
                    </td>
                  </tr>
                ) : paginated.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="px-5 py-14 text-center text-muted-foreground text-sm font-sans">
                      {rows.length === 0 ? "No procedures yet. Create one using the button above." : "No procedures match your filters."}
                    </td>
                  </tr>
                ) : (
                  paginated.map((row) => (
                    <tr key={row.id} className="border-b border-border last:border-0 hover:bg-muted/40 transition-colors">
                      {/* Name cell */}
                      <td className="px-5 py-4 max-w-[240px]">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-xl shrink-0 overflow-hidden bg-muted flex items-center justify-center" aria-hidden="true">
                            {row.image ? (
                              // eslint-disable-next-line @next/next/no-img-element
                              <img src={row.image} alt="" className="w-full h-full object-cover" />
                            ) : (
                              <Scissors className="w-5 h-5" style={{ color: "var(--brand-navy)" }} />
                            )}
                          </div>
                          <div className="min-w-0">
                            <p className="flex items-center gap-1.5 text-sm font-semibold text-foreground font-sans leading-tight">
                              {row.isFeatured && (
                                <Star className="w-3.5 h-3.5 shrink-0" style={{ color: "var(--brand-green)" }} fill="currentColor" aria-label="Featured" />
                              )}
                              <span className="line-clamp-1 min-w-0">{row.name}</span>
                            </p>
                            <p className="text-xs text-muted-foreground font-sans mt-0.5">
                              {row.reviewCount} {row.reviewCount === 1 ? "review" : "reviews"}
                            </p>
                          </div>
                        </div>
                      </td>

                      {/* Category */}
                      <td className="px-5 py-4">
                        <span
                          className="inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-bold font-sans"
                          style={{ background: `${getCategoryColor(row.category, row.categoryColor)}18`, color: getCategoryColor(row.category, row.categoryColor) }}
                        >
                          {row.category}
                        </span>
                      </td>

                      {/* Rating */}
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-1.5">
                          <Star className="w-3.5 h-3.5" style={{ color: "#F59E0B" }} fill="#F59E0B" aria-hidden="true" />
                          <span className="text-sm font-semibold text-foreground font-sans">{row.rating.toFixed(1)}</span>
                        </div>
                      </td>

                      {/* Featured */}
                      <td className="px-5 py-4">
                        {row.isFeatured ? (
                          <span className="inline-flex items-center gap-1 text-xs font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
                            <Star className="w-3.5 h-3.5" fill="currentColor" aria-hidden="true" /> Yes
                          </span>
                        ) : (
                          <span className="text-xs font-sans text-muted-foreground">No</span>
                        )}
                      </td>

                      {/* Status */}
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-2">
                          <span className="w-2 h-2 rounded-full" style={{ background: row.status === "published" ? "var(--brand-green)" : "#F59E0B" }} aria-hidden="true" />
                          <span className="text-xs font-semibold font-sans capitalize" style={{ color: row.status === "published" ? "var(--brand-green)" : "#F59E0B" }}>
                            {row.status}
                          </span>
                        </div>
                      </td>

                      {/* Last updated (content audit) */}
                      <td className="px-5 py-4">
                        <ContentAuditInfo audit={row.audit} mode="updated" variant="table" />
                      </td>

                      {/* Actions */}
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-1">
                          <Link
                            href={`/dashboard/procedures/${row.id}/edit`}
                            className="p-2 cursor-pointer rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors inline-flex"
                            title="Edit"
                            aria-label={`Edit procedure: ${row.name}`}
                          >
                            <Pencil className="w-3.5 h-3.5" aria-hidden="true" />
                          </Link>
                          <button
                            type="button"
                            onClick={() => setDeleteTarget(row)}
                            className="p-2 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                            title="Delete"
                            aria-label={`Delete procedure: ${row.name}`}
                          >
                            <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
        </DashboardTableCard>
      </DashboardPageContent>

      <DeleteConfirmModal
        open={deleteTarget !== null}
        userName={deleteTarget?.name ?? ""}
        isLoading={isDeleting}
        onConfirm={handleDelete}
        onClose={() => setDeleteTarget(null)}
      />
    </>
  )
}
