'use client';

import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Archive, Mail, MessageCircle, Phone, RotateCcw } from 'lucide-react';
import { format } from 'date-fns';

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TagBadge } from '@/components/shared/tag-badge';
import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog';
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
import { PortalInviteButton } from '@/components/clients/portal-invite-button';
import { GdprExportButton } from '@/components/clients/gdpr-export-button';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
import { getCountryName } from '@/lib/i18n/countries';

interface ClientDetailHeaderProps {
  client: {
    id: string;
    fullName: string;
    nationalityIso?: string | null;
    archivedAt?: string | null;
    createdAt?: string;
    contacts?: Array<{
      channel: string;
      value: string;
      valueE164?: string | null;
      isPrimary: boolean;
      label?: string | null;
    }>;
    tags?: Array<{ id: string; name: string; color: string }>;
    clientPortalEnabled?: boolean;
  };
}

export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
  const queryClient = useQueryClient();
  const [archiveOpen, setArchiveOpen] = useState(false);

  const isArchived = !!client.archivedAt;

  const archiveMutation = useMutation({
    mutationFn: () => apiFetch(`/api/v1/clients/${client.id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clients', client.id] });
      queryClient.invalidateQueries({ queryKey: ['clients'] });
      setArchiveOpen(false);
    },
  });

  const restoreMutation = useMutation({
    mutationFn: () => apiFetch(`/api/v1/clients/${client.id}/restore`, { method: 'POST' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clients', client.id] });
      queryClient.invalidateQueries({ queryKey: ['clients'] });
      setArchiveOpen(false);
    },
  });

  const primaryEmail =
    client.contacts?.find((c) => c.channel === 'email' && c.isPrimary)?.value ??
    client.contacts?.find((c) => c.channel === 'email')?.value;
  const primaryPhoneContact =
    client.contacts?.find((c) => c.channel === 'phone' && c.isPrimary) ??
    client.contacts?.find((c) => c.channel === 'phone');
  const primaryPhone = primaryPhoneContact?.value;
  // wa.me requires the E.164 number without the leading "+". Strip from the
  // canonical E.164 form when available; otherwise strip non-digits from the
  // display value as a best-effort fallback.
  const whatsappNumber = primaryPhoneContact?.valueE164
    ? primaryPhoneContact.valueE164.replace(/^\+/, '')
    : primaryPhoneContact?.value
      ? primaryPhoneContact.value.replace(/[^\d]/g, '')
      : null;

  const country = client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null;
  const addedLabel = client.createdAt
    ? `Added ${format(new Date(client.createdAt), 'MMM d, yyyy')}`
    : null;
  const meta = [country, addedLabel].filter(Boolean) as string[];

  return (
    <>
      <DetailHeaderStrip>
        <div className="flex items-start gap-3">
          <div className="min-w-0 flex-1 space-y-2">
            <div className="flex items-center gap-2 flex-wrap">
              <h1 className="truncate text-lg font-bold text-foreground sm:text-2xl">
                {client.fullName}
              </h1>
              {isArchived && (
                <Badge variant="secondary" className="text-xs">
                  Archived
                </Badge>
              )}
            </div>

            {meta.length > 0 ? (
              <p className="text-xs text-muted-foreground sm:text-sm">{meta.join(' · ')}</p>
            ) : null}

            <div className="flex flex-wrap items-center gap-1.5 pt-1">
              {primaryEmail ? (
                <Button
                  asChild
                  variant="outline"
                  size="sm"
                  className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
                >
                  <a href={`mailto:${primaryEmail}`} aria-label={`Email ${primaryEmail}`}>
                    <Mail />
                    Email
                  </a>
                </Button>
              ) : null}
              {primaryPhone ? (
                <Button
                  asChild
                  variant="outline"
                  size="sm"
                  className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
                >
                  <a href={`tel:${primaryPhone}`} aria-label={`Call ${primaryPhone}`}>
                    <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 ${primaryPhone} on WhatsApp`}
                  >
                    <MessageCircle />
                    WhatsApp
                  </a>
                </Button>
              ) : null}
              {!isArchived && client.clientPortalEnabled !== false ? (
                <div className="hidden sm:inline-flex">
                  <PortalInviteButton
                    clientId={client.id}
                    clientName={client.fullName}
                    defaultEmail={primaryEmail}
                  />
                </div>
              ) : null}
              <div className="hidden sm:inline-flex">
                <GdprExportButton clientId={client.id} />
              </div>
            </div>

            {client.tags && client.tags.length > 0 && (
              <div className="flex flex-wrap gap-1">
                {client.tags.map((tag) => (
                  <TagBadge key={tag.id} name={tag.name} color={tag.color} />
                ))}
              </div>
            )}
          </div>

          {/* Top-right: archive/restore as a small icon button - destructive
              action sits out of the primary action flow. */}
          <button
            type="button"
            onClick={() => setArchiveOpen(true)}
            aria-label={isArchived ? 'Restore client' : 'Archive client'}
            title={isArchived ? 'Restore client' : 'Archive client'}
            className={cn(
              'shrink-0 rounded-md p-1.5 text-muted-foreground/70 transition-colors',
              'hover:bg-foreground/5 hover:text-foreground',
              isArchived ? 'hover:text-foreground' : 'hover:text-destructive',
            )}
          >
            {isArchived ? <RotateCcw className="size-4" /> : <Archive className="size-4" />}
          </button>
        </div>
      </DetailHeaderStrip>

      <ArchiveConfirmDialog
        open={archiveOpen}
        onOpenChange={setArchiveOpen}
        entityName={client.fullName}
        entityType="Client"
        isArchived={isArchived}
        onConfirm={() => {
          if (isArchived) {
            restoreMutation.mutate();
          } else {
            archiveMutation.mutate();
          }
        }}
        isLoading={archiveMutation.isPending || restoreMutation.isPending}
      />
    </>
  );
}
