// =============================================================================
// HeadlineSift.com — Category List Table
// =============================================================================
"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useTransition } from "react";
import { toggleCategoryStatus, deleteCategory } from "./actions";
import { cn } from "@/lib/utils";

// ============================================================================
// Types
// ============================================================================

export interface CategoryRow {
  id: string;
  name: string;
  slug: string;
  level: string;
  description: string | null;
  aiSafetyLevel: string;
  maxPublicStories: number;
  status: string;
  displayOrder: number;
  createdAt: Date;
  dependentCount: number;
}

interface CategoryTableProps {
  categories: CategoryRow[];
  searchQuery: string;
  levelFilter: string;
  editingId: string | null;
  onEdit: (id: string) => void;
  onAdd: () => void;
}

// ============================================================================
// Sub-components
// ============================================================================

function StatusBadge({ status }: { status: string }) {
  if (status === "ACTIVE") {
    return (
      <span className="inline-flex items-center rounded-full bg-green-50 px-2 py-0.5 text-2xs font-semibold uppercase tracking-wider text-green-700">
        Active
      </span>
    );
  }
  return (
    <span className="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-2xs font-semibold uppercase tracking-wider text-slate-600">
      Inactive
    </span>
  );
}

function LevelBadge({ level }: { level: string }) {
  const styles: Record<string, string> = {
    GLOBAL: "badge bg-purple-50 text-purple-700",
    COUNTRY: "badge bg-blue-50 text-blue-700",
    BOTH: "badge bg-teal-50 text-teal-700",
  };
  return (
    <span className={styles[level] ?? "badge bg-slate-100 text-slate-600"}>
      {level === "BOTH" ? "Global + Country" : level.charAt(0) + level.slice(1).toLowerCase()}
    </span>
  );
}

function AiSafetyBadge({ level }: { level: string }) {
  const styles: Record<string, string> = {
    LOW: "badge bg-green-50 text-green-700",
    MEDIUM: "badge bg-amber-50 text-amber-700",
    HIGH: "badge bg-red-50 text-red-700",
  };
  return (
    <span className={styles[level] ?? "badge bg-slate-100 text-slate-600"}>
      {level}
    </span>
  );
}

function EmptyState({ hasSearch, hasFilter }: { hasSearch: boolean; hasFilter: boolean }) {
  if (hasSearch || hasFilter) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <span className="text-5xl" aria-hidden="true">🔍</span>
        <h3 className="mt-4 text-lg font-semibold text-heading">No categories found</h3>
        <p className="mt-2 max-w-md text-sm text-body-muted">
          Try adjusting your search query or level filter.
        </p>
      </div>
    );
  }
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <span className="text-5xl" aria-hidden="true">🏷️</span>
      <h3 className="mt-4 text-lg font-semibold text-heading">No categories yet</h3>
      <p className="mt-2 max-w-md text-sm text-body-muted">
        Add your first category to start organizing news by topic.
      </p>
    </div>
  );
}

function DeleteButton({ category }: { category: CategoryRow }) {
  const [isPending, startTransition] = useTransition();

  const handleDelete = useCallback(() => {
    if (category.dependentCount > 0) {
      alert(
        `Cannot delete "${category.name}" — it has ${category.dependentCount} dependent record(s). Remove or reassign those records first.`,
      );
      return;
    }
    const confirmed = window.confirm(
      `Delete "${category.name}" (${category.slug})?\n\nThis action cannot be undone.`,
    );
    if (!confirmed) {
      return;
    }
    startTransition(() => {
      deleteCategory(category.id);
    });
  }, [category, startTransition]);

  return (
    <button
      type="button"
      onClick={handleDelete}
      disabled={isPending}
      className={cn(
        "rounded px-2 py-1 text-2xs font-medium transition-colors",
        category.dependentCount > 0
          ? "cursor-not-allowed text-body-muted/40"
          : "text-red-600 hover:bg-red-50",
      )}
      title={
        category.dependentCount > 0
          ? `${category.dependentCount} dependent record(s) — cannot delete`
          : "Delete category"
      }
    >
      {isPending ? "Deleting…" : "Delete"}
    </button>
  );
}

// ============================================================================
// Table Component
// ============================================================================

