'use client';

import Link from 'next/link';
import { useParams } from 'next/navigation';
import { ExternalLink, Home, Mail, Phone } from 'lucide-react';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
import { InlineEditableField } from '@/components/shared/inline-editable-field';
import { WhatsAppIcon } from '@/components/icons/whatsapp';

interface Props {
  client: {
    id: string;
    fullName: string;
    status: string;
    placeOfResidence: string | null;
    /** Optional primary email - surfaces the same Email button the main
     *  ClientDetailHeader renders. Null when the residential client
     *  hasn't shared an email. */
    email?: string | null;
    /** Optional primary phone (free-text fallback). E.164 form preferred
     *  via `phoneE164` so `tel:` links route correctly. */
    phone?: string | null;
    phoneE164?: string | null;
    /** Optional FK to a matching main-client record. Set by the
     *  auto-link matcher on create OR by admin action. When set, the
     *  header shows a chip linking to the other side. */
    linkedClientId?: string | null;
  };
  onSaveName: (next: string | null) => Promise<void>;
}

const STATUS_TONE: Record<string, string> = {
  prospect: 'bg-blue-100 text-blue-900',
  active: 'bg-emerald-100 text-emerald-900',
  inactive: 'bg-muted text-muted-foreground',
};

const STATUS_LABEL: Record<string, string> = {
  prospect: 'Prospect',
  active: 'Active',
  inactive: 'Inactive',
};

export function ResidentialClientDetailHeader({ client, onSaveName }: Props) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  // WhatsApp number must be digits-only with no leading + (wa.me convention).
  // Prefer the E.164 form when available; fall back to the free-text phone
  // stripped down to digits.
  const whatsappNumber = client.phoneE164
    ? client.phoneE164.replace(/^\+/, '')
    : (client.phone ?? '').replace(/\D/g, '') || null;
  const callHref = client.phoneE164 ?? client.phone ?? null;

  return (
    <DetailHeaderStrip>
      <div className="space-y-2">
        <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground inline-flex items-center gap-1.5">
          <Home className="h-3 w-3" aria-hidden /> Residential client
        </div>
        <h1 className="truncate text-lg font-bold tracking-tight text-foreground sm:text-2xl">
          <InlineEditableField value={client.fullName} onSave={onSaveName} />
        </h1>
        <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
          <Badge className={STATUS_TONE[client.status] ?? 'bg-muted'}>
            {STATUS_LABEL[client.status] ?? client.status}
          </Badge>
          {client.placeOfResidence && <span>{client.placeOfResidence}</span>}
          {client.linkedClientId ? (
            <Link
              /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
              href={`/${portSlug}/clients/${client.linkedClientId}` as any}
              className="inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs hover:bg-muted"
              title="This residential client is linked to an existing main-CRM client record."
            >
              Linked to main client
              <ExternalLink className="size-3" aria-hidden />
            </Link>
          ) : null}
        </div>

        {/* Action row - mirrors the buttons on the main ClientDetailHeader so
            residential reps have one-tap email / call / WhatsApp from the
            header without scrolling to the contact section. */}
        {client.email || callHref || whatsappNumber ? (
          <div className="flex flex-wrap items-center gap-1.5 pt-1">
            {client.email ? (
              <Button
                asChild
                variant="outline"
                size="sm"
                className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
              >
                <a href={`mailto:${client.email}`} aria-label={`Email ${client.email}`}>
                  <Mail />
                  Email
                </a>
              </Button>
            ) : null}
            {callHref ? (
              <Button
                asChild
                variant="outline"
                size="sm"
                className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
              >
                <a href={`tel:${callHref}`} aria-label={`Call ${callHref}`}>
                  <Phone />
                  Call
                </a>
              </Button>
            ) : null}
            {whatsappNumber ? (
              <Button
                asChild
                variant="outline"
                size="sm"
                className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
              >
                <a
                  href={`https://wa.me/${whatsappNumber}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={`Message ${client.fullName} on WhatsApp`}
                >
                  <WhatsAppIcon className="h-4 w-4" />
                  WhatsApp
                </a>
              </Button>
            ) : null}
          </div>
        ) : null}
      </div>
    </DetailHeaderStrip>
  );
}
