import {
  Button, Item,
  ItemContent,
  ItemDescription,
  ItemFooter,
  ItemTitle
} from "@repo/shadcn-ui/components";
import {
  EyeIcon,
  MapPinIcon,
  RefreshCwIcon,
  UserPlusIcon
} from "lucide-react";
import React, { useMemo } from 'react';
import { CustomerSummary } from "../../schemas";


interface CustomerCardProps {
  customer: CustomerSummary;
  onViewCustomer?: () => void;
  onChangeCustomer?: () => void;
  onAddNewCustomer?: () => void;
  className?: string;
}

function buildAddress(customer: CustomerSummary) {
  // Línea 1: calle(s)
  const line1 = [customer.street, customer.street2].filter(Boolean).join(", ");

  // Línea 2: CP + ciudad con espacio no rompible entre CP y ciudad
  const line2Parts: string[] = [];
  if (customer.postal_code && customer.city) {
    line2Parts.push(`${customer.postal_code}\u00A0${customer.city}`); // CP Ciudad
  } else {
    if (customer.postal_code) line2Parts.push(customer.postal_code);
    if (customer.city) line2Parts.push(customer.city);
  }
  const line2 = line2Parts.join(" ");

  // Línea 3: provincia + país
  const line3 = [customer.province, customer.country].filter(Boolean).join(", ");

  const stack = [line1, line2, line3].filter(Boolean);
  const inline = stack.join(" · "); // separador compacto
  const full = stack.join(", ");

  return { has: stack.length > 0, stack, inline, full };
}

export const CustomerCard = ({
  customer,
  onViewCustomer,
  onChangeCustomer,
  onAddNewCustomer,
  className,
}: CustomerCardProps) => {
  const address = useMemo(() => buildAddress(customer), [customer]);

  return (
    <Item variant="outline" className={className}>
      <ItemContent>
        <ItemTitle className="flex items-start gap-2 w-full justify-between">
          <span className="grow text-balance">{customer.name}</span>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="cursor-pointer"
            onClick={onViewCustomer}
            aria-label="Ver ficha completa del cliente"
          >
            <EyeIcon className="size-4 text-muted-foreground" />
          </Button>
        </ItemTitle>
        <ItemDescription className="text-sm text-muted-foreground">
          {/* TIN en su propia línea si existe */}
          {customer.tin && (
            <div className="font-mono tabular-nums">{customer.tin}</div>
          )}

          {/* Dirección */}
          {address.has ? (
            <address
              className="not-italic mt-1 text-pretty"
              aria-label={address.full}
            >
              {/* Desktop/tablet: compacto en una línea (o dos por wrap natural) */}
              <div className="hidden sm:flex items-center gap-1 flex-wrap">
                <MapPinIcon aria-hidden className="size-3.5 translate-y-[1px]" />
                {/* Partes con separadores reales para que el wrap ocurra en “ · ” */}
                {address.stack.map((part, i) => (
                  <React.Fragment key={i}>
                    <span>{part}</span>
                    {i < address.stack.length - 1 && (
                      <span aria-hidden className="mx-1">·</span>
                    )}
                  </React.Fragment>
                ))}
              </div>

              {/* Móvil: apilado (3 líneas máximo) */}
              <div className="sm:hidden">
                <div className="flex items-start gap-1">
                  <MapPinIcon aria-hidden className="size-3.5 translate-y-[1px]" />
                  <div className="flex-1">
                    {address.stack.map((line, i) => (
                      <div key={i}>{line}</div>
                    ))}
                  </div>
                </div>
              </div>
            </address>
          ) : (
            <span className="italic text-muted-foreground">Sin dirección</span>
          )}
        </ItemDescription>
      </ItemContent>

      {/* Footer con acciones */}
      <ItemFooter className="flex-wrap gap-2">
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={onChangeCustomer}
          className="flex-1 min-w-36 gap-2 cursor-pointer"
        >
          <RefreshCwIcon className="size-4" />
          <span className="text-sm text-muted-foreground">Cambiar de cliente</span>
        </Button>

        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={onAddNewCustomer}
          className="flex-1 min-w-36 gap-2 cursor-pointer"
        >
          <UserPlusIcon className="size-4" />
          <span className="text-sm text-muted-foreground">Nuevo cliente</span>
        </Button>
      </ItemFooter>
    </Item>
  );
};