'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { YachtDetailHeader } from '@/components/yachts/yacht-detail-header';
import { getYachtTabs } from '@/components/yachts/yacht-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

export interface YachtData {
  id: string;
  portId: string;
  name: string;
  hullNumber: string | null;
  registration: string | null;
  flag: string | null;
  yearBuilt: number | null;
  builder: string | null;
  model: string | null;
  hullMaterial: string | null;
  lengthFt: string | null;
  widthFt: string | null;
  draftFt: string | null;
  lengthM: string | null;
  widthM: string | null;
  draftM: string | null;
  currentOwnerType: 'client' | 'company';
  currentOwnerId: string;
  status: string;
  notes: string | null;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
}

interface YachtDetailProps {
  yachtId: string;
  currentUserId?: string;
}

export function YachtDetail({ yachtId, currentUserId }: YachtDetailProps) {
  const { data, isLoading } = useQuery<YachtData>({
    queryKey: ['yachts', yachtId],
    queryFn: () => apiFetch<{ data: YachtData }>(`/api/v1/yachts/${yachtId}`).then((r) => r.data),
  });

  useRealtimeInvalidation({
    'yacht:updated': [['yachts', yachtId]],
    'yacht:archived': [['yachts', yachtId]],
    'yacht:ownership_transferred': [
      ['yachts', yachtId],
      ['yachts', yachtId, 'ownership-history'],
    ],
  });

  const tabs = data ? getYachtTabs({ yachtId, currentUserId, yacht: data }) : [];

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