import {
  Avatar,
  AvatarFallback,
  Badge,
  Button,
  DropdownMenu, DropdownMenuContent,
  DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger
} from '@repo/shadcn-ui/components';
import type { ColumnDef } from "@tanstack/react-table";
import { Building2Icon, GlobeIcon, MailIcon, MoreHorizontalIcon, PencilIcon, PhoneIcon, User2Icon } from 'lucide-react';
import * as React from "react";
import { useTranslation } from '../../i18n';
import { CustomerSummaryFormData } from '../../schemas';

type CustomerActionHandlers = {
  onEdit?: (customer: CustomerSummaryFormData) => void;
  onView?: (customer: CustomerSummaryFormData) => void;
  onDelete?: (customer: CustomerSummaryFormData) => void;
};

function shortId(id: string) {
  return id ? `${id.slice(0, 4)}_${id.slice(-4)}` : "-";
}

// ---- Helpers UI ----
const StatusBadge = ({ status }: { status: string }) => {
  // Map visual simple; ajustar a tu catálogo real
  const v =
    status.toLowerCase() === "active"
      ? "default"
      : status.toLowerCase() === "inactive"
        ? "outline"
        : "secondary";
  return (
    <Badge variant={v as any} className="uppercase tracking-wide text-[11px]">
      {status}
    </Badge>
  );
};

const KindBadge = ({ isCompany }: { isCompany: boolean }) => (
  <Badge variant="outline" className="gap-1">
    {isCompany ? <Building2Icon className="size-3.5" /> : <User2Icon className="size-3.5" />}
    {isCompany ? "Company" : "Person"}
  </Badge>
);

const Soft = ({ children }: { children: React.ReactNode }) => (
  <span className="text-muted-foreground">{children}</span>
);

const ContactCell = ({ customer }: { customer: CustomerSummaryFormData }) => (
  <div className="grid gap-1">
    <div className="flex items-center gap-2 group:text-foreground group-hover:text-primary">
      <MailIcon className="size-3.5 group" />
      <a className="group" href={`mailto:${customer.email_primary}`}>
        {customer.email_primary || <Soft>—</Soft>}
      </a>
      {customer.email_secondary && <Soft>• {customer.email_secondary}</Soft>}
    </div>
    <div className="flex flex-wrap items-center gap-2  group:text-foreground group-hover:text-primary">
      <PhoneIcon className="size-3.5 group" />
      <span>{customer.phone_primary || customer.mobile_primary || <Soft>-</Soft>}</span>
      {customer.phone_secondary && <Soft>• {customer.phone_secondary}</Soft>}
      {customer.mobile_secondary && <Soft>• {customer.mobile_secondary}</Soft>}
      {customer.fax && <Soft>• fax {customer.fax}</Soft>}
    </div>
    {customer.website && (
      <div className="flex items-center gap-2">
        <GlobeIcon className="size-3.5" />
        <a className="underline underline-offset-2" href={safeHttp(customer.website)} target="_blank" rel="noreferrer">
          {customer.website}
        </a>
      </div>
    )}
  </div>
);

const AddressCell: React.FC<{ c: CustomerSummaryFormData }> = ({ c }) => {
  const line1 = [c.street, c.street2].filter(Boolean).join(", ");
  const line2 = [c.postal_code, c.city].filter(Boolean).join(" ");
  const line3 = [c.province, c.country].filter(Boolean).join(", ");
  return (
    <address className="not-italic grid gap-1 text-sm">
      <div>{line1 || <Soft>—</Soft>}</div>
      <div>{[line2, line3].filter(Boolean).join(" • ")}</div>
    </address>
  );
};

function initials(name: string) {
  const parts = name.trim().split(/\s+/).slice(0, 2);
  return parts.map(p => p[0]?.toUpperCase() ?? "").join("") || "?";
}

function safeHttp(url: string) {
  if (!url) return "#";
  if (/^https?:\/\//i.test(url)) return url;
  return `https://${url}`;
}

export function useCustomersListColumns(
  handlers: CustomerActionHandlers = {}
): ColumnDef<CustomerSummaryFormData>[] {
  const { t } = useTranslation();
  const {
    onEdit, onView, onDelete,
  } = handlers;

  return React.useMemo<ColumnDef<CustomerSummaryFormData>[]>(() => [
    // Identidad + estado + metadatos (columna compuesta)
    {
      id: "identity",
      header: "Customer",
      accessorFn: (row) => row.name, // para ordenar/buscar por nombre
      enableHiding: false,
      size: 380,
      cell: ({ row }) => {
        const c = row.original;
        const isCompany = String(c.is_company).toLowerCase() === "true";
        return (
          <div className="flex items-start gap-3">
            <Avatar className="size-10">
              <AvatarFallback aria-label={c.name}>{initials(c.name)}</AvatarFallback>
            </Avatar>
            <div className="min-w-0 grid gap-1">
              <div className="flex flex-wrap items-center gap-2">
                <span className="font-medium truncate">{c.name}</span>
                {c.trade_name && <Soft>({c.trade_name})</Soft>}
              </div>
              <div className="flex flex-wrap items-center gap-2">
                {c.tin && <span className="font-medium truncate">{c.tin}</span>}
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <StatusBadge status={c.status} />
                <KindBadge isCompany={isCompany} />
                {c.reference && <Badge variant="secondary">Ref: {c.reference}</Badge>}
              </div>
            </div>
          </div>
        );
      },
    },

    // Contacto (emails, teléfonos, web)
    {
      id: "contact",
      header: "Contact",
      accessorFn: (r) => `${r.email_primary} ${r.phone_primary} ${r.mobile_primary} ${r.website}`,
      size: 420,
      cell: ({ row }) => <ContactCell customer={row.original} />,
    },

    // Dirección (múltiples campos en bloque)
    {
      id: "address",
      header: "Address",
      accessorFn: (r) =>
        `${r.street} ${r.street2} ${r.city} ${r.postal_code} ${r.province} ${r.country}`,
      size: 360,
      cell: ({ row }) => <AddressCell c={row.original} />,
    },

    // Acciones
    {
      id: "actions",
      header: () => <span className="sr-only">Actions</span>,
      size: 72,
      enableSorting: false,
      enableHiding: false,
      cell: ({ row }) => {
        const customer = row.original;
        const { website, email_primary } = customer;
        return (
          <div className="flex justify-end">
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="icon"
                aria-label="Edit customer"
                onClick={() => onEdit?.(customer)}
              >
                <PencilIcon className="size-4" />
              </Button>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" aria-label="More actions">
                    <MoreHorizontalIcon className="size-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel>Actions</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => onView?.(customer)}>Open</DropdownMenuItem>
                  <DropdownMenuItem onClick={() => onEdit?.(customer)}>Edit</DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => window.open(safeHttp(website), "_blank")}>
                    Visit website
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => navigator.clipboard.writeText(email_primary)}>
                    Copy email
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    className="text-destructive"
                    onClick={() => onDelete?.(customer)}
                  >
                    Delete
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        );
      },
    },
  ], [t, onEdit, onView, onDelete]);
}
