'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { ClientDetailHeader } from '@/components/clients/client-detail-header';
import { getClientTabs } from '@/components/clients/client-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

interface ClientData {
  id: string;
  portId: string;
  fullName: string;
  companyName: string | null;
  nationality: string | null;
  isProxy: boolean;
  proxyType: string | null;
  actualOwnerName: string | null;
  yachtName: string | null;
  yachtLengthFt: string | null;
  yachtWidthFt: string | null;
  yachtDraftFt: string | null;
  yachtLengthM: string | null;
  yachtWidthM: string | null;
  yachtDraftM: string | null;
  berthSizeDesired: string | null;
  preferredContactMethod: string | null;
  preferredLanguage: string | null;
  timezone: string | null;
  source: string | null;
  sourceDetails: string | null;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
  contacts: Array<{
    id: string;
    channel: string;
    value: string;
    label: string | null;
    isPrimary: boolean;
    notes: string | null;
  }>;
  tags: Array<{
    id: string;
    name: string;
    color: string;
  }>;
}

interface ClientDetailProps {
  clientId: string;
  currentUserId?: string;
}

export function ClientDetail({ clientId, currentUserId }: ClientDetailProps) {
  const { data, isLoading } = useQuery<ClientData>({
    queryKey: ['clients', clientId],
    queryFn: () =>
      apiFetch<{ data: ClientData }>(`/api/v1/clients/${clientId}`).then((r) => r.data),
  });

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

  const tabs = data
    ? getClientTabs({ clientId, currentUserId, client: data })
    : [];

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