"use client"

import { useState, useMemo, useEffect, useCallback } from "react"
import Link from "next/link"
import { toast } from "sonner"
import {
  FileText,
  Plus,
  Search,
  Pencil,
  Trash2,
  Eye,
  BookOpen,
  Clock,
  Tag,
  Loader2,
  Star,
} from "lucide-react"
import { Navbar } from "@/components/dashboard/navbar"
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 { DeleteConfirmModal } from "@/components/dashboard/delete-confirm-modal"
import {
  LanguageFilterSelect,
  type LanguageFilterValue,
} from "@/components/dashboard/shared/LanguageFilterSelect"
import { getArticleAvailableLocales, type ArticleFilterLocale } from "@/lib/article-locale-filter"
import type { ContentAudit } from "@/types/content-audit"

type ArticleStatus = "published" | "draft"

interface Article {
  id: string
  slug: string
  title: string
  category: string
  categoryColor?: string
  author: string
  readingTime: string
  publishDate: string
  /** ISO string for sorting (display uses `publishDate`) */
  publishDateIso: string
  status: ArticleStatus
  image: string
  isFeatured?: boolean
  locales: ArticleFilterLocale[]
  audit: ContentAudit
}

type FilterStatus = "all" | ArticleStatus
type FilterCategory = "all" | string

const ARTICLES_TABLE_ID = "articles-table"

const ARTICLES_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: "publish-newest", label: "Publish date (newest)" },
  { value: "publish-oldest", label: "Publish date (oldest)" },
  { value: "title-asc", label: "Title A → Z" },
  { value: "title-desc", label: "Title Z → A" },
]

const ARTICLES_SORT_COMPARATORS: Record<string, (a: Article, b: Article) => 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(),
  "publish-newest": (a, b) => new Date(b.publishDateIso).getTime() - new Date(a.publishDateIso).getTime(),
  "publish-oldest": (a, b) => new Date(a.publishDateIso).getTime() - new Date(b.publishDateIso).getTime(),
  "title-asc": (a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: "base" }),
  "title-desc": (a, b) => b.title.localeCompare(a.title, 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)"
}

function formatReadingTime(raw: string): string {
  const t = raw.trim()
  if (!t) return "—"
  if (/min/i.test(t)) return t
  if (/^\d+$/.test(t)) return `${t} min`
  return t
}

function formatPublishDate(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    })
  } catch {
    return iso
  }
}

function Initials({ name }: { name: string }) {
  const parts = name.replace("Dr. ", "").split(" ")
  const initials = parts
    .map((p) => p[0])
    .join("")
    .slice(0, 2)
    .toUpperCase()
  return (
    <div
      className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold font-sans shrink-0"
      style={{ background: "var(--brand-navy)" }}
      aria-hidden="true"
    >
      {initials}
    </div>
  )
}

