'use client';

import { useState, useEffect } from 'react';
import type { PaginationState } from '@tanstack/react-table';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { DataTable } from '@/components/data-table/DataTable';
import BackToDashboard from '@/components/BackToDashboard';
import { useRequirePermission } from '@/lib/useRequirePermission';

interface City {
  id: number;
  name: string;
  state_name: string;
  country_name: string;
  country_code: string;
}

export default function CityPage() {
  useRequirePermission('master_data.view_city');
  const { user } = useAuth();
  const [cities, setCities] = useState<City[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  // Server-side pagination + search — the cities table holds 150k+ rows,
  // so the backend pages and filters instead of the browser.
  const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
  const [search, setSearch] = useState('');

  const columns = [
    {
      id: 'srNo',
      header: 'City ID',
      cell: ({ row }: any) => (
        <span className="font-semibold text-slate-500 dark:text-slate-400">
          {row.original.id}
        </span>
      ),
    },
    {
      accessorKey: 'name',
      header: 'City Name',
      cell: ({ row }: any) => (
        <p className="font-extrabold text-slate-800 dark:text-white text-sm">
          {row.original.name}
        </p>
      ),
    },
    {
      accessorKey: 'state_name',
      header: 'State Name',
      cell: ({ row }: any) => (
        <span className="text-slate-650 dark:text-slate-350 font-semibold">
          {row.original.state_name || '-'}
        </span>
      ),
    },
    {
      accessorKey: 'country_name',
      header: 'Country Name',
      cell: ({ row }: any) => (
        <span className="text-slate-650 dark:text-slate-350 font-semibold">
          {row.original.country_name || '-'}
        </span>
      ),
    },
    {
      accessorKey: 'country_code',
      header: 'Country Code',
      cell: ({ row }: any) => (
        <span className="text-slate-600 dark:text-slate-400 font-semibold">
          {row.original.country_code || '-'}
        </span>
      ),
    },
  ];

  useEffect(() => {
    if (!user) return;
    let cancelled = false;
    setLoading(true);
    // Debounce so typing in search doesn't fire a request per keystroke.
    const timer = setTimeout(async () => {
      try {
        const res = (await api.get(
          `/master-data/cities?page=${pagination.pageIndex + 1}&page_size=${pagination.pageSize}&search=${encodeURIComponent(search)}`
        )) as any;
        if (cancelled) return;
        const data = res.data;
        if (data && Array.isArray(data.results)) {
          setCities(data.results);
          setTotal(data.count ?? data.results.length);
        } else if (Array.isArray(data)) {
          setCities(data);
          setTotal(data.length);
        } else {
          setCities([]);
          setTotal(0);
        }
      } catch (err) {
        if (!cancelled) {
          console.error('Failed to load cities:', err);
          setCities([]);
          setTotal(0);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, search ? 300 : 0);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [user, pagination, search]);

  const handleSearchChange = (value: string) => {
    setSearch(value);
    setPagination((p) => ({ ...p, pageIndex: 0 }));
  };

  if (!user) return null;

  return (
    <main className="flex-1 p-8 overflow-y-auto w-full space-y-6 max-w-7xl mx-auto">
      <BackToDashboard />
      <div>
        <p className="text-sm text-slate-500 dark:text-slate-400">
          View the master list of cities configuration.
        </p>
      </div>
      <DataTable
        columns={columns}
        data={cities}
        loading={loading}
        pageCount={Math.max(1, Math.ceil(total / pagination.pageSize))}
        controlledPagination={pagination}
        onPaginationChange={setPagination}
        controlledGlobalFilter={search}
        onGlobalFilterChange={handleSearchChange}
        searchPlaceholder="Search cities by name..."
        emptyStateTitle="No Cities Found"
        emptyStateDescription="The cities master database table is currently empty."
      />
    </main>
  );
}
