'use client';

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

import { DetailLayout, type DetailTab } from '@/components/shared/detail-layout';
import { DetailNotFound } from '@/components/shared/detail-not-found';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';
import { usePermissions } from '@/hooks/use-permissions';
import {
  KIND_LABELS,
  TRIAGE_LABELS,
  TRIAGE_TONE,
  type InquiryKind,
  type InquiryTriageState,
} from '@/components/inquiries/inquiry-columns';
import { InquiryConvertActions } from '@/components/inquiries/inquiry-convert-actions';

interface InquiryDetailData {
  id: string;
  kind: InquiryKind;
  contactName: string | null;
  contactEmail: string | null;
  payload: Record<string, unknown> | null;
  receivedAt: string;
  sourceIp: string | null;
  utmSource: string | null;
  utmMedium: string | null;
  utmCampaign: string | null;
  triageState: InquiryTriageState;
  triagedAt: string | null;
  convertedClientId: string | null;
  convertedInterestId: string | null;
  convertedClient: { id: string; fullName: string } | null;
  convertedInterest: { id: string; pipelineStage: string } | null;
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="grid grid-cols-[140px_1fr] gap-2 py-1.5 text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className="min-w-0 break-words">
        {value || <span className="text-muted-foreground">—</span>}
      </span>
    </div>
  );
}

export function InquiryDetail({ id }: { id: string }) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const { isSuperAdmin } = usePermissions();

  const { data, isLoading, error } = useQuery<InquiryDetailData>({
    queryKey: ['inquiries', id],
    queryFn: () =>
      apiFetch<{ data: InquiryDetailData }>(`/api/v1/inquiries/${id}`).then((r) => r.data),
    retry: (count, err) => {
      const status = (err as { status?: number })?.status;
      return status === 404 || status === 403 ? false : count < 2;
    },
  });

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

  const p = (data?.payload ?? {}) as Record<string, unknown>;
  const str = (k: string) => (typeof p[k] === 'string' ? (p[k] as string) : '');
  // Read a payload value that may be a string[] (e.g. residence_types, the
  // contact form's interest[]) OR a lone string, and present it comma-joined.
  const list = (k: string): string => {
    const v = p[k];
    if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string').join(', ');
    return typeof v === 'string' ? v : '';
  };
  // The free-text message a lead left. Website forms use different keys
  // (contact form -> `comments`; others -> `message`/`comment`), so probe the
  // common ones and surface it for every inquiry kind.
  const comment = str('comments') || str('message') || str('comment') || str('notes');
  // Preferred method of contact (register form: 'email' | 'phone'). Surfaced so
  // reps honour the lead's stated contact request.
  const preferredContactRaw = str('method_of_contact').toLowerCase();
  const preferredContact =
    preferredContactRaw === 'email'
      ? 'Email'
      : preferredContactRaw === 'phone'
        ? 'Phone call back'
        : '';
  const residenceTypes = list('residence_types');
  // Contact-form "type of interest" (owner/broker/investor/…), stored as an array.
  const contactInterest = list('interest');

  const tabs: DetailTab[] = [
    {
      id: 'overview',
      label: 'Overview',
      content: (
        <div className="max-w-xl">
          <Row label="Name" value={data?.contactName} />
          <Row label="Email" value={data?.contactEmail} />
          <Row label="Phone" value={str('phone')} />
          {data?.kind === 'residence_inquiry' ? (
            <Row label="Residence type(s)" value={residenceTypes} />
          ) : null}
          {data?.kind === 'residence_inquiry' ? (
            <Row label="Place of residence" value={str('address')} />
          ) : null}
          {data?.kind === 'berth_inquiry' ? <Row label="Berth" value={str('berth')} /> : null}
          {data?.kind === 'contact_form' && contactInterest ? (
            <Row label="Type of interest" value={contactInterest} />
          ) : null}
          {preferredContact ? <Row label="Preferred contact" value={preferredContact} /> : null}
          {comment ? (
            <Row label="Message" value={<span className="whitespace-pre-wrap">{comment}</span>} />
          ) : null}
          <Row label="Type" value={data ? KIND_LABELS[data.kind] : ''} />
          <Row label="Received" value={data ? format(new Date(data.receivedAt), 'PPpp') : ''} />
          <Row label="Source IP" value={data?.sourceIp} />
          <Row label="UTM source" value={data?.utmSource} />
          <Row label="UTM medium" value={data?.utmMedium} />
          <Row label="UTM campaign" value={data?.utmCampaign} />
        </div>
      ),
    },
    {
      id: 'tracking',
      label: 'Tracking',
      content: (
        <div className="max-w-xl">
          <Row
            label="Status"
            value={
              data ? (
                <Badge className={TRIAGE_TONE[data.triageState]}>
                  {TRIAGE_LABELS[data.triageState]}
                </Badge>
              ) : (
                ''
              )
            }
          />
          <Row
            label="Triaged at"
            value={data?.triagedAt ? format(new Date(data.triagedAt), 'PPpp') : ''}
          />
          <Row
            label="Converted client"
            value={
              data?.convertedClient ? (
                <a
                  href={`/${portSlug}/clients/${data.convertedClient.id}`}
                  className="text-primary hover:underline"
                >
                  {data.convertedClient.fullName}
                </a>
              ) : null
            }
          />
          <Row
            label="Converted interest"
            value={
              data?.convertedInterest ? (
                <a
                  href={`/${portSlug}/interests/${data.convertedInterest.id}`}
                  className="text-primary hover:underline"
                >
                  View interest ({data.convertedInterest.pipelineStage})
                </a>
              ) : null
            }
          />
        </div>
      ),
    },
    {
      id: 'payload',
      label: 'Raw payload',
      content: (
        <pre className="max-h-96 overflow-auto rounded-md bg-muted/40 p-3 text-xs">
          {JSON.stringify(data?.payload ?? {}, null, 2)}
        </pre>
      ),
    },
  ].filter((tab) => tab.id !== 'payload' || isSuperAdmin);

  return (
    <DetailLayout
      isLoading={isLoading}
      header={
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-xl font-semibold">{data?.contactName || '(no name)'}</h1>
              {data ? (
                <Badge className={TRIAGE_TONE[data.triageState]}>
                  {TRIAGE_LABELS[data.triageState]}
                </Badge>
              ) : null}
            </div>
            <p className="mt-1 text-sm text-muted-foreground">
              {data ? KIND_LABELS[data.kind] : ''} inquiry
              {data?.contactEmail ? ` · ${data.contactEmail}` : ''}
            </p>
          </div>
          {data ? <InquiryConvertActions portSlug={portSlug} inquiry={data} /> : null}
        </div>
      }
      tabs={tabs}
      defaultTab="overview"
    />
  );
}
