'use client';

import { useQuery } from '@tanstack/react-query';
import { useParams } from 'next/navigation';

import { DetailLayout } from '@/components/shared/detail-layout';
import { CompanyDetailHeader } from '@/components/companies/company-detail-header';
import { getCompanyTabs } from '@/components/companies/company-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import type { Address } from '@/components/shared/addresses-editor';

export interface CompanyData {
  id: string;
  portId: string;
  name: string;
  legalName: string | null;
  taxId: string | null;
  registrationNumber: string | null;
  incorporationCountryIso: string | null;
  incorporationSubdivisionIso: string | null;
  incorporationDate: string | null;
  status: string;
  billingEmail: string | null;
  notes: string | null;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
  tags?: Array<{ id: string; name: string; color: string }>;
  addresses?: Address[];
}

interface CompanyDetailProps {
  companyId: string;
  currentUserId?: string;
}

export function CompanyDetail({ companyId, currentUserId }: CompanyDetailProps) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading } = useQuery<CompanyData>({
    queryKey: ['companies', companyId],
    queryFn: () =>
      apiFetch<{ data: CompanyData }>(`/api/v1/companies/${companyId}`).then((r) => r.data),
  });

  useRealtimeInvalidation({
    'company:updated': [['companies', companyId]],
    'company:archived': [['companies', companyId]],
    'company_membership:added': [['companies', companyId, 'members']],
    'company_membership:updated': [['companies', companyId, 'members']],
    'company_membership:ended': [['companies', companyId, 'members']],
  });

  const tabs = data ? getCompanyTabs({ companyId, portSlug, currentUserId, company: data }) : [];

  return (
    <DetailLayout
      header={data ? <CompanyDetailHeader company={data} /> : null}
      tabs={tabs}
      defaultTab="overview"
      isLoading={isLoading}
    />
  );
}
