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

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

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

export interface CountryRow {
  id: string;
  name: string;
  code: string;
  region: string | null;
  defaultLanguage: string;
  isGlobal: boolean;
  status: string;
  displayOrder: number;
  createdAt: Date;
  /** Count of dependent records (for delete gating). */
  dependentCount: number;
}

interface CountryTableProps {
  countries: CountryRow[];
  searchQuery: 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 EmptyState({
  hasSearch,
}: {
  hasSearch: boolean;
}) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <span className="text-5xl" aria-hidden="true">
        {hasSearch ? "🔍" : "🌍"}
      </span>
      <h3 className="mt-4 text-lg font-semibold text-heading">
        {hasSearch ? "No countries found" : "No countries yet"}
      </h3>
      <p className="mt-2 max-w-md text-sm text-body-muted">
        {hasSearch
          ? "Try adjusting your search query."
          : "Add your first country to start organizing news by geographic region."}
      </p>
    </div>
  );
}

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

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

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

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

export default function CountryTable({
  countries,
  searchQuery,
  editingId,
  onEdit,
  onAdd,
}: CountryTableProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  // Update the URL search param with debounce-like UX
  const handleSearch = useCallback(
    (value: string) => {
      const params = new URLSearchParams(searchParams.toString());
      if (value) {
        params.set("search", value);
      } else {
        params.delete("search");
      }
      // Remove edit param when searching
      params.delete("edit");
      startTransition(() => {
        router.push(`/admin/countries?${params.toString()}`);
      });
    },
    [router, searchParams, startTransition],
  );

  // Toggle status with optimistic-ish update via redirect
  const handleToggleStatus = useCallback(
    (id: string) => {
      startTransition(() => {
        toggleCountryStatus(id);
      });
    },
    [startTransition],
  );

  const hasSearch = searchQuery.length > 0;

  return (
    <div className="space-y-4">
      {/* Toolbar: Search + Add */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        {/* Search */}
        <div className="relative flex-1 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 code…"
            onChange={(e) => handleSearch(e.target.value)}
            className="input pl-9"
          />
        </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 Country
        </button>
      </div>

      {/* Table or Empty State */}
      {countries.length === 0 ? (
        <div className="card">
          <EmptyState hasSearch={hasSearch} />
        </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">
                  Code
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden sm:table-cell">
                  Region
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden md:table-cell">
                  Language
                </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 hidden lg:table-cell w-16">
                  Order
                </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">
              {countries.map((country, index) => {
                const isEditing = editingId === country.id;
                return (
                  <tr
                    key={country.id}
                    className={cn(
                      "transition-colors hover:bg-surface-secondary",
                      isEditing && "bg-brand-50/50",
                    )}
                  >
                    {/* Display order number */}
                    <td className="px-4 py-3 text-xs text-body-muted tabular-nums">
                      {country.displayOrder || index + 1}
                    </td>

                    {/* Name + Global badge */}
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-heading truncate">
                          {country.name}
                        </span>
                        {country.isGlobal && (
                          <span
                            className="shrink-0 text-sm"
                            title="Global country"
                            aria-label="Global country"
                          >
                            🌍
                          </span>
                        )}
                      </div>
                    </td>

                    {/* Code */}
                    <td className="px-4 py-3">
                      <code className="rounded bg-surface-tertiary px-1.5 py-0.5 text-xs font-mono text-body-muted">
                        {country.code}
                      </code>
                    </td>

                    {/* Region */}
                    <td className="px-4 py-3 text-body-muted hidden sm:table-cell">
                      {country.region ?? "—"}
                    </td>

                    {/* Language */}
                    <td className="px-4 py-3 text-body-muted hidden md:table-cell">
                      {country.defaultLanguage}
                    </td>

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

                    {/* Display Order (numeric) */}
                    <td className="px-4 py-3 text-xs text-body-muted tabular-nums hidden lg:table-cell">
                      {country.displayOrder}
                    </td>

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

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

                        {/* Delete */}
                        <DeleteButton country={country} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

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