// =============================================================================
// HeadlineSift.com — Source Mappings Page Client Shell
// =============================================================================
"use client";

import { useState, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import SourceMappingForm from "./SourceMappingForm";
import SourceMappingTable from "./SourceMappingTable";
import type { SourceMappingRow } from "./SourceMappingTable";

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

interface EditMappingData {
  id: string;
  sourceId: string;
  countryId: string;
  categoryId: string;
  priority: number;
  status: 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 SourceMappingsPageClientProps {
  mappings: SourceMappingRow[];
  sourceFilter: string | null;
  countryFilter: string | null;
  categoryFilter: string | null;
  sourceOptions: SourceOption[];
  countryOptions: CountryOption[];
  categoryOptions: CategoryOption[];
  editMapping: EditMappingData | null;
  successMsg: string | null;
  errorMsg: string | null;
}

// ============================================================================
// Component
// ============================================================================

export function SourceMappingsPageClient({
  mappings,
  sourceFilter,
  countryFilter,
  categoryFilter,
  sourceOptions,
  countryOptions,
  categoryOptions,
  editMapping,
  successMsg,
  errorMsg,
}: SourceMappingsPageClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showAddForm, setShowAddForm] = useState(false);

  // Navigate to edit mode
  const handleEdit = useCallback(
    (id: string) => {
      const params = new URLSearchParams(searchParams.toString());
      params.set("edit", id);
      params.delete("success");
      params.delete("error");
      setShowAddForm(false);
      router.push(`/admin/source-mappings?${params.toString()}`);
    },
    [router, searchParams],
  );

  // Show the add form
  const handleAdd = useCallback(() => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("edit");
    params.delete("success");
    params.delete("error");
    setShowAddForm(true);
    router.push(`/admin/source-mappings?${params.toString()}`, { scroll: false });
  }, [router, searchParams]);

  // Cancel the form
  const handleCancel = useCallback(() => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("edit");
    params.delete("success");
    params.delete("error");
    setShowAddForm(false);
    router.push(`/admin/source-mappings?${params.toString()}`, { scroll: false });
  }, [router, searchParams]);

  const showForm = showAddForm || editMapping !== null;

  return (
    <div className="animate-fade-in space-y-6">
      {/* Page Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold">Source Mappings</h1>
          <p className="mt-1 text-sm text-body-muted">
            Link sources to countries and categories to control where news is
            fetched and classified.
          </p>
        </div>
      </div>

      {/* Success Banner */}
      {successMsg && (
        <div
          className="rounded-md bg-green-50 p-3 text-sm text-green-700 ring-1 ring-inset ring-green-200"
          role="alert"
        >
          {successMsg}
        </div>
      )}

      {/* Error Banner (from URL params) */}
      {errorMsg && !successMsg && (
        <div
          className="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-inset ring-red-200"
          role="alert"
        >
          {errorMsg}
        </div>
      )}

      {/* Inline Form (Add or Edit) */}
      {showForm && (
        <SourceMappingForm
          editMapping={editMapping}
          sourceOptions={sourceOptions}
          countryOptions={countryOptions}
          categoryOptions={categoryOptions}
          onCancel={handleCancel}
        />
      )}

      {/* Mappings Table with Filters */}
      <SourceMappingTable
        mappings={mappings}
        sourceFilter={sourceFilter}
        countryFilter={countryFilter}
        categoryFilter={categoryFilter}
        sourceOptions={sourceOptions}
        countryOptions={countryOptions}
        categoryOptions={categoryOptions}
        editingId={editMapping?.id ?? null}
        onEdit={handleEdit}
        onAdd={handleAdd}
      />
    </div>
  );
}