export default function CategoryTable({
  categories,
  searchQuery,
  levelFilter,
  editingId,
  onEdit,
  onAdd,
}: CategoryTableProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const updateParams = useCallback(
    (updates: Record<string, string | null>) => {
      const params = new URLSearchParams(searchParams.toString());
      for (const [key, value] of Object.entries(updates)) {
        if (value) {
          params.set(key, value);
        } else {
          params.delete(key);
        }
      }
      params.delete("edit");
      params.delete("success");
      params.delete("error");
      startTransition(() => {
        router.push(`/admin/categories?${params.toString()}`);
      });
    },
    [router, searchParams, startTransition],
  );

  const handleSearch = useCallback(
    (value: string) => {
      updateParams({ search: value || null });
    },
    [updateParams],
  );

  const handleLevelFilter = useCallback(
    (value: string) => {
      updateParams({ level: value || null });
    },
    [updateParams],
  );

  const handleToggleStatus = useCallback(
    (id: string) => {
      startTransition(() => {
        toggleCategoryStatus(id);
      });
    },
    [startTransition],
  );

  const hasSearch = searchQuery.length > 0;
  const hasFilter = levelFilter.length > 0;

  return (
    <div className="space-y-4">
      {/* Toolbar: Search + Level Filter + Add */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          {/* Search */}
          <div className="relative max-w-sm">
            <svg
              className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-body-muted"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
              />
            </svg>
            <input
              type="search"
              defaultValue={searchQuery}
              placeholder="Search by name or slug…"
              onChange={(e) => handleSearch(e.target.value)}
              className="input pl-9"
            />
          </div>

          {/* Level Filter */}
          <select
            value={levelFilter}
            onChange={(e) => handleLevelFilter(e.target.value)}
            className="input max-w-[12rem]"
          >
            <option value="">All levels</option>
            <option value="GLOBAL">Global only</option>
            <option value="COUNTRY">Country only</option>
            <option value="BOTH">Both</option>
          </select>
        </div>

        {/* Add Button */}
        <button type="button" onClick={onAdd} className="btn-primary">
          <svg
            className="h-4 w-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 4.5v15m7.5-7.5h-15"
            />
          </svg>
          Add Category
        </button>
      </div>

      {/* Table or Empty State */}
      {categories.length === 0 ? (
        <div className="card">
          <EmptyState hasSearch={hasSearch} hasFilter={hasFilter} />
        </div>
      ) : (
        <div className="card overflow-x-auto p-0">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-surface-secondary text-left">
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted w-12">
                  #
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">
                  Name
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden sm:table-cell">
                  Slug
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">
                  Level
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden md:table-cell">
                  AI Safety
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden lg:table-cell w-16">
                  Max
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">
                  Status
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted w-28">
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {categories.map((cat, index) => {
                const isEditing = editingId === cat.id;
                return (
                  <tr
                    key={cat.id}
                    className={cn(
                      "transition-colors hover:bg-surface-secondary",
                      isEditing && "bg-brand-50/50",
                    )}
                  >
                    <td className="px-4 py-3 text-xs text-body-muted tabular-nums">
                      {cat.displayOrder || index + 1}
                    </td>

                    <td className="px-4 py-3">
                      <span className="font-medium text-heading truncate block max-w-[14rem]">
                        {cat.name}
                      </span>
                    </td>

                    <td className="px-4 py-3 hidden sm:table-cell">
                      <code className="rounded bg-surface-tertiary px-1.5 py-0.5 text-xs font-mono text-body-muted">
                        {cat.slug}
                      </code>
                    </td>

                    <td className="px-4 py-3">
                      <LevelBadge level={cat.level} />
                    </td>

                    <td className="px-4 py-3 hidden md:table-cell">
                      <AiSafetyBadge level={cat.aiSafetyLevel} />
                    </td>

                    <td className="px-4 py-3 text-xs text-body-muted tabular-nums hidden lg:table-cell">
                      {cat.maxPublicStories}
                    </td>

                    <td className="px-4 py-3">
                      <StatusBadge status={cat.status} />
                    </td>

                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        <button
                          type="button"
                          onClick={() => onEdit(cat.id)}
                          className="rounded px-2 py-1 text-2xs font-medium text-brand-600 hover:bg-brand-50 transition-colors"
                        >
                          Edit
                        </button>

                        <button
                          type="button"
                          onClick={() => handleToggleStatus(cat.id)}
                          disabled={isPending}
                          className={cn(
                            "rounded px-2 py-1 text-2xs font-medium transition-colors",
                            cat.status === "ACTIVE"
                              ? "text-amber-600 hover:bg-amber-50"
                              : "text-green-600 hover:bg-green-50",
                          )}
                        >
                          {cat.status === "ACTIVE" ? "Deactivate" : "Activate"}
                        </button>

                        <DeleteButton category={cat} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Footer */}
          <div className="border-t border-border px-4 py-3 text-xs text-body-muted">
            {categories.length} {categories.length === 1 ? "category" : "categories"}
            {hasSearch && (
              <>
                {" "}
                matching &ldquo;{searchQuery}&rdquo;
              </>
            )}
            {hasFilter && (
              <>
                {" "}
                · level: {levelFilter}
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
