'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;
}

export function ClientCard({ client, portSlug, onEdit, onArchive }: 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;
  const interestBerthLabel = interest
    ? interest.mooringNumber
      ? `Berth ${interest.mooringNumber}`
      : '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>
            <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-[10px] 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>
  );
}
