import { Button } from '@/components/ui/button';
import type { PublicBookingConfirmation } from '@repo/api-contract';
import { siWhatsapp } from 'simple-icons';

type ShareWhatsappButtonProps = {
  confirmation: PublicBookingConfirmation;
};

function formatDateLabel(isoDate: string) {
  const [year, month, day] = isoDate.split('-').map(Number);
  const date = new Date(year, (month ?? 1) - 1, day ?? 1);

  return new Intl.DateTimeFormat('es-AR', {
    weekday: 'long',
    day: '2-digit',
    month: 'long',
    year: 'numeric',
  }).format(date);
}

function formatBookingPrice(price: number): string {
  if (price === 0) {
    return 'Sin cargo';
  }

  return new Intl.NumberFormat('es-AR', {
    style: 'currency',
    currency: 'ARS',
    maximumFractionDigits: Number.isInteger(price) ? 0 : 2,
  }).format(price);
}

function createWhatsappMessage(confirmation: PublicBookingConfirmation) {
  const dateLabel = formatDateLabel(confirmation.date);
  const lines = ['Ya reservamos cancha para jugar.', `Complejo: ${confirmation.complexName}`];

  if (confirmation.complexAddress) {
    lines.push(`Direccion: ${confirmation.complexAddress}`);
  }

  lines.push(
    `Cancha: ${confirmation.courtName} (${confirmation.sport.name})`,
    `Fecha: ${dateLabel}`,
    `Horario: ${confirmation.startTime} - ${confirmation.endTime}`,
    `Precio: ${formatBookingPrice(confirmation.price)}`,
    `Codigo de reserva: ${confirmation.bookingCode}`
  );

  return lines.join('\n');
}

export function ShareWhatsappButton({ confirmation }: ShareWhatsappButtonProps) {
  const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(
    createWhatsappMessage(confirmation)
  )}`;

  return (
    <Button
      type="button"
      variant="outline"
      className="h-12 w-full rounded-xl border-slate-200 bg-white text-sm font-semibold text-slate-900 hover:bg-slate-50 sm:text-base"
      asChild
    >
      <a href={whatsappUrl} target="_blank" rel="noopener noreferrer">
        <svg
          viewBox="0 0 24 24"
          aria-hidden="true"
          className="size-4"
          style={{ color: `#${siWhatsapp.hex}` }}
        >
          <path d={siWhatsapp.path} fill="currentColor" />
        </svg>
        Compartir por WhatsApp
      </a>
    </Button>
  );
}
