'use client';

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

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

export type InquiryKind = 'berth_inquiry' | 'residence_inquiry' | 'contact_form';
export type InquiryTriageState = 'open' | 'assigned' | 'converted' | 'dismissed';

export interface InquiryRow {
  id: string;
  kind: InquiryKind;
  contactName: string | null;
  contactEmail: string | null;
  receivedAt: string;
  triageState: InquiryTriageState;
  convertedClientId: string | null;
  convertedInterestId: string | null;
  sourceIp: string | null;
  utmSource?: string | null;
}

export const KIND_LABELS: Record<InquiryKind, string> = {
  berth_inquiry: 'Berth',
  residence_inquiry: 'Residence',
  contact_form: 'Contact',
};

const KIND_TONE: Record<InquiryKind, string> = {
  berth_inquiry: 'bg-blue-100 text-blue-800',
  residence_inquiry: 'bg-amber-100 text-amber-900',
  contact_form: 'bg-slate-100 text-slate-800',
};

export const TRIAGE_TONE: Record<InquiryTriageState, string> = {
  open: 'bg-blue-100 text-blue-800',
  assigned: 'bg-amber-100 text-amber-900',
  converted: 'bg-emerald-100 text-emerald-800',
  dismissed: 'bg-slate-100 text-slate-600',
};

export const TRIAGE_LABELS: Record<InquiryTriageState, string> = {
  open: 'Open',
  assigned: 'Assigned',
  converted: 'Converted',
  dismissed: 'Dismissed',
};

export const INQUIRY_COLUMN_OPTIONS: Array<{ id: string; label: string }> = [
  { id: 'contactEmail', label: 'Email' },
  { id: 'kind', label: 'Type' },
  { id: 'triageState', label: 'Status' },
  { id: 'utmSource', label: 'UTM source' },
  { id: 'receivedAt', label: 'Received' },
];

export const INQUIRY_DEFAULT_HIDDEN: string[] = ['utmSource'];

interface GetColumnsOptions {
  portSlug: string;
  onTriage: (row: InquiryRow, state: InquiryTriageState) => void;
}

export function getInquiryColumns({
  portSlug,
  onTriage,
}: GetColumnsOptions): ColumnDef<InquiryRow, unknown>[] {
  return [
    {
      id: 'contactName',
      accessorKey: 'contactName',
      header: 'Name',
      cell: ({ row }) => (
        <Link
          href={`/${portSlug}/inquiries/${row.original.id}`}
          className="truncate font-medium text-primary hover:underline"
          onClick={(e) => e.stopPropagation()}
        >
          {row.original.contactName || '(no name)'}
        </Link>
      ),
    },
    {
      id: 'contactEmail',
      accessorKey: 'contactEmail',
      header: 'Email',
      enableSorting: false,
      cell: ({ getValue }) => {
        const email = getValue() as string | null;
        return email ? (
          <span className="text-sm">{email}</span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
    },
    {
      id: 'kind',
      accessorKey: 'kind',
      header: 'Type',
      cell: ({ getValue }) => {
        const kind = getValue() as InquiryKind;
        return <Badge className={KIND_TONE[kind]}>{KIND_LABELS[kind]}</Badge>;
      },
    },
    {
      id: 'triageState',
      accessorKey: 'triageState',
      header: 'Status',
      cell: ({ row }) => {
        const state = row.original.triageState;
        return (
          <div className="flex items-center gap-1.5">
            <Badge className={TRIAGE_TONE[state]}>{TRIAGE_LABELS[state]}</Badge>
            {row.original.convertedInterestId ? (
              <Link
                href={`/${portSlug}/interests/${row.original.convertedInterestId}`}
                className="text-primary hover:underline text-xs"
                onClick={(e) => e.stopPropagation()}
              >
                interest →
              </Link>
            ) : row.original.convertedClientId ? (
              <Link
                href={`/${portSlug}/clients/${row.original.convertedClientId}`}
                className="text-primary hover:underline text-xs"
                onClick={(e) => e.stopPropagation()}
              >
                client →
              </Link>
            ) : null}
          </div>
        );
      },
    },
    {
      id: 'utmSource',
      accessorKey: 'utmSource',
      header: 'UTM source',
      enableSorting: false,
      cell: ({ getValue }) => {
        const utm = getValue() as string | null;
        return utm ? (
          <span className="text-sm">{utm}</span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
    },
    {
      id: 'receivedAt',
      accessorKey: 'receivedAt',
      header: 'Received',
      cell: ({ getValue }) => {
        const iso = getValue() as string;
        const d = new Date(iso);
        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 }) => {
        const isResolved =
          row.original.triageState === 'converted' || row.original.triageState === 'dismissed';
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                aria-label={`Row actions for ${row.original.contactName ?? 'inquiry'}`}
                onClick={(e) => e.stopPropagation()}
              >
                <MoreHorizontal className="h-4 w-4" aria-hidden />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem asChild>
                <Link href={`/${portSlug}/inquiries/${row.original.id}`}>
                  <ExternalLink className="mr-2 h-3.5 w-3.5" aria-hidden />
                  Open
                </Link>
              </DropdownMenuItem>
              {!isResolved ? (
                <>
                  <DropdownMenuItem onClick={() => onTriage(row.original, 'assigned')}>
                    <UserCheck className="mr-2 h-3.5 w-3.5" aria-hidden />
                    Assign to me
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => onTriage(row.original, 'dismissed')}>
                    <X className="mr-2 h-3.5 w-3.5" aria-hidden />
                    Dismiss
                  </DropdownMenuItem>
                </>
              ) : (
                <DropdownMenuItem onClick={() => onTriage(row.original, 'open')}>
                  Reopen
                </DropdownMenuItem>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];
}
