'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Plus } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { InlineEditableField } from '@/components/shared/inline-editable-field';
import { InlineCountryField } from '@/components/shared/inline-country-field';
import { InlineTimezoneField } from '@/components/shared/inline-timezone-field';
import { InlinePhoneField } from '@/components/shared/inline-phone-field';
import { SubdivisionCombobox } from '@/components/shared/subdivision-combobox';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import type { CountryCode } from '@/lib/i18n/countries';

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

interface ResidentialClientDetail {
  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[];
}

const STATUS_OPTIONS = [
  { value: 'prospect', label: 'Prospect' },
  { value: 'active', label: 'Active' },
  { value: 'inactive', label: 'Inactive' },
];

const CONTACT_OPTIONS = [
  { value: 'email', label: 'Email' },
  { value: 'phone', label: 'Phone' },
];

const SOURCE_OPTIONS = [
  { value: 'website', label: 'Website' },
  { value: 'manual', label: 'Manual' },
  { value: 'referral', label: 'Referral' },
  { value: 'broker', label: 'Broker' },
];

const STAGE_LABELS: Record<string, string> = {
  new: 'New',
  contacted: 'Contacted',
  viewing_scheduled: 'Viewing scheduled',
  offer_made: 'Offer made',
  offer_accepted: 'Offer accepted',
  closed_won: 'Closed — won',
  closed_lost: 'Closed — lost',
};

export function ResidentialClientDetail({ clientId }: { clientId: string }) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const qc = useQueryClient();
  const [newInterestOpen, setNewInterestOpen] = useState(false);

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

  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 save = (field: string) => async (next: string | null) => {
    await update.mutateAsync({ [field]: next });
  };

  if (isLoading || !data) {
    return <div className="text-sm text-muted-foreground">Loading…</div>;
  }
  const client = data.data;

  return (
    <div className="space-y-6">
      <div>
        <Link
          /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
          href={`/${portSlug}/residential/clients` as any}
          className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
        >
          <ArrowLeft className="h-3 w-3" /> All residential clients
        </Link>
      </div>

      <div className="rounded-xl border border-slate-200 bg-gradient-brand-soft px-5 py-4 shadow-xs">
        <div className="text-xs font-semibold uppercase tracking-wide text-brand">
          Residential Client
        </div>
        <h1 className="mt-1 truncate text-2xl font-bold tracking-tight text-foreground">
          <InlineEditableField value={client.fullName} onSave={save('fullName')} />
        </h1>
      </div>

      <div className="rounded-lg border bg-card p-6 space-y-6">
        <div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-6">
          <div className="space-y-1">
            <h3 className="text-sm font-medium mb-2">Contact</h3>
            <Row label="Email">
              <InlineEditableField value={client.email} onSave={save('email')} />
            </Row>
            <Row label="Phone">
              <InlinePhoneField
                e164={client.phoneE164}
                country={client.phoneCountry}
                onSave={async ({ e164, country }) => {
                  await update.mutateAsync({
                    phone: e164,
                    phoneE164: e164,
                    phoneCountry: country,
                  });
                }}
              />
            </Row>
            <Row label="Preferred contact">
              <InlineEditableField
                variant="select"
                options={CONTACT_OPTIONS}
                value={client.preferredContactMethod}
                onSave={save('preferredContactMethod')}
              />
            </Row>
            <Row label="Nationality">
              <InlineCountryField
                value={client.nationalityIso}
                onSave={async (iso) => {
                  await update.mutateAsync({ nationalityIso: iso });
                }}
              />
            </Row>
            <Row label="Timezone">
              <InlineTimezoneField
                value={client.timezone}
                countryHint={(client.nationalityIso as CountryCode | null) ?? null}
                onSave={async (tz) => {
                  await update.mutateAsync({ timezone: tz });
                }}
              />
            </Row>
            <Row label="Place of residence">
              <InlineEditableField
                value={client.placeOfResidence}
                onSave={save('placeOfResidence')}
              />
            </Row>
            <Row label="Country of residence">
              <InlineCountryField
                value={client.placeOfResidenceCountryIso}
                onSave={async (iso) => {
                  // When country flips, clear the subdivision — codes are country-scoped.
                  await update.mutateAsync({
                    placeOfResidenceCountryIso: iso,
                    subdivisionIso: null,
                  });
                }}
              />
            </Row>
            <Row label="Region">
              <SubdivisionCombobox
                value={client.subdivisionIso}
                onChange={(code) => {
                  void update.mutateAsync({ subdivisionIso: code });
                }}
                country={(client.placeOfResidenceCountryIso as CountryCode | null) ?? null}
              />
            </Row>
          </div>

          <div className="space-y-1">
            <h3 className="text-sm font-medium mb-2">Status</h3>
            <Row label="Status">
              <InlineEditableField
                variant="select"
                options={STATUS_OPTIONS}
                value={client.status}
                onSave={save('status')}
              />
            </Row>
            <Row label="Source">
              <InlineEditableField
                variant="select"
                options={SOURCE_OPTIONS}
                value={client.source}
                onSave={save('source')}
              />
            </Row>
            <Row label="Notes">
              <InlineEditableField value={client.notes} onSave={save('notes')} />
            </Row>
          </div>
        </div>
      </div>

      <div className="rounded-lg border bg-card p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold">Interests</h2>
          <Button size="sm" onClick={() => setNewInterestOpen(true)}>
            <Plus className="h-3.5 w-3.5 mr-1.5" />
            New interest
          </Button>
        </div>
        {client.interests.length === 0 ? (
          <p className="text-sm text-muted-foreground">No interests yet.</p>
        ) : (
          <ul className="space-y-2">
            {client.interests.map((i) => (
              <li key={i.id} className="flex items-center gap-3 p-3 rounded-md border bg-muted/30">
                <span className="text-xs font-medium uppercase text-muted-foreground w-32 shrink-0">
                  {STAGE_LABELS[i.pipelineStage] ?? i.pipelineStage}
                </span>
                <span className="flex-1 truncate text-sm">{i.preferences || i.notes || '—'}</span>
                <Link
                  /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
                  href={`/${portSlug}/residential/interests/${i.id}` as any}
                  className="text-xs text-primary hover:underline"
                >
                  View
                </Link>
              </li>
            ))}
          </ul>
        )}
      </div>

      <NewInterestSheet
        clientId={clientId}
        open={newInterestOpen}
        onOpenChange={setNewInterestOpen}
      />
    </div>
  );
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
      <dt className="w-40 shrink-0 text-sm text-muted-foreground">{label}</dt>
      <dd className="flex-1 min-w-0">{children}</dd>
    </div>
  );
}

