'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 { CompanyForm } from '@/components/companies/company-form';
import { companyFilterDefinitions } from '@/components/companies/company-filters';
import { getCompanyColumns, type CompanyRow } from '@/components/companies/company-columns';
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

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

  const [createOpen, setCreateOpen] = useState(false);
  const [editCompany, setEditCompany] = useState<CompanyRow | null>(null);
  const [archiveCompany, setArchiveCompany] = useState<CompanyRow | null>(null);

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

  useRealtimeInvalidation({
    'company:created': [['companies']],
    'company:updated': [['companies']],
    'company:archived': [['companies']],
  });

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

  const columns = getCompanyColumns({
    portSlug,
    onEdit: (company) => setEditCompany(company),
    onArchive: (company) => setArchiveCompany(company),
  });

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

      <div className="flex items-center gap-2">
        <FilterBar
          filters={companyFilterDefinitions}
          values={filters}
          onChange={setFilter}
          onClear={clearFilters}
        />
        <SavedViewsDropdown
          entityType="companies"
          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 companies yet"
          description="Create your first company to get started."
          action={{ label: 'New Company', 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 companies yet"
              description="Create your first company to get started."
              action={{ label: 'New Company', onClick: () => setCreateOpen(true) }}
            />
          }
        />
      )}

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

      {editCompany && (
        <CompanyForm
          open={!!editCompany}
          onOpenChange={(open) => !open && setEditCompany(null)}
          company={{
            id: editCompany.id,
            name: editCompany.name,
            legalName: editCompany.legalName,
            taxId: editCompany.taxId,
            registrationNumber: editCompany.registrationNumber,
            incorporationCountryIso: editCompany.incorporationCountryIso,
            incorporationSubdivisionIso: editCompany.incorporationSubdivisionIso,
            incorporationDate: editCompany.incorporationDate,
            status: editCompany.status,
            billingEmail: editCompany.billingEmail,
            notes: editCompany.notes,
          }}
        />
      )}

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