"use client"

import { Pencil, Trash2, LayoutGrid, FileText, UserRound, Building2, Stethoscope } from "lucide-react"
import { getMedicalIconComponent } from "@/components/dashboard/shared/IconPicker"
import { ContentAuditInfo } from "@/components/dashboard/shared/ContentAuditInfo"
import type { ContentAudit } from "@/types/content-audit"
import type { CategoryTranslationPayload } from "@/types/category-api"

export interface Category {
  id: string
  name: string
  slug: string
  description?: string
  color: string
  iconKey: string | null
  articleCount: number
  doctorCount: number
  hospitalCount: number
  procedureCount: number
  isVisible: boolean
  createdAt: string
  /** ISO string for sorting (display uses `createdAt`) */
  createdAtIso: string
  audit: ContentAudit
  translations: {
    en: CategoryTranslationPayload
    ar: CategoryTranslationPayload
    tr: CategoryTranslationPayload
  }
}

interface CategoryTableProps {
  categories: Category[]
  isLoading: boolean
  onEdit: (category: Category) => void
  onDelete: (category: Category) => void
  onToggleVisibility: (category: Category) => void
}

const LINKED_CONTENT_ITEMS = [
  {
    key: "articles" as const,
    countKey: "articleCount" as const,
    label: "Articles",
    icon: FileText,
    bg: "rgba(43,182,115,0.10)",
    color: "var(--brand-green)",
    border: "rgba(43,182,115,0.18)",
  },
  {
    key: "doctors" as const,
    countKey: "doctorCount" as const,
    label: "Doctors",
    icon: UserRound,
    bg: "rgba(29,45,104,0.08)",
    color: "var(--brand-navy)",
    border: "rgba(29,45,104,0.14)",
  },
  {
    key: "hospitals" as const,
    countKey: "hospitalCount" as const,
    label: "Hospitals",
    icon: Building2,
    bg: "rgba(14,165,233,0.10)",
    color: "#0284C7",
    border: "rgba(14,165,233,0.18)",
  },
  {
    key: "procedures" as const,
    countKey: "procedureCount" as const,
    label: "Procedures",
    icon: Stethoscope,
    bg: "rgba(245,158,11,0.10)",
    color: "#D97706",
    border: "rgba(245,158,11,0.20)",
  },
]

function CategoryLinkedContent({ category }: { category: Category }) {
  const items = LINKED_CONTENT_ITEMS.filter((item) => category[item.countKey] > 0)

  if (items.length === 0) {
    return (
      <span className="text-xs text-muted-foreground font-sans italic">No linked content</span>
    )
  }

  return (
    <div className="flex flex-wrap gap-1.5 max-w-[260px]">
      {items.map((item) => {
        const Icon = item.icon
        const count = category[item.countKey]
        return (
          <span
            key={item.key}
            className="inline-flex items-center gap-1.5 px-2 py-1 rounded-lg text-[11px] font-semibold font-sans leading-none border"
            style={{
              background: item.bg,
              color: item.color,
              borderColor: item.border,
            }}
            title={`${count} ${item.label.toLowerCase()}`}
          >
            <Icon className="w-3 h-3 shrink-0 opacity-80" aria-hidden="true" />
            <span className="tabular-nums">{count}</span>
            <span className="opacity-90">{item.label}</span>
          </span>
        )
      })}
    </div>
  )
}

export function CategoryTable({
  categories,
  isLoading,
  onEdit,
  onDelete,
}: CategoryTableProps) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full" aria-label="Categories list">
        <thead>
          <tr className="border-b border-border">
            {["Category", "Slug", "Linked Content", "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>
          {isLoading ? (
            <CategoryTableSkeleton />
          ) : categories.length === 0 ? (
            <CategoryTableEmpty />
          ) : (
            categories.map((cat) => (
              <CategoryRow
                key={cat.id}
                category={cat}
                onEdit={onEdit}
                onDelete={onDelete}
              />
            ))
          )}
        </tbody>
      </table>
    </div>
  )
}

