'use client';

import { Archive, Building2, Eye, Hash, MapPin, MoreHorizontal, Pencil } from 'lucide-react';
import Link from 'next/link';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';
import { getCountryName } from '@/lib/i18n/countries';
import type { CompanyRow } from './company-columns';

const STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-100 text-green-800 border-green-300',
  dissolved: 'bg-red-100 text-red-800 border-red-300',
};

const STATUS_LABELS: Record<string, string> = {
  active: 'Active',
  dissolved: 'Dissolved',
};

interface CompanyCardProps {
  company: CompanyRow;
  portSlug: string;
  onEdit: (company: CompanyRow) => void;
  onArchive: (company: CompanyRow) => void;
}

export function CompanyCard({ company, portSlug, onEdit, onArchive }: CompanyCardProps) {
  const statusLabel = STATUS_LABELS[company.status] ?? company.status;
  const statusColor =
    STATUS_COLORS[company.status] ?? 'bg-muted text-muted-foreground border-muted';

  const country = company.incorporationCountryIso
    ? getCountryName(company.incorporationCountryIso, 'en')
    : null;

  const memberCount = company.memberCount ?? 0;
  const yachtCount = company.yachtCount ?? 0;
  const countParts: string[] = [];
  if (memberCount > 0)
    countParts.push(`${memberCount} ${memberCount === 1 ? 'member' : 'members'}`);
  if (yachtCount > 0) countParts.push(`${yachtCount} ${yachtCount === 1 ? 'yacht' : 'yachts'}`);

  // Skip legalName if it is identical to name or absent
  const showLegalName =
    company.legalName && company.legalName.toLowerCase() !== company.name.toLowerCase();

  return (
    <ListCard
      href={`/${portSlug}/companies/${company.id}`}
      ariaLabel={`Company ${company.name}`}
      actions={
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9"
              onClick={(e) => e.stopPropagation()}
              aria-label={`Actions for ${company.name}`}
            >
              <MoreHorizontal className="h-4 w-4" aria-hidden />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem asChild>
              <Link href={`/${portSlug}/companies/${company.id}`}>
                <Eye className="mr-2 h-3.5 w-3.5" aria-hidden />
                View
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => onEdit(company)}>
              <Pencil className="mr-2 h-3.5 w-3.5" aria-hidden />
              Edit
            </DropdownMenuItem>
            <DropdownMenuItem className="text-destructive" onClick={() => onArchive(company)}>
              <Archive className="mr-2 h-3.5 w-3.5" aria-hidden />
              Archive
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      }
    >
      <div className="flex items-start gap-3">
        <ListCardAvatar icon={<Building2 className="h-5 w-5" aria-hidden />} />
        <div className="min-w-0 flex-1">
          {/* Title row + spacer for actions button */}
          <div className="flex items-start justify-between gap-2">
            <h3 className="truncate text-base font-semibold tracking-tight text-foreground">
              {company.name}
            </h3>
            <span aria-hidden className="block h-9 w-9 shrink-0" />
          </div>

          {/* Legal name subtitle */}
          {showLegalName ? (
            <p className="mt-0.5 truncate text-sm text-muted-foreground">{company.legalName}</p>
          ) : null}

          {/* Country + Tax ID meta line */}
          {country || company.taxId ? (
            <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
              {country ? (
                <ListCardMeta icon={<MapPin className="h-3 w-3" aria-hidden />}>
                  {country}
                </ListCardMeta>
              ) : null}
              {company.taxId ? (
                <ListCardMeta icon={<Hash className="h-3 w-3" aria-hidden />}>
                  {company.taxId}
                </ListCardMeta>
              ) : null}
            </div>
          ) : null}

          {/* Member / yacht counts */}
          {countParts.length > 0 ? (
            <p className="mt-0.5 text-xs text-muted-foreground">{countParts.join(' · ')}</p>
          ) : null}

          {/* Status pill */}
          {company.status ? (
            <div className="mt-1.5">
              <span
                className={cn(
                  'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
                  statusColor,
                )}
              >
                {statusLabel}
              </span>
            </div>
          ) : null}
        </div>
      </div>
    </ListCard>
  );
}