function NewInterestSheet({
  clientId,
  open,
  onOpenChange,
}: {
  clientId: string;
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const qc = useQueryClient();
  const [preferences, setPreferences] = useState('');
  const [notes, setNotes] = useState('');

  const create = useMutation({
    mutationFn: () =>
      apiFetch('/api/v1/residential/interests', {
        method: 'POST',
        body: {
          residentialClientId: clientId,
          preferences: preferences || undefined,
          notes: notes || undefined,
          source: 'manual',
        },
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['residential-client', clientId] });
      onOpenChange(false);
      setPreferences('');
      setNotes('');
      toast.success('Interest added');
    },
    onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to add'),
  });

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>New interest</SheetTitle>
        </SheetHeader>
        <form
          className="mt-6 space-y-4"
          onSubmit={(e) => {
            e.preventDefault();
            create.mutate();
          }}
        >
          <div className="space-y-1.5">
            <Label htmlFor="ri-prefs">Preferences</Label>
            <Input
              id="ri-prefs"
              value={preferences}
              onChange={(e) => setPreferences(e.target.value)}
              placeholder="Unit type, size, budget…"
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="ri-notes">Notes</Label>
            <Input id="ri-notes" value={notes} onChange={(e) => setNotes(e.target.value)} />
          </div>
          <SheetFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={create.isPending}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={create.isPending}>
              {create.isPending ? 'Saving…' : 'Create'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
