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

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

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

export interface SourceMappingRow {
  id: string;
  sourceId: string;
  countryId: string;
  categoryId: string;
  priority: number;
  status: string;
  createdAt: Date;
  // From include relations
  sourceName: string;
  sourceType: string;
  countryName: string;
  countryCode: string;
  categoryName: string;
  categorySlug: string;
  categoryLevel: string;
}

interface SourceOption {
  id: string;
  name: string;
  sourceType: string;
}

interface CountryOption {
  id: string;
  name: string;
  code: string;
}

interface CategoryOption {
  id: string;
  name: string;
  slug: string;
  level: string;
}

interface SourceMappingTableProps {
  mappings: SourceMappingRow[];
  sourceFilter: string | null;
  countryFilter: string | null;
  categoryFilter: string | null;
  sourceOptions: SourceOption[];
  countryOptions: CountryOption[];
  categoryOptions: CategoryOption[];
  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 TypeBadge({ type }: { type: string }) {
  const colors: Record<string, string> = {
    RSS: "bg-blue-50 text-blue-700",
    API: "bg-purple-50 text-purple-700",
    MANUAL: "bg-slate-100 text-slate-600",
    SCRAPE: "bg-amber-50 text-amber-700",
  };

  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full px-1.5 py-0.5 text-2xs font-medium",
        colors[type] ?? "bg-slate-100 text-slate-600",
      )}
    >
      {type}
    </span>
  );
}

function LevelBadge({ level }: { level: string }) {
  const colors: Record<string, string> = {
    GLOBAL: "bg-indigo-50 text-indigo-700",
    COUNTRY: "bg-teal-50 text-teal-700",
    BOTH: "bg-violet-50 text-violet-700",
  };

  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full px-1.5 py-0.5 text-2xs font-medium",
        colors[level] ?? "bg-slate-100 text-slate-600",
      )}
    >
      {level}
    </span>
  );
}

function EmptyState({ hasFilters }: { hasFilters: boolean }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <span className="text-5xl" aria-hidden="true">
        {hasFilters ? "🔍" : "🔗"}
      </span>
      <h3 className="mt-4 text-lg font-semibold text-heading">
        {hasFilters ? "No mappings match your filters" : "No source mappings yet"}
      </h3>
      <p className="mt-2 max-w-md text-sm text-body-muted">
        {hasFilters
          ? "Try clearing one or more filters."
          : "Map sources to countries and categories to control where news content is fetched and classified."}
      </p>
    </div>
  );
}

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

  const handleDelete = useCallback(() => {
    const confirmed = window.confirm(
      `Delete mapping "${mapping.sourceName}" → "${mapping.countryName}" / "${mapping.categoryName}"?\n\nThis action cannot be undone.`,
    );
    if (!confirmed) {
      return;
    }
    startTransition(() => {
      deleteSourceMapping(mapping.id);
    });
  }, [mapping, startTransition]);

  return (
    <button
      type="button"
      onClick={handleDelete}
      disabled={isPending}
      className="rounded px-2 py-1 text-2xs font-medium text-red-600 hover:bg-red-50 transition-colors"
      title="Delete mapping"
    >
      {isPending ? "Deleting…" : "Delete"}
    </button>
  );
}

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

