import { DataTableColumnHeader } from '@repo/rdx-ui/components';
import {
  Avatar,
  AvatarFallback,
  Badge,
  Button,
  DropdownMenu, DropdownMenuContent,
  DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from '@repo/shadcn-ui/components';
import { cn } from '@repo/shadcn-ui/lib/utils';
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)}` : "-";
}

const statuses = {
  inactive: 'text-gray-400 bg-gray-100 dark:text-gray-500 dark:bg-gray-100/10',
  active: 'text-green-500 bg-green-500/10 dark:text-green-400 dark:bg-green-400/10',
  error: 'text-rose-500 bg-rose-500/10 dark:text-rose-400 dark:bg-rose-400/10',
}

// ---- Helpers UI ----
const StatusBadge = ({ status }: { status: string }) => {
  // Map visual simple; ajustar a tu catálogo real
  const statusClass = React.useMemo(() => status.toLowerCase() === 'active' ? statuses.active : statuses.inactive, [status]);
  const contentTxt = React.useMemo(() => status.toLowerCase() === 'active' ? 'El cliente está activo' : 'El cliente está inactivo', [status]);

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div className={cn('flex-none rounded-full p-1', statusClass)}>
          <div className="size-2 rounded-full bg-current" />
        </div>
      </TooltipTrigger>
      <TooltipContent>{contentTxt}
      </TooltipContent>
    </Tooltip>
  )
};

const KindBadge = ({ isCompany }: { isCompany: boolean }) => (
  <Badge variant="outline" className="gap-1 tracking-wide text-xs text-foreground/70">
    {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 text-foreground text-sm my-1.5">

    {customer.email_primary && (
      <div className='flex items-center gap-2'>
        <MailIcon className='size-3.5' />
        <a className='group' href={`mailto:${customer.email_primary}`}>
          {customer.email_primary}
        </a>
      </div>
    )}

    {customer.email_secondary && (
      <div className="flex items-center gap-2"><MailIcon className="size-3.5" />{customer.email_secondary}</div>
    )}

    <div className="flex flex-wrap items-center gap-2">
      <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>}
      {false && customer.fax && <Soft>• fax {customer.fax}</Soft>}
    </div>
    {false && customer.website && (
      <div className="flex flex-wrap 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 = ({ c }: { c: CustomerSummaryFormData }) => {
  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-foreground  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: "customer",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.customer")} className="text-left" />
      ),
      accessorFn: (row) => row.name, // para ordenar/buscar por nombre
      enableHiding: false,
      size: 140,
      minSize: 120,
      cell: ({ row }) => {
        const c = row.original;
        const isCompany = String(c.is_company).toLowerCase() === "true";
        return (
          <div className="flex items-start gap-1 my-1.5">
            <Avatar className="size-10 hidden">
              <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">
                <StatusBadge status={c.status} /> <span className="font-medium truncate text-primary">{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-base truncate">{c.tin}</span>}
                <KindBadge isCompany={isCompany} />
              </div>
            </div>
          </div>
        );
      },
    },

    // Contacto (emails, teléfonos, web)
    {
      id: "contact",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.contact")} className="text-left" />
      ),
      accessorFn: (r) => `${r.email_primary} ${r.phone_primary} ${r.mobile_primary} ${r.website}`,
      size: 140,
      minSize: 120,
      cell: ({ row }) => <ContactCell customer={row.original} />,
    },

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

    // Acciones
    {
      id: "actions",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.actions")} className="text-right" />
      ),
      size: 64,
      minSize: 64,
      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]);
}
