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

import { useState, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import CountryForm from "./CountryForm";
import CountryTable from "./CountryTable";
import type { CountryRow } from "./CountryTable";

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

interface EditCountryData {
  id: string;
  name: string;
  code: string;
  region: string | null;
  defaultLanguage: string;
  isGlobal: boolean;
  status: string;
  displayOrder: number;
}

interface CountriesPageClientProps {
  countries: CountryRow[];
  searchQuery: string;
  editCountry: EditCountryData | null;
  successMsg: string | null;
  errorMsg: string | null;
}

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

export function CountriesPageClient({
  countries,
  searchQuery,
  editCountry,
  successMsg,
  errorMsg,
}: CountriesPageClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showAddForm, setShowAddForm] = useState(false);

  // Navigate to edit mode (sets ?edit=<id>)
  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/countries?${params.toString()}`);
    },
    [router, searchParams],
  );

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

  // Cancel the form — clear edit param and hide add form
  const handleCancel = useCallback(() => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("edit");
    params.delete("success");
    params.delete("error");
    setShowAddForm(false);
    router.push(`/admin/countries?${params.toString()}`, { scroll: false });
  }, [router, searchParams]);

  // Is the form visible (either adding new or editing existing)?
  const showForm = showAddForm || editCountry !== 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">Countries</h1>
          <p className="mt-1 text-sm text-body-muted">
            Manage geographic regions for news filtering and source mapping.
          </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 && (
        <CountryForm
          editCountry={editCountry}
          onCancel={handleCancel}
        />
      )}

      {/* Country Table */}
      <CountryTable
        countries={countries}
        searchQuery={searchQuery}
        editingId={editCountry?.id ?? null}
        onEdit={handleEdit}
        onAdd={handleAdd}
      />
    </div>
  );
}
