'use client';

import { useMemo, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { Plus, Archive, Tag as TagIcon, TagsIcon } from 'lucide-react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

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 { TagPicker } from '@/components/shared/tag-picker';
import { ColumnPicker } from '@/components/shared/column-picker';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { CompanyCard } from '@/components/companies/company-card';
import { CompanyForm } from '@/components/companies/company-form';
import { companyFilterDefinitions } from '@/components/companies/company-filters';
import {
  getCompanyColumns,
  COMPANY_COLUMN_OPTIONS,
  COMPANY_DEFAULT_HIDDEN,
  type CompanyRow,
} from '@/components/companies/company-columns';
import { useCreateFromUrl } from '@/hooks/use-create-from-url';
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { useTablePreferences } from '@/hooks/use-table-preferences';
import { useConfirmation } from '@/hooks/use-confirmation';
import { apiFetch } from '@/lib/api/client';

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

  const [createOpen, setCreateOpen] = useState(false);
  useCreateFromUrl(() => setCreateOpen(true));

  // Quick-create from the global command-search lands here with
  // `?create=1&prefill_name=…`. Hydrate the company-form's name field
  // so the rep doesn't retype.
  const searchParams = useSearchParams();
  const createPrefill = useMemo(() => {
    const name = searchParams?.get('prefill_name');
    return name ? { name } : undefined;
  }, [searchParams]);

  const [editCompany, setEditCompany] = useState<CompanyRow | null>(null);
  const [archiveCompany, setArchiveCompany] = useState<CompanyRow | null>(null);
  const [tagDialog, setTagDialog] = useState<{ ids: string[]; mode: 'add' | 'remove' } | null>(
    null,
  );
  const [tagChoice, setTagChoice] = useState<string[]>([]);

  const bulkMutation = useMutation({
    mutationFn: async (
      payload:
        | { action: 'archive'; ids: string[] }
        | { action: 'add_tag'; ids: string[]; tagId: string }
        | { action: 'remove_tag'; ids: string[]; tagId: string },
    ) =>
      apiFetch<{ data: { summary: { total: number; succeeded: number; failed: number } } }>(
        '/api/v1/companies/bulk',
        { method: 'POST', body: payload },
      ),
    onSuccess: (res) => {
      queryClient.invalidateQueries({ queryKey: ['companies'] });
      const s = res.data.summary;
      if (s.failed > 0) {
        toast.warning(`${s.succeeded} of ${s.total} succeeded. ${s.failed} failed.`);
      }
    },
  });

  const {
    data,
    pagination,
    isLoading,
    isFetching,
    sort,
    setSort,
    setPage,
    setPageSize,
    filters,
    setFilter,
    applyView,
    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),
  });

  // Persisted column visibility - same pattern as ClientList / BerthList.
  const { hidden, setHidden } = useTablePreferences('companies', COMPANY_DEFAULT_HIDDEN);
  const columnVisibility = Object.fromEntries(hidden.map((id) => [id, false]));

  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" aria-hidden />
              New Company
            </Button>
          </PermissionGate>
        }
      />

      <div className="flex items-center gap-2">
        <FilterBar
          filters={companyFilterDefinitions}
          values={filters}
          onChange={setFilter}
          onClear={clearFilters}
        />
        <div className="ml-auto flex items-center gap-2">
          <SavedViewsDropdown
            entityType="companies"
            onApplyView={(savedFilters, savedSort) => {
              applyView({ filters: savedFilters, sort: savedSort });
            }}
          />
          <ColumnPicker columns={COMPANY_COLUMN_OPTIONS} hidden={hidden} onChange={setHidden} />
        </div>
      </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}
          columnVisibility={columnVisibility}
          data={data}
          pagination={pagination}
          onPaginationChange={(p, ps) => {
            setPage(p);
            setPageSize(ps);
          }}
          sort={sort}
          onSortChange={setSort}
          isLoading={isFetching && !isLoading}
          getRowId={(row) => row.id}
          bulkActions={[
            {
              label: 'Add tag',
              icon: TagIcon,
              onClick: (ids) => {
                if (ids.length === 0) return;
                setTagChoice([]);
                setTagDialog({ ids, mode: 'add' });
              },
            },
            {
              label: 'Remove tag',
              icon: TagsIcon,
              onClick: (ids) => {
                if (ids.length === 0) return;
                setTagChoice([]);
                setTagDialog({ ids, mode: 'remove' });
              },
            },
            {
              label: 'Archive',
              icon: Archive,
              variant: 'destructive',
              onClick: async (ids) => {
                if (ids.length === 0) return;
                const ok = await confirm({
                  title: `Archive ${ids.length} compan${ids.length === 1 ? 'y' : 'ies'}`,
                  description: 'This can be undone from the archived list.',
                  confirmLabel: 'Archive',
                });
                if (!ok) return;
                bulkMutation.mutate({ action: 'archive', ids });
              },
            },
          ]}
          cardRender={(row) => (
            <CompanyCard
              company={row.original}
              portSlug={portSlug}
              onEdit={setEditCompany}
              onArchive={setArchiveCompany}
            />
          )}
          emptyState={
            <EmptyState
              title="No companies yet"
              description="Create your first company to get started."
              action={{ label: 'New Company', onClick: () => setCreateOpen(true) }}
            />
          }
        />
      )}

      <Dialog open={!!tagDialog} onOpenChange={(o) => !o && setTagDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{tagDialog?.mode === 'add' ? 'Add tag' : 'Remove tag'}</DialogTitle>
            <DialogDescription>
              {tagDialog?.mode === 'add'
                ? `Add a tag to ${tagDialog?.ids.length ?? 0} selected compan${tagDialog?.ids.length === 1 ? 'y' : 'ies'}.`
                : `Remove a tag from ${tagDialog?.ids.length ?? 0} selected compan${tagDialog?.ids.length === 1 ? 'y' : 'ies'}. Companies without the tag are unchanged.`}
            </DialogDescription>
          </DialogHeader>
          <div className="py-2">
            <TagPicker
              selectedIds={tagChoice}
              onChange={(ids) => setTagChoice(ids.slice(-1))}
              placeholder="Pick one tag…"
            />
            <p className="text-xs text-muted-foreground mt-2">
              Pick a single tag. To apply multiple tags, run the action once per tag.
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setTagDialog(null)}>
              Cancel
            </Button>
            <Button
              disabled={bulkMutation.isPending || tagChoice.length === 0}
              onClick={() => {
                if (!tagDialog || tagChoice.length === 0) return;
                const tagId = tagChoice[0];
                if (!tagId) return;
                bulkMutation.mutate(
                  {
                    action: tagDialog.mode === 'add' ? 'add_tag' : 'remove_tag',
                    ids: tagDialog.ids,
                    tagId,
                  },
                  { onSettled: () => setTagDialog(null) },
                );
              }}
            >
              Apply
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

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

      {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}
      />
      {confirmDialog}
    </div>
  );
}
