'use client';

import { useState } from 'react';
import { useParams } from 'next/navigation';
import { Plus } from 'lucide-react';
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { Button } from '@/components/ui/button';
import { DataTable } from '@/components/shared/data-table';
import { FilterBar } from '@/components/shared/filter-bar';
import { SavedViewsDropdown } from '@/components/shared/saved-views-dropdown';
import { PageHeader } from '@/components/shared/page-header';
import { EmptyState } from '@/components/shared/empty-state';
import { TableSkeleton } from '@/components/shared/loading-skeleton';
import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { ClientForm } from '@/components/clients/client-form';
import { clientFilterDefinitions } from '@/components/clients/client-filters';
import { getClientColumns, type ClientRow } from '@/components/clients/client-columns';
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

export function ClientList() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const queryClient = useQueryClient();

  const [createOpen, setCreateOpen] = useState(false);
  const [editClient, setEditClient] = useState<ClientRow | null>(null);
  const [archiveClient, setArchiveClient] = useState<ClientRow | null>(null);

  const {
    data,
    pagination,
    isLoading,
    isFetching,
    sort,
    setSort,
    setPage,
    setPageSize,
    filters,
    setFilter,
    clearFilters,
  } = usePaginatedQuery<ClientRow>({
    queryKey: ['clients'],
    endpoint: '/api/v1/clients',
    filterDefinitions: clientFilterDefinitions,
  });

  useRealtimeInvalidation({
    'client:created': [['clients']],
    'client:updated': [['clients']],
    'client:archived': [['clients']],
    'client:restored': [['clients']],
  });

  const archiveMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/clients/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clients'] });
      setArchiveClient(null);
    },
  });

  const columns = getClientColumns({
    portSlug,
    onEdit: (client) => setEditClient(client),
    onArchive: (client) => setArchiveClient(client),
  });

  return (
    <div className="space-y-4">
      <PageHeader
        title="Clients"
        description="Manage your client records"
        variant="gradient"
        actions={
          <PermissionGate resource="clients" action="create">
            <Button size="sm" onClick={() => setCreateOpen(true)}>
              <Plus className="mr-1.5 h-4 w-4" />
              New Client
            </Button>
          </PermissionGate>
        }
      />

      <div className="flex items-center gap-2">
        <FilterBar
          filters={clientFilterDefinitions}
          values={filters}
          onChange={setFilter}
          onClear={clearFilters}
        />
        <SavedViewsDropdown
          entityType="clients"
          currentFilters={filters}
          currentSort={sort}
          onApplyView={(savedFilters, _savedSort) => {
            clearFilters();
            Object.entries(savedFilters).forEach(([key, val]) => setFilter(key, val));
          }}
        />
      </div>

      {isLoading ? (
        <TableSkeleton />
      ) : (
        <DataTable
          columns={columns}
          data={data}
          pagination={pagination}
          onPaginationChange={(p, ps) => {
            setPage(p);
            setPageSize(ps);
          }}
          sort={sort}
          onSortChange={setSort}
          isLoading={isFetching && !isLoading}
          getRowId={(row) => row.id}
          emptyState={
            <EmptyState
              title="No clients found"
              description="Get started by adding your first client."
              action={{ label: 'New Client', onClick: () => setCreateOpen(true) }}
            />
          }
        />
      )}

      <ClientForm open={createOpen} onOpenChange={setCreateOpen} />

      {editClient && (
        <ClientForm
          open={!!editClient}
          onOpenChange={(open) => !open && setEditClient(null)}
          client={editClient as unknown as NonNullable<Parameters<typeof ClientForm>[0]['client']>}
        />
      )}

      <ArchiveConfirmDialog
        open={!!archiveClient}
        onOpenChange={(open) => !open && setArchiveClient(null)}
        entityName={archiveClient?.fullName ?? ''}
        entityType="Client"
        isArchived={false}
        onConfirm={() => archiveClient && archiveMutation.mutate(archiveClient.id)}
        isLoading={archiveMutation.isPending}
      />
    </div>
  );
}