export default function ArticlesPage() {
  const [articles, setArticles] = useState<Article[]>([])
  const [loading, setLoading] = useState(true)
  const [listError, setListError] = useState<string | null>(null)

  const [search, setSearch] = useState("")
  const [filterStatus, setFilterStatus] = useState<FilterStatus>("all")
  const [filterCategory, setFilterCategory] = useState<FilterCategory>("all")
  const [filterLanguage, setFilterLanguage] = useState<LanguageFilterValue>("all")
  const [deleteTarget, setDeleteTarget] = useState<Article | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)

  const tableView = useDashboardTableViewControls<Article>({
    tableId: ARTICLES_TABLE_ID,
    defaultSortKey: "newest",
    defaultItemsPerPage: 6,
    sortOptions: ARTICLES_SORT_OPTIONS,
    comparators: ARTICLES_SORT_COMPARATORS,
  })

  const loadArticles = useCallback(async () => {
    setListError(null)
    setLoading(true)
    try {
      const res = await fetch("/api/admin/articles", { 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 articles")
      }
      const rows = Array.isArray(json.articles) ? json.articles : []
      setArticles(
        rows.map(
          (a: {
            id: string
            slug?: string
            title: string
            category: string
            categoryColor?: string
            author: string
            readingTime: string
            publishDate: string
            status: ArticleStatus
            image: string
            isFeatured?: boolean
            translations?: Partial<
              Record<
                ArticleFilterLocale,
                {
                  title?: string
                  subTitle?: string | null
                  author?: string
                  content?: string
                  tags?: string[]
                }
              >
            >
            audit?: ContentAudit
            createdAt?: string
            updatedAt?: string
          }) => ({
            id: a.id,
            slug: typeof a.slug === "string" ? a.slug : "",
            title: a.title,
            category: a.category,
            categoryColor: a.categoryColor,
            author: a.author,
            readingTime: formatReadingTime(a.readingTime),
            publishDateIso: typeof a.publishDate === "string" ? a.publishDate : "",
            publishDate: formatPublishDate(a.publishDate),
            status: a.status,
            image: a.image,
            isFeatured: Boolean(a.isFeatured),
            locales: getArticleAvailableLocales(a.translations ?? {}),
            audit:
              a.audit && typeof a.audit === "object"
                ? a.audit
                : {
                    createdAt: typeof a.createdAt === "string" ? a.createdAt : "",
                    updatedAt: typeof a.updatedAt === "string" ? a.updatedAt : "",
                    createdBy: null,
                    updatedBy: null,
                  },
          })
        )
      )
    } catch (e) {
      setListError(e instanceof Error ? e.message : "Failed to load")
      setArticles([])
    } finally {
      setLoading(false)
    }
  }, [])

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

  const totalArticles = articles.length
  const totalPublished = articles.filter((a) => a.status === "published").length
  const totalDraft = articles.filter((a) => a.status === "draft").length
  const totalCategories = new Set(articles.map((a) => a.category)).size

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

  const allCategories = useMemo(() => {
    const names = Array.from(new Set(articles.map((a) => a.category))).sort()
    return ["all", ...names] as const
  }, [articles])

  const categoryColorByName = useMemo(() => {
    const m = new Map<string, string | undefined>()
    for (const a of articles) {
      if (!m.has(a.category)) m.set(a.category, a.categoryColor)
    }
    return m
  }, [articles])

  const filtered = useMemo(() => {
    return articles.filter((a) => {
      const q = search.toLowerCase()
      const matchSearch =
        a.title.toLowerCase().includes(q) ||
        a.slug.toLowerCase().includes(q) ||
        a.author.toLowerCase().includes(q) ||
        a.category.toLowerCase().includes(q)
      const matchStatus = filterStatus === "all" || a.status === filterStatus
      const matchCat = filterCategory === "all" || a.category === filterCategory
      const matchLanguage =
        filterLanguage === "all" || a.locales.includes(filterLanguage)
      return matchSearch && matchStatus && matchCat && matchLanguage
    })
  }, [articles, search, filterStatus, filterCategory, filterLanguage])

  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

  async function handleDelete() {
    if (!deleteTarget) return
    setIsDeleting(true)
    try {
      const res = await fetch(`/api/admin/articles/${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")
      }
      setArticles((prev) => prev.filter((a) => a.id !== deleteTarget.id))
      toast.success("Article deleted")
      setDeleteTarget(null)
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Delete failed")
    } finally {
      setIsDeleting(false)
    }
  }

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

      <DashboardPageContent>
        <DashboardPageHeader
          title="Article Management"
          description="Create, manage and publish medical articles and guides."
          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(43,182,115,0.10)",
                color: "var(--brand-green)",
                border: "1px solid rgba(43,182,115,0.20)",
              }}
            >
              <FileText className="w-3 h-3" aria-hidden="true" />
              Content
            </span>
          }
          action={
            <Link
              href="/dashboard/articles/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" />
              New Article
            </Link>
          }
        />

        {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>
            <button
              type="button"
              onClick={() => void loadArticles()}
              className="rounded-xl border border-red-300 bg-white px-3 py-1.5 text-xs font-semibold text-red-900 hover:bg-red-50 cursor-pointer"
            >
              Retry
            </button>
          </div>
        )}

        <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 border border-border mb-2">
                  <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 title, slug, author or category..."
                    className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground font-sans outline-none"
                    aria-label="Search articles"
                  />
                </div>

                <LanguageFilterSelect
                  value={filterLanguage}
                  onChange={(value) => {
                    setFilterLanguage(value)
                    tableView.resetToFirstPage()
                  }}
                  disabled={loading}
                />

                <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="articles"
                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="articles"
                onPageChange={tableView.setCurrentPage}
              />
            ) : null
          }
        >
            <table className="w-full" aria-label="Articles list">
              <thead>
                <tr className="border-b border-border">
                  {["Article", "Category", "Author", "Reading Time", "Publish Date", "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={8} 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 articles…</p>
                    </td>
                  </tr>
                ) : paginated.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="px-5 py-14 text-center text-muted-foreground text-sm font-sans">
                      {articles.length === 0
                        ? "No articles yet. Create one using the button above."
                        : "No articles match your filters."}
                    </td>
                  </tr>
                ) : (
                  paginated.map((article) => (
                    <tr
                      key={article.id}
                      className="border-b border-border last:border-0 hover:bg-muted/40 transition-colors"
                    >
                      <td className="px-5 py-4 max-w-[240px]">
                        <div className="flex items-start gap-3">
                          <div
                            className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 overflow-hidden bg-muted"
                            style={{ background: article.image ? undefined : "rgba(29,45,104,0.08)" }}
                            aria-hidden="true"
                          >
                            {article.image ? (
                              // eslint-disable-next-line @next/next/no-img-element
                              <img src={article.image} alt="" className="w-full h-full object-cover" />
                            ) : (
                              <FileText className="w-4.5 h-4.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">
                              {article.isFeatured ? (
                                <Star
                                  className="w-3.5 h-3.5 shrink-0"
                                  style={{ color: "var(--brand-green)" }}
                                  fill="currentColor"
                                  aria-label="Featured"
                                />
                              ) : null}
                              <span className="line-clamp-1 min-w-0">{article.title}</span>
                            </p>
                            <p className="text-xs text-muted-foreground font-sans mt-0.5 line-clamp-1">
                              {article.slug || "—"}
                            </p>
                          </div>
                        </div>
                      </td>

                      <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(article.category, article.categoryColor)}18`,
                            color: getCategoryColor(article.category, article.categoryColor),
                          }}
                        >
                          {article.category}
                        </span>
                      </td>

                      <td className="px-5 py-4">
                        <div className="flex items-center gap-2">
                          
                          <span className="text-sm text-foreground font-sans whitespace-nowrap">
                            {article.author || "—"}
                          </span>
                        </div>
                      </td>

                      <td className="px-5 py-4">
                        <div className="flex items-center gap-1.5">
                          <Clock className="w-3.5 h-3.5 text-muted-foreground" aria-hidden="true" />
                          <span className="text-sm text-muted-foreground font-sans">{article.readingTime}</span>
                        </div>
                      </td>

                      <td className="px-5 py-4">
                        <span className="text-xs text-muted-foreground font-sans">{article.publishDate}</span>
                      </td>

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

                      <td className="px-5 py-4">
                        <ContentAuditInfo audit={article.audit} mode="updated" variant="table" />
                      </td>

                      <td className="px-5 py-4">
                        <div className="flex items-center gap-1">
                          <Link
                            href={`/dashboard/articles/${article.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 article: ${article.title}`}
                          >
                            <Pencil className="w-3.5 h-3.5" aria-hidden="true" />
                          </Link>
                          <button
                            type="button"
                            onClick={() => setDeleteTarget(article)}
                            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 article: ${article.title}`}
                          >
                            <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
        </DashboardTableCard>
      </DashboardPageContent>

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