/* ── Skeleton ── */
function CategoryTableSkeleton() {
  return (
    <>
      {Array.from({ length: 5 }).map((_, i) => (
        <tr key={i} className="border-b border-border last:border-0">
          {Array.from({ length: 5 }).map((__, j) => (
            <td key={j} className="px-5 py-4">
              <div
                className="h-4 bg-muted rounded-lg animate-pulse"
                style={{
                  width:
                    j === 0
                      ? "160px"
                      : j === 2
                        ? "180px"
                        : j === 3
                          ? "64px"
                          : "100px",
                }}
              />
            </td>
          ))}
        </tr>
      ))}
    </>
  )
}

/* ── Empty ── */
function CategoryTableEmpty() {
  return (
    <tr>
      <td colSpan={6} className="px-5 py-16 text-center">
        <div className="flex flex-col items-center gap-3">
          <div
            className="w-14 h-14 rounded-2xl flex items-center justify-center"
            style={{ background: "rgba(29,45,104,0.08)" }}
          >
            <LayoutGrid className="w-7 h-7" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
          </div>
          <p className="text-sm font-semibold text-foreground font-sans">No categories found</p>
          <p className="text-xs text-muted-foreground font-sans">Try adjusting your search or create a new category.</p>
        </div>
      </td>
    </tr>
  )
}

/* ── Row ── */
interface CategoryRowProps {
  category: Category
  onEdit: (c: Category) => void
  onDelete: (c: Category) => void
}

function CategoryRow({ category, onEdit, onDelete }: CategoryRowProps) {
  const IconComp = category.iconKey ? getMedicalIconComponent(category.iconKey) : null
  const hasLinkedContent =
    category.articleCount > 0 ||
    category.doctorCount > 0 ||
    category.hospitalCount > 0 ||
    category.procedureCount > 0
  return (
    <tr className="border-b border-border last:border-0 hover:bg-muted/40 transition-colors">
      {/* Name + color swatch */}
      <td className="px-5 py-4">
        <div className="flex items-center gap-3">
        <div
          className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0 text-white text-xs font-bold font-sans"
          style={{ background: category.color }}
        >
          {IconComp ? (
            <IconComp className="w-5 h-5" aria-hidden="true" />
          ) : (
            category.name.charAt(0).toUpperCase()
          )}
        </div>
          <div>
            <p className="text-sm font-semibold text-foreground font-sans">{category.name}</p>
            {category.description && (
              <p className="text-xs text-muted-foreground font-sans line-clamp-1 max-w-[200px]">
                {category.description}
              </p>
            )}
          </div>
        </div>
      </td>

      {/* Slug */}
      <td className="px-5 py-4">
        <span
          className="inline-block px-2.5 py-1 rounded-lg text-xs font-mono font-medium"
          style={{
            background: "rgba(29,45,104,0.07)",
            color: "var(--brand-navy)",
          }}
        >
          /{category.slug}
        </span>
      </td>

      {/* Linked content counts */}
      <td className="px-5 py-4 align-top">
        <CategoryLinkedContent category={category} />
      </td>

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

      {/* Actions */}
      <td className="px-5 py-4">
        <div className="flex items-center gap-1">
          <button
            onClick={() => onEdit(category)}
            className="p-2 cursor-pointer rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
            title="Edit"
            aria-label={`Edit category ${category.name}`}
          >
            <Pencil className="w-3.5 h-3.5" aria-hidden="true" />
          </button>
          <button
            onClick={() => {
              if (hasLinkedContent) return
              onDelete(category)
            }}
            disabled={hasLinkedContent}
            className={`p-2 rounded-lg transition-colors ${
              hasLinkedContent
                ? "text-muted-foreground/70 cursor-not-allowed opacity-70 border border-border/60"
                : "cursor-pointer text-muted-foreground hover:text-red-500 hover:bg-red-50"
            }`}
            title={
              hasLinkedContent
                ? "Cannot delete while linked content exists"
                : `Delete category ${category.name}`
            }
            aria-label={`Delete category ${category.name}`}
          >
            <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
          </button>
        </div>
      </td>
    </tr>
  )
}
