'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { DetailNotFound } from '@/components/shared/detail-not-found';
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 { useTenanciesModuleEnabled } from '@/providers/port-provider';
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;
  /** Phase 3c - origin tracking. Surfaces the [EOI] badge in the header. */
  source?: string | null;
  sourceDocumentId?: string | null;
}

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

export function YachtDetail({ yachtId, currentUserId }: YachtDetailProps) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading, error } = useQuery<YachtData>({
    queryKey: ['yachts', yachtId],
    queryFn: () => apiFetch<{ data: YachtData }>(`/api/v1/yachts/${yachtId}`).then((r) => r.data),
    retry: (failureCount, err) => {
      const status = (err as { status?: number } | null | undefined)?.status;
      if (status === 404 || status === 403) return false;
      return failureCount < 2;
    },
  });

  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 tenanciesModuleEnabled = useTenanciesModuleEnabled();

  if (error && !isLoading) {
    const status = (error as { status?: number } | null | undefined)?.status;
    return (
      <DetailNotFound
        entity="yacht"
        backHref={`/${portSlug}/yachts`}
        backLabel="Back to yachts"
        status={status}
      />
    );
  }

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

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