'use client';

import Link from 'next/link';
import type { Route } from 'next';
import { format } from 'date-fns';
import { Mail, Phone } from 'lucide-react';
import { WhatsAppIcon } from '@/components/icons/whatsapp';
import type { ColumnDef } from '@tanstack/react-table';

import { Badge } from '@/components/ui/badge';
import type { ColumnPickerOption } from '@/components/shared/column-picker';

export interface ResidentialClientRow {
  id: string;
  fullName: string;
  email: string | null;
  phone: string | null;
  placeOfResidence: string | null;
  status: string;
  source: string | null;
  createdAt: string;
  updatedAt: string;
}

const STATUS_LABELS: Record<string, string> = {
  prospect: 'Prospect',
  active: 'Active',
  inactive: 'Inactive',
};

/**
 * Column manifest for the residential clients list `<ColumnPicker>`.
 * Mirrors the marina-side clients/interests pattern so the residential
 * team gets the same show/hide affordance.
 */
export const RESIDENTIAL_CLIENT_COLUMN_OPTIONS: ColumnPickerOption[] = [
  { id: 'fullName', label: 'Name', alwaysVisible: true },
  { id: 'email', label: 'Email' },
  { id: 'phone', label: 'Phone' },
  { id: 'residence', label: 'Residence' },
  { id: 'status', label: 'Status' },
  { id: 'source', label: 'Source' },
  { id: 'createdAt', label: 'Date added' },
];

/**
 * "Residence" is empty for nearly every residential client (we don't
 * capture it at intake — it rendered as a column of "-"), so it's hidden
 * by default and "Date added" takes its place. Users can re-enable
 * Residence via the picker; their choice then persists.
 */
export const RESIDENTIAL_CLIENT_DEFAULT_HIDDEN: string[] = ['residence'];

export function getResidentialClientColumns({
  portSlug,
}: {
  portSlug: string;
}): ColumnDef<ResidentialClientRow, unknown>[] {
  return [
    {
      id: 'fullName',
      accessorKey: 'fullName',
      header: 'Name',
      cell: ({ row }) => (
        <Link
          href={`/${portSlug}/residential/clients/${row.original.id}` as Route}
          className="font-medium text-primary hover:underline"
          onClick={(e) => e.stopPropagation()}
        >
          {row.original.fullName}
        </Link>
      ),
    },
    {
      id: 'email',
      header: 'Email',
      enableSorting: false,
      cell: ({ row }) => {
        const value = row.original.email;
        if (!value) return <span className="text-muted-foreground">-</span>;
        return (
          <a
            href={`mailto:${value}`}
            onClick={(e) => e.stopPropagation()}
            className="inline-flex items-center gap-1.5 text-sm text-foreground hover:text-primary hover:underline"
            title={`Email ${value}`}
          >
            <Mail className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />
            <span className="truncate">{value}</span>
          </a>
        );
      },
    },
    {
      id: 'phone',
      header: 'Phone',
      enableSorting: false,
      cell: ({ row }) => {
        const value = row.original.phone;
        if (!value) return <span className="text-muted-foreground">-</span>;
        const waDigits = value.replace(/[^\d]/g, '');
        return (
          <span className="inline-flex items-center gap-1.5 text-sm">
            <a
              href={`tel:${value}`}
              onClick={(e) => e.stopPropagation()}
              className="inline-flex items-center gap-1.5 text-foreground hover:text-primary hover:underline"
              title={`Call ${value}`}
            >
              <Phone className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />
              <span>{value}</span>
            </a>
            <a
              href={`https://wa.me/${waDigits}`}
              target="_blank"
              rel="noopener noreferrer"
              onClick={(e) => e.stopPropagation()}
              className="text-emerald-600 hover:text-emerald-700"
              title={`WhatsApp ${value}`}
              aria-label={`WhatsApp ${value}`}
            >
              <WhatsAppIcon className="h-3.5 w-3.5" />
            </a>
          </span>
        );
      },
    },
    {
      id: 'residence',
      accessorKey: 'placeOfResidence',
      header: 'Residence',
      enableSorting: false,
      cell: ({ getValue }) => {
        const v = getValue() as string | null;
        return v ? (
          <span className="text-muted-foreground">{v}</span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
    },
    {
      id: 'status',
      accessorKey: 'status',
      header: 'Status',
      cell: ({ getValue }) => {
        const s = getValue() as string;
        return (
          <Badge variant="outline" className="text-xs">
            {STATUS_LABELS[s] ?? s}
          </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="capitalize text-xs">
            {source}
          </Badge>
        );
      },
    },
    {
      id: 'createdAt',
      accessorKey: 'createdAt',
      header: 'Date added',
      cell: ({ getValue }) => (
        <span className="text-sm text-muted-foreground">
          {format(new Date(getValue() as string), 'MMM d, yyyy')}
        </span>
      ),
    },
  ];
}
