'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { useMobileChrome } from '@/components/layout/mobile/mobile-layout-provider';
import { YachtDetailHeader } from '@/components/yachts/yacht-detail-header';
import { getYachtTabs } from '@/components/yachts/yacht-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
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),
  });

  const { setChrome } = useMobileChrome();
  const titleForChrome: string | null = data?.name ?? null;
  useEffect(() => {
    setChrome({ title: titleForChrome, showBackButton: true });
    return () => setChrome({ title: null, showBackButton: false });
  }, [titleForChrome, setChrome]);

  useBreadcrumbHint(data ? { parents: [], current: data.name } : null);

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