'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { InterestDetailHeader } from '@/components/interests/interest-detail-header';
import { getInterestTabs } from '@/components/interests/interest-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

interface InterestData {
  id: string;
  portId: string;
  clientId: string;
  clientName: string | null;
  berthId: string | null;
  berthMooringNumber: string | null;
  pipelineStage: string;
  leadCategory: string | null;
  source: string | null;
  eoiStatus: string | null;
  contractStatus: string | null;
  depositStatus: string | null;
  reservationStatus: string | null;
  dateFirstContact: string | null;
  dateLastContact: string | null;
  dateEoiSent: string | null;
  dateEoiSigned: string | null;
  dateContractSent: string | null;
  dateContractSigned: string | null;
  dateDepositReceived: string | null;
  reminderEnabled: boolean;
  reminderDays: number | null;
  reminderLastFired: string | null;
  notes: string | null;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
  tags: Array<{ id: string; name: string; color: string }>;
}

interface InterestDetailProps {
  interestId: string;
  currentUserId?: string;
}

export function InterestDetail({ interestId, currentUserId }: InterestDetailProps) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

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

  useRealtimeInvalidation({
    'interest:updated': [['interests', interestId]],
    'interest:stageChanged': [['interests', interestId]],
    'interest:archived': [['interests', interestId]],
    'interest:berthLinked': [['interests', interestId]],
    'interest:berthUnlinked': [['interests', interestId]],
  });

  const tabs = data
    ? getInterestTabs({ interestId, currentUserId, interest: data })
    : [];

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