'use client';

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

import { Badge } from '@/components/ui/badge';
import { DetailLayout } from '@/components/shared/detail-layout';
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
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 { getResidentialInterestTabs } from '@/components/residential/residential-interest-tabs';

interface ResidentialInterest {
  id: string;
  residentialClientId: string;
  pipelineStage: string;
  source: string | null;
  notes: string | null;
  preferences: string | null;
  residenceType: string | null;
  assignedTo: string | null;
  client: { id: string; fullName: string } | null;
}

interface Stage {
  id: string;
  label: string;
  terminal: 'won' | 'lost' | null;
}

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

  const { data, isLoading } = useQuery<{ data: ResidentialInterest }>({
    queryKey: ['residential-interest', interestId],
    queryFn: () => apiFetch(`/api/v1/residential/interests/${interestId}`),
  });

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

  useRealtimeInvalidation({
    'residential_interest:updated': [['residential-interest', interestId]],
  });

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

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

  // Breadcrumb: Residential › Interests › <client> › <stage>
  useBreadcrumbHint(
    data
      ? {
          parents:
            data.data.client && data.data.residentialClientId
              ? [
                  {
                    label: data.data.client.fullName,
                    href: `/${portSlug}/residential/clients/${data.data.residentialClientId}`,
                  },
                ]
              : [],
          current: 'Interest',
        }
      : null,
  );

  const stageOptions = useMemo(
    () =>
      (stagesData?.data.stages ?? []).map((s) => ({
        value: s.id,
        label: s.label,
      })),
    [stagesData],
  );
  const stageLabel = useMemo(() => {
    const s = stagesData?.data.stages.find((x) => x.id === data?.data.pipelineStage);
    return s?.label ?? data?.data.pipelineStage ?? '';
  }, [stagesData, data]);

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

  return (
    <DetailLayout
      header={
        data ? (
          <DetailHeaderStrip>
            <div className="space-y-1">
              <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Residential interest
              </div>
              <h1 className="truncate text-2xl font-bold tracking-tight text-foreground">
                {data.data.client?.fullName ?? 'Unknown client'}
              </h1>
              <Badge variant="outline">{stageLabel}</Badge>
            </div>
          </DetailHeaderStrip>
        ) : null
      }
      tabs={tabs}
      defaultTab="overview"
      isLoading={isLoading}
    />
  );
}
