'use client';

import Link from 'next/link';
import { format, formatDistanceToNowStrict } from 'date-fns';
import { MoreHorizontal, Pencil, Archive, MessageSquare } from 'lucide-react';
import type { ColumnDef } from '@tanstack/react-table';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import { TagBadge } from '@/components/shared/tag-badge';
import { stageBadgeClass, stageLabel } from '@/lib/constants';
import { computeUrgencyBadges, type InterestUrgencyInput } from '@/components/interests/urgency';

export interface InterestRow {
  id: string;
  clientId: string;
  clientName: string | null;
  berthId: string | null;
  berthMooringNumber: string | null;
  pipelineStage: string;
  leadCategory: string | null;
  source: string | null;
  archivedAt: string | null;
  createdAt: string;
  /** Surfaced by listInterests for the row-level sales-triage signals
   *  (last-activity relative time, comment-icon, urgency badges). */
  updatedAt?: string;
  dateLastContact?: string | null;
  dateEoiSent?: string | null;
  dateDepositReceived?: string | null;
  eoiStatus?: string | null;
  outcome?: string | null;
  notesCount?: number;
  tags?: Array<{ id: string; name: string; color: string }>;
}

const CATEGORY_LABELS: Record<string, string> = {
  general_interest: 'General Interest',
  specific_qualified: 'Specific Qualified',
  hot_lead: 'Hot Lead',
};

const SOURCE_LABELS: Record<string, string> = {
  website: 'Website',
  manual: 'Manual',
  referral: 'Referral',
  broker: 'Broker',
};

interface GetColumnsOptions {
  portSlug: string;
  onEdit: (interest: InterestRow) => void;
  onArchive: (interest: InterestRow) => void;
}

export function getInterestColumns({
  portSlug,
  onEdit,
  onArchive,
}: GetColumnsOptions): ColumnDef<InterestRow, unknown>[] {
  return [
    {
      id: 'clientName',
      accessorKey: 'clientName',
      header: 'Client',
      cell: ({ row }) => {
        const notesCount = row.original.notesCount ?? 0;
        return (
          <div className="flex items-center gap-1.5 min-w-0">
            <Link
              href={`/${portSlug}/clients/${row.original.clientId}`}
              className="truncate font-medium text-primary hover:underline"
              onClick={(e) => e.stopPropagation()}
            >
              {row.original.clientName ?? '—'}
            </Link>
            {notesCount > 0 ? (
              <span
                title={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
                aria-label={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
                className="inline-flex items-center text-muted-foreground"
              >
                <MessageSquare className="size-3.5" />
              </span>
            ) : null}
          </div>
        );
      },
    },
    {
      id: 'berthMooringNumber',
      accessorKey: 'berthMooringNumber',
      header: 'Berth',
      cell: ({ row }) => {
        if (!row.original.berthId || !row.original.berthMooringNumber) {
          return <span className="text-muted-foreground">—</span>;
        }
        return (
          <Link
            href={`/${portSlug}/berths/${row.original.berthId}`}
            className="text-primary hover:underline text-sm"
            onClick={(e) => e.stopPropagation()}
          >
            {row.original.berthMooringNumber}
          </Link>
        );
      },
    },
    {
      id: 'pipelineStage',
      accessorKey: 'pipelineStage',
      header: 'Stage',
      cell: ({ row }) => {
        const stage = row.original.pipelineStage;
        const badges = computeUrgencyBadges(row.original satisfies InterestUrgencyInput);
        return (
          <div className="flex flex-col gap-1 items-start">
            <span
              className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${stageBadgeClass(stage)}`}
            >
              {stageLabel(stage)}
            </span>
            {badges.length > 0 ? (
              <div className="flex flex-wrap gap-1">
                {badges.map((b) => (
                  <span
                    key={b.id}
                    title={b.detail}
                    aria-label={b.detail}
                    className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium ${b.className}`}
                  >
                    {b.label}
                  </span>
                ))}
              </div>
            ) : null}
          </div>
        );
      },
    },
    {
      id: 'leadCategory',
      accessorKey: 'leadCategory',
      header: 'Category',
      cell: ({ getValue }) => {
        const cat = getValue() as string | null;
        if (!cat) return <span className="text-muted-foreground">—</span>;
        return (
          <Badge variant="outline" className="text-xs capitalize">
            {CATEGORY_LABELS[cat] ?? cat}
          </Badge>
        );
      },
    },
    {
      id: 'source',
      accessorKey: 'source',
      header: 'Source',
      cell: ({ getValue }) => {
        const source = getValue() as string | null;
        if (!source) return <span className="text-muted-foreground">—</span>;
        return (
          <Badge variant="outline" className="text-xs">
            {SOURCE_LABELS[source] ?? source}
          </Badge>
        );
      },
    },
    {
      id: 'tags',
      header: 'Tags',
      enableSorting: false,
      cell: ({ row }) => {
        const rowTags = row.original.tags ?? [];
        if (rowTags.length === 0) return <span className="text-muted-foreground">—</span>;
        return (
          <div className="flex flex-wrap gap-1">
            {rowTags.slice(0, 3).map((tag) => (
              <TagBadge key={tag.id} name={tag.name} color={tag.color} />
            ))}
            {rowTags.length > 3 && (
              <Badge variant="secondary" className="text-xs">
                +{rowTags.length - 3}
              </Badge>
            )}
          </div>
        );
      },
    },
    {
      // Sales-triage default: prefer the explicit dateLastContact, fall back
      // to updatedAt. Sortable on dateLastContact server-side; the column
      // header label ("Last activity") makes the fallback semantics clear.
      id: 'dateLastContact',
      accessorKey: 'dateLastContact',
      header: 'Last activity',
      cell: ({ row }) => {
        const lastIso = row.original.dateLastContact ?? row.original.updatedAt ?? null;
        if (!lastIso) {
          return <span className="text-muted-foreground text-sm">—</span>;
        }
        const d = new Date(lastIso);
        return (
          <span className="text-muted-foreground text-sm tabular-nums" title={format(d, 'PPpp')}>
            {formatDistanceToNowStrict(d, { addSuffix: true })}
          </span>
        );
      },
    },
    {
      id: 'actions',
      header: '',
      enableSorting: false,
      size: 48,
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              onClick={(e) => e.stopPropagation()}
            >
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => onEdit(row.original)}>
              <Pencil className="mr-2 h-3.5 w-3.5" />
              Edit
            </DropdownMenuItem>
            <DropdownMenuItem className="text-destructive" onClick={() => onArchive(row.original)}>
              <Archive className="mr-2 h-3.5 w-3.5" />
              Archive
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];
}
