'use client';

import type { ReactNode } from 'react';
import { Archive, MoreHorizontal, Pencil } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { CountryFlag } from '@/components/shared/country-flag';
import { TagBadge } from '@/components/shared/tag-badge';
import {
  ListCard,
  ListCardAvatar,
  ListCardMeta,
  deriveInitials,
} from '@/components/shared/list-card';
import { getCountryName } from '@/lib/i18n/countries';
import { stageBadgeClass, stageLabel, formatSource } from '@/lib/constants';
import type { ClientRow } from './client-columns';

interface ClientCardProps {
  client: ClientRow;
  portSlug: string;
  onEdit: (client: ClientRow) => void;
  onArchive: (client: ClientRow) => void;
  /** Hide the Archive action for users who can't archive (clients:edit). */
  canArchive?: boolean;
}

export function ClientCard({
  client,
  portSlug,
  onEdit,
  onArchive,
  canArchive = true,
}: ClientCardProps) {
  // Card display: prefer email, fall back to phone.
  const primaryContactValue = client.primaryEmail ?? client.primaryPhone ?? null;
  const nationality = client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null;
  const sourceLabel = formatSource(client.source);
  const tags = client.tags ?? [];

  const metaItems: { key: string; node: ReactNode }[] = [];
  if (nationality) {
    metaItems.push({
      key: 'nationality',
      node: (
        <span className="inline-flex items-center gap-1">
          <CountryFlag code={client.nationalityIso} className="h-2.5 w-3.5" decorative />
          <ListCardMeta>{nationality}</ListCardMeta>
        </span>
      ),
    });
  }
  if (sourceLabel) {
    metaItems.push({ key: 'source', node: <ListCardMeta>{sourceLabel}</ListCardMeta> });
  }

  const interest = client.latestInterest ?? null;
  const interestCount = client.interestCount ?? 0;
  // Show ALL berths the client has interests in (across every interest),
  // not just the latest interest's primary mooring — matches the desktop
  // table's Berths column + the interest header. Cap the inline list so
  // the card stays compact; overflow folds into a "+N" suffix.
  const linkedBerths = client.linkedBerths ?? [];
  const MAX_BERTHS_SHOWN = 4;
  const shownMoorings = linkedBerths.slice(0, MAX_BERTHS_SHOWN).map((b) => b.mooringNumber);
  const extraBerths = linkedBerths.length - shownMoorings.length;
  const interestBerthLabel =
    shownMoorings.length > 0
      ? `${linkedBerths.length === 1 ? 'Berth' : 'Berths'} ${shownMoorings.join(', ')}${
          extraBerths > 0 ? ` +${extraBerths}` : ''
        }`
      : interest
        ? 'General interest'
        : null;
  const interestStageLabel = interest ? stageLabel(interest.stage) : null;
  const interestStageBadge = interest ? stageBadgeClass(interest.stage) : null;
  const extraInterests = interestCount > 1 ? interestCount - 1 : 0;

  return (
    <ListCard
      href={`/${portSlug}/clients/${client.id}`}
      ariaLabel={`Client ${client.fullName}`}
      actions={
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9"
              onClick={(e) => e.stopPropagation()}
              aria-label={`Actions for ${client.fullName}`}
            >
              <MoreHorizontal className="h-4 w-4" aria-hidden />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => onEdit(client)}>
              <Pencil className="mr-2 h-3.5 w-3.5" aria-hidden />
              Edit
            </DropdownMenuItem>
            {canArchive && (
              <DropdownMenuItem className="text-destructive" onClick={() => onArchive(client)}>
                <Archive className="mr-2 h-3.5 w-3.5" aria-hidden />
                Archive
              </DropdownMenuItem>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      }
    >
      <div className="flex items-start gap-3">
        <ListCardAvatar initials={deriveInitials(client.fullName)} />
        <div className="min-w-0 flex-1">
          <div className="flex items-start justify-between gap-2">
            <h3 className="truncate text-base font-semibold tracking-tight text-foreground">
              {client.fullName}
            </h3>
            <span aria-hidden className="block h-9 w-9 shrink-0" />
          </div>

          {primaryContactValue ? (
            <p className="truncate text-sm text-muted-foreground">{primaryContactValue}</p>
          ) : null}

          {metaItems.length > 0 ? (
            <div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground">
              {metaItems.map((m, i) => (
                <span key={m.key} className="inline-flex items-center gap-1">
                  {i > 0 ? <span aria-hidden>·</span> : null}
                  {m.node}
                </span>
              ))}
            </div>
          ) : null}

          {interest ? (
            <div className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">
              <span className="truncate">{interestBerthLabel}</span>
              <span aria-hidden>·</span>
              <span
                className={`shrink-0 rounded-full px-1.5 py-0.5 text-xs font-medium ${interestStageBadge}`}
              >
                {interestStageLabel}
              </span>
              {extraInterests > 0 ? (
                <span className="shrink-0 text-muted-foreground/80">+{extraInterests}</span>
              ) : null}
            </div>
          ) : null}

          {tags.length > 0 ? (
            <div className="mt-2 flex flex-wrap gap-1">
              {tags.slice(0, 2).map((tag) => (
                <TagBadge key={tag.id} name={tag.name} color={tag.color} />
              ))}
              {tags.length > 2 ? (
                <span className="inline-flex items-center rounded-full bg-secondary px-2 py-0.5 text-xs text-secondary-foreground">
                  +{tags.length - 2}
                </span>
              ) : null}
            </div>
          ) : null}
        </div>
      </div>
    </ListCard>
  );
}
