'use client';

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

import { DetailLayout } from '@/components/shared/detail-layout';
import { useMobileChrome } from '@/components/layout/mobile/mobile-layout-provider';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
import { apiFetch } from '@/lib/api/client';
import { ResidentialClientDetailHeader } from '@/components/residential/residential-client-detail-header';
import { getResidentialClientTabs } from '@/components/residential/residential-client-tabs';

interface ResidentialInterestSummary {
  id: string;
  pipelineStage: string;
  source: string | null;
  notes: string | null;
  preferences: string | null;
  updatedAt: string;
}

interface ResidentialClient {
  id: string;
  fullName: string;
  email: string | null;
  phone: string | null;
  phoneE164: string | null;
  phoneCountry: string | null;
  nationalityIso: string | null;
  timezone: string | null;
  placeOfResidence: string | null;
  placeOfResidenceCountryIso: string | null;
  subdivisionIso: string | null;
  preferredContactMethod: string | null;
  status: string;
  source: string | null;
  notes: string | null;
  interests: ResidentialInterestSummary[];
}

interface Stage {
  id: string;
  label: string;
}

export function ResidentialClientDetail({
  clientId,
  currentUserId,
}: {
  clientId: string;
  currentUserId?: string;
}) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const qc = useQueryClient();

  const { data, isLoading } = useQuery<{ data: ResidentialClient }>({
    queryKey: ['residential-client', clientId],
    queryFn: () => apiFetch(`/api/v1/residential/clients/${clientId}`),
  });

  const { data: stagesData } = useQuery<{ data: { stages: Stage[] } }>({
    queryKey: ['residential-stages', portSlug],
    queryFn: () => apiFetch('/api/v1/residential/stages'),
  });

  useRealtimeInvalidation({
    'residential_client:updated': [['residential-client', clientId]],
    'residential_interest:created': [['residential-client', clientId]],
    'residential_interest:updated': [['residential-client', clientId]],
    'residential_interest:archived': [['residential-client', clientId]],
  });

  const update = useMutation({
    mutationFn: (patch: Record<string, unknown>) =>
      apiFetch(`/api/v1/residential/clients/${clientId}`, { method: 'PATCH', body: patch }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['residential-client', clientId] }),
  });

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

  // Topbar breadcrumb hint - Residential › Clients › <name>
  useBreadcrumbHint(data ? { parents: [], current: data.data.fullName } : null);

  const stageLabels = useMemo(() => {
    const map: Record<string, string> = {};
    for (const s of stagesData?.data.stages ?? []) map[s.id] = s.label;
    return map;
  }, [stagesData]);

  const tabs = data
    ? getResidentialClientTabs({
        clientId,
        client: data.data,
        portSlug,
        currentUserId,
        stageLabels,
      })
    : [];

  return (
    <DetailLayout
      header={
        data ? (
          <ResidentialClientDetailHeader
            client={data.data}
            onSaveName={async (next) => {
              await update.mutateAsync({ fullName: next });
            }}
          />
        ) : null
      }
      tabs={tabs}
      defaultTab="overview"
      isLoading={isLoading}
    />
  );
}