export default function SourceMappingTable({
  mappings,
  sourceFilter,
  countryFilter,
  categoryFilter,
  sourceOptions,
  countryOptions,
  categoryOptions,
  editingId,
  onEdit,
  onAdd,
}: SourceMappingTableProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  // Build URL with filter changes
  const navigate = useCallback(
    (overrides: Record<string, string | null>) => {
      const params = new URLSearchParams(searchParams.toString());
      for (const [key, value] of Object.entries(overrides)) {
        if (value === null) {
          params.delete(key);
        } else {
          params.set(key, value);
        }
      }
      params.delete("edit");
      startTransition(() => {
        router.push(`/admin/source-mappings?${params.toString()}`);
      });
    },
    [router, searchParams, startTransition],
  );

  // Toggle status
  const handleToggleStatus = useCallback(
    (id: string) => {
      startTransition(() => {
        toggleSourceMappingStatus(id);
      });
    },
    [startTransition],
  );

  const hasFilters = sourceFilter !== null || countryFilter !== null || categoryFilter !== null;

  return (
    <div className="space-y-4">
      {/* ── Filter Toolbar ── */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        {/* Filters */}
        <div className="flex flex-wrap items-center gap-3">
          {/* Source Filter */}
          <select
            value={sourceFilter ?? ""}
            onChange={(e) => navigate({ source: e.target.value || null })}
            className="input text-xs"
            style={{ maxWidth: "12rem" }}
          >
            <option value="">All sources</option>
            {sourceOptions.map((s) => (
              <option key={s.id} value={s.id}>
                {s.name}
              </option>
            ))}
          </select>

          {/* Country Filter */}
          <select
            value={countryFilter ?? ""}
            onChange={(e) => navigate({ country: e.target.value || null })}
            className="input text-xs"
            style={{ maxWidth: "10rem" }}
          >
            <option value="">All countries</option>
            {countryOptions.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>

          {/* Category Filter */}
          <select
            value={categoryFilter ?? ""}
            onChange={(e) => navigate({ category: e.target.value || null })}
            className="input text-xs"
            style={{ maxWidth: "10rem" }}
          >
            <option value="">All categories</option>
            {categoryOptions.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>

          {/* Active filter indicator */}
          {hasFilters && (
            <span className="text-2xs text-body-muted">
              {mappings.length} result{mappings.length !== 1 ? "s" : ""}
            </span>
          )}
        </div>

        {/* Add Button */}
        <button type="button" onClick={onAdd} className="btn-primary shrink-0">
          <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 Mapping
        </button>
      </div>

      {/* ── Table or Empty State ── */}
      {mappings.length === 0 ? (
        <div className="card">
          <EmptyState hasFilters={hasFilters} />
        </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">
                  Source
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">
                  Country
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden sm:table-cell">
                  Category
                </th>
                <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden md:table-cell w-16">
                  Priority
                </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">
              {mappings.map((mapping) => {
                const isEditing = editingId === mapping.id;
                return (
                  <tr
                    key={mapping.id}
                    className={cn(
                      "transition-colors hover:bg-surface-secondary",
                      isEditing && "bg-brand-50/50",
                    )}
                  >
                    {/* Source */}
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-heading truncate max-w-[180px]">
                          {mapping.sourceName}
                        </span>
                        <TypeBadge type={mapping.sourceType} />
                      </div>
                    </td>

                    {/* Country */}
                    <td className="px-4 py-3">
                      <span className="font-medium text-heading">
                        {mapping.countryName}
                      </span>
                      <code className="ml-1.5 rounded bg-surface-tertiary px-1 py-0.5 text-2xs font-mono text-body-muted">
                        {mapping.countryCode}
                      </code>
                    </td>

                    {/* Category */}
                    <td className="px-4 py-3 hidden sm:table-cell">
                      <div className="flex items-center gap-2">
                        <span className="text-body">
                          {mapping.categoryName}
                        </span>
                        <LevelBadge level={mapping.categoryLevel} />
                      </div>
                    </td>

                    {/* Priority */}
                    <td className="px-4 py-3 hidden md:table-cell tabular-nums text-body-muted">
                      {mapping.priority}
                    </td>

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

                    {/* Actions */}
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        {/* Edit */}
                        <button
                          type="button"
                          onClick={() => onEdit(mapping.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(mapping.id)}
                          disabled={isPending}
                          className={cn(
                            "rounded px-2 py-1 text-2xs font-medium transition-colors",
                            mapping.status === "ACTIVE"
                              ? "text-amber-600 hover:bg-amber-50"
                              : "text-green-600 hover:bg-green-50",
                          )}
                        >
                          {mapping.status === "ACTIVE" ? "Deactivate" : "Activate"}
                        </button>

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

          {/* Footer: count */}
          <div className="border-t border-border px-4 py-3 text-xs text-body-muted">
            {mappings.length} {mappings.length === 1 ? "mapping" : "mappings"}
          </div>
        </div>
      )}
    </div>
  );
}
