'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 { CompanyDetailHeader } from '@/components/companies/company-detail-header';
import { getCompanyTabs } from '@/components/companies/company-tabs';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
import { apiFetch } from '@/lib/api/client';
import type { Address } from '@/components/shared/addresses-editor';

export interface CompanyData {
  id: string;
  portId: string;
  name: string;
  legalName: string | null;
  taxId: string | null;
  registrationNumber: string | null;
  incorporationCountryIso: string | null;
  incorporationSubdivisionIso: string | null;
  incorporationDate: string | null;
  status: string;
  billingEmail: string | null;
  notes: string | null;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
  tags?: Array<{ id: string; name: string; color: string }>;
  addresses?: Address[];
}

interface CompanyDetailProps {
  companyId: string;
  currentUserId?: string;
}

export function CompanyDetail({ companyId, currentUserId }: CompanyDetailProps) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading, error } = useQuery<CompanyData>({
    queryKey: ['companies', companyId],
    queryFn: () =>
      apiFetch<{ data: CompanyData }>(`/api/v1/companies/${companyId}`).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({
    'company:updated': [['companies', companyId]],
    'company:archived': [['companies', companyId]],
    'company_membership:added': [['companies', companyId, 'members']],
    'company_membership:updated': [['companies', companyId, 'members']],
    'company_membership:ended': [['companies', companyId, 'members']],
  });

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

  const tabs = data ? getCompanyTabs({ companyId, portSlug, currentUserId, company: data }) : [];

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