'use client';

import { useParams, useRouter } from 'next/navigation';
import type { Route } from 'next';
import { useState } from 'react';
import { Archive, Bell, RotateCcw, Trash2 } from 'lucide-react';
import { format } from 'date-fns';

import { Badge } from '@/components/ui/badge';
import { TagBadge } from '@/components/shared/tag-badge';
import { PermissionGate } from '@/components/shared/permission-gate';
import { SmartArchiveDialog } from '@/components/clients/smart-archive-dialog';
import { SmartRestoreDialog } from '@/components/clients/smart-restore-dialog';
import { HardDeleteDialog } from '@/components/clients/hard-delete-dialog';
import { ReminderForm } from '@/components/reminders/reminder-form';
import { useQueryClient } from '@tanstack/react-query';
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
import { CountryFlag } from '@/components/shared/country-flag';
import { PortalInviteButton } from '@/components/clients/portal-invite-button';
import { GdprExportButton } from '@/components/clients/gdpr-export-button';
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 router = useRouter();
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const [archiveOpen, setArchiveOpen] = useState(false);
  const [hardDeleteOpen, setHardDeleteOpen] = useState(false);
  const [reminderOpen, setReminderOpen] = useState(false);
  const qc = useQueryClient();

  const isArchived = !!client.archivedAt;

  const primaryEmail =
    client.contacts?.find((c) => c.channel === 'email' && c.isPrimary)?.value ??
    client.contacts?.find((c) => c.channel === 'email')?.value;

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

  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>

            {country || addedLabel ? (
              <p className="flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground sm:text-sm">
                {country ? (
                  <span className="inline-flex items-center gap-1.5">
                    <CountryFlag
                      code={client.nationalityIso}
                      className="h-3 w-4 sm:h-3.5 sm:w-5"
                      decorative
                    />
                    <span>{country}</span>
                  </span>
                ) : null}
                {country && addedLabel ? <span aria-hidden>·</span> : null}
                {addedLabel ? <span>{addedLabel}</span> : null}
              </p>
            ) : null}

            {/* CM-4: Email/Call/WhatsApp deep-link pills removed at client
                request. GDPR export moved to the top-right action cluster.
                Portal-invite stays as the one primary CTA here. */}
            {!isArchived && client.clientPortalEnabled === true ? (
              <div className="flex flex-wrap items-center gap-1.5 pt-1">
                <div className="hidden sm:inline-flex">
                  <PortalInviteButton
                    clientId={client.id}
                    clientName={client.fullName}
                    defaultEmail={primaryEmail}
                  />
                </div>
              </div>
            ) : null}

            {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 + (for archived clients with the
              right perm) permanently-delete. Destructive actions sit out
              of the primary action flow. */}
          <div className="flex items-start gap-1">
            {/* CM-4: GDPR export relocated here as a compact icon trigger,
                alongside reminder/archive/delete. Self-gates on permission. */}
            <GdprExportButton clientId={client.id} variant="icon" />
            {isArchived && (
              <PermissionGate resource="admin" action="permanently_delete_clients">
                <button
                  type="button"
                  onClick={() => setHardDeleteOpen(true)}
                  aria-label="Permanently delete client"
                  title="Permanently delete client"
                  className="shrink-0 rounded-md p-1.5 text-muted-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive"
                >
                  <Trash2 className="size-4" aria-hidden />
                </button>
              </PermissionGate>
            )}
            <button
              type="button"
              onClick={() => setReminderOpen(true)}
              aria-label="Add reminder for this client"
              title="Add reminder for this client"
              className="shrink-0 rounded-md p-1.5 text-muted-foreground/70 transition-colors hover:bg-foreground/5 hover:text-primary"
            >
              <Bell className="size-4" aria-hidden />
            </button>
            {/* Archive + Restore are reversible -> gate on clients:edit, the
                same action the archive routes now require. Hidden for view-only
                users so they never click a button that 403s. */}
            <PermissionGate resource="clients" action="edit">
              <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',
                  isArchived ? 'hover:text-emerald-600' : 'hover:text-destructive',
                )}
              >
                {isArchived ? (
                  <RotateCcw className="size-4" aria-hidden />
                ) : (
                  <Archive className="size-4" aria-hidden />
                )}
              </button>
            </PermissionGate>
          </div>
        </div>
      </DetailHeaderStrip>

      <ReminderForm
        open={reminderOpen}
        onOpenChange={setReminderOpen}
        defaultClientId={client.id}
        onSuccess={() => qc.invalidateQueries({ queryKey: ['reminders'] })}
      />

      {isArchived ? (
        <SmartRestoreDialog
          open={archiveOpen}
          onOpenChange={setArchiveOpen}
          clientId={client.id}
          clientName={client.fullName}
        />
      ) : (
        <SmartArchiveDialog
          open={archiveOpen}
          onOpenChange={setArchiveOpen}
          clientId={client.id}
          clientName={client.fullName}
        />
      )}

      {isArchived && (
        <HardDeleteDialog
          open={hardDeleteOpen}
          onOpenChange={setHardDeleteOpen}
          clientId={client.id}
          clientName={client.fullName}
          onDeleted={() => router.push(`/${portSlug}/clients` as Route)}
        />
      )}
    </>
  );
}
