'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 { YachtForm } from '@/components/yachts/yacht-form';
import { yachtFilterDefinitions } from '@/components/yachts/yacht-filters';
import { getYachtColumns, type YachtRow } from '@/components/yachts/yacht-columns';
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

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

  const [createOpen, setCreateOpen] = useState(false);
  const [editYacht, setEditYacht] = useState<YachtRow | null>(null);
  const [archiveYacht, setArchiveYacht] = useState<YachtRow | null>(null);

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

  useRealtimeInvalidation({
    'yacht:created': [['yachts']],
    'yacht:updated': [['yachts']],
    'yacht:archived': [['yachts']],
    'yacht:ownership_transferred': [['yachts']],
  });

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

  const columns = getYachtColumns({
    portSlug,
    onEdit: (yacht) => setEditYacht(yacht),
    onArchive: (yacht) => setArchiveYacht(yacht),
  });

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

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

      {isLoading ? (
        <TableSkeleton />
      ) : !data.length ? (
        <EmptyState
          title="No yachts found"
          description="Get started by adding your first yacht."
          action={{ label: 'New Yacht', onClick: () => setCreateOpen(true) }}
        />
      ) : (
        <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 yachts found"
              description="Get started by adding your first yacht."
              action={{ label: 'New Yacht', onClick: () => setCreateOpen(true) }}
            />
          }
        />
      )}

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

      {editYacht && (
        <YachtForm
          open={!!editYacht}
          onOpenChange={(open) => !open && setEditYacht(null)}
          yacht={{
            id: editYacht.id,
            name: editYacht.name,
            hullNumber: editYacht.hullNumber,
            registration: editYacht.registration,
            lengthFt: editYacht.lengthFt,
            widthFt: editYacht.widthFt,
            draftFt: editYacht.draftFt,
            lengthM: editYacht.lengthM,
            widthM: editYacht.widthM,
            currentOwnerType: editYacht.currentOwnerType,
            currentOwnerId: editYacht.currentOwnerId,
            status: editYacht.status,
          }}
        />
      )}

      <ArchiveConfirmDialog
        open={!!archiveYacht}
        onOpenChange={(open) => !open && setArchiveYacht(null)}
        entityName={archiveYacht?.name ?? ''}
        entityType="Yacht"
        isArchived={false}
        onConfirm={() => archiveYacht && archiveMutation.mutate(archiveYacht.id)}
        isLoading={archiveMutation.isPending}
      />
    </div>
  );
}
