import React, { useState } from 'react';
import { CreditCard, Banknote, ArrowRightLeft, Receipt, User } from 'lucide-react';
import { Card } from '../../ui/Card';
import { Button } from '../../ui/Button';
import { Input } from '../../ui/Input';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

interface CustomerInfo {
  name: string;
  email: string;
  phone: string;
}

interface POSPaymentProps {
  total: number;
  onProcessPayment: (paymentData: {
    paymentMethod: 'cash' | 'card' | 'transfer';
    cashReceived?: number;
    change?: number;
    customerInfo?: CustomerInfo;
  }) => void;
  disabled?: boolean;
}

/**
 * POSPayment - Color-coded payment section with customer info
 * Optimized for quick checkout with visual payment method selection
 */
export const POSPayment: React.FC<POSPaymentProps> = ({
  total,
  onProcessPayment,
  disabled = false,
}) => {
  const { currencySymbol } = useTenantCurrency();
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'card' | 'transfer'>('cash');
  const [cashReceived, setCashReceived] = useState('');
  const [customerInfo, setCustomerInfo] = useState<CustomerInfo>({
    name: '',
    email: '',
    phone: '',
  });
  const [showCustomerForm, setShowCustomerForm] = useState(false);

  const change = cashReceived ? Math.max(0, parseFloat(cashReceived) - total) : 0;
  const canProcessPayment =
    !disabled &&
    (paymentMethod === 'card' ||
      paymentMethod === 'transfer' ||
      (paymentMethod === 'cash' && cashReceived && parseFloat(cashReceived) >= total));

  const handleProcessPayment = () => {
    if (!canProcessPayment) return;

    onProcessPayment({
      paymentMethod,
      cashReceived: paymentMethod === 'cash' ? parseFloat(cashReceived) : undefined,
      change: paymentMethod === 'cash' ? change : undefined,
      customerInfo: showCustomerForm ? customerInfo : undefined,
    });

    // Reset form
    setCashReceived('');
    setCustomerInfo({ name: '', email: '', phone: '' });
    setShowCustomerForm(false);
  };

  // Payment method configurations with colors
  const paymentMethods = [
    {
      id: 'cash' as const,
      name: 'Efectivo',
      icon: Banknote,
      color: 'var(--color-success)',
      bgColor: 'var(--color-success-light)',
      borderColor: 'var(--color-success-dark)',
    },
    {
      id: 'card' as const,
      name: 'Tarjeta',
      icon: CreditCard,
      color: 'var(--color-info)',
      bgColor: 'var(--color-info-light)',
      borderColor: 'var(--color-info-dark)',
    },
    {
      id: 'transfer' as const,
      name: 'Transferencia',
      icon: ArrowRightLeft,
      color: 'var(--color-secondary)',
      bgColor: 'var(--color-secondary-light)',
      borderColor: 'var(--color-secondary-dark)',
    },
  ];

  return (
    <div className="space-y-4">
      {/* Customer Info Toggle */}
      <Card className="p-4">
        <button
          onClick={() => setShowCustomerForm(!showCustomerForm)}
          className="w-full flex items-center justify-between text-left"
        >
          <div className="flex items-center gap-2">
            <User className="w-5 h-5 text-[var(--color-primary)]" />
            <span className="font-semibold text-[var(--text-primary)]">
              Cliente (Opcional)
            </span>
          </div>
          <span className="text-[var(--text-tertiary)]">
            {showCustomerForm ? '▼' : '▶'}
          </span>
        </button>

        {showCustomerForm && (
          <div className="mt-4 space-y-3">
            <Input
              placeholder="Nombre"
              value={customerInfo.name}
              onChange={(e) =>
                setCustomerInfo((prev) => ({ ...prev, name: e.target.value }))
              }
            />
            <Input
              placeholder="Email"
              type="email"
              value={customerInfo.email}
              onChange={(e) =>
                setCustomerInfo((prev) => ({ ...prev, email: e.target.value }))
              }
            />
            <Input
              placeholder="Teléfono"
              value={customerInfo.phone}
              onChange={(e) =>
                setCustomerInfo((prev) => ({ ...prev, phone: e.target.value }))
              }
            />
          </div>
        )}
      </Card>

      {/* Payment Method Selection */}
      <Card className="p-4">
        <h3 className="text-lg font-bold text-[var(--text-primary)] mb-4">
          Método de Pago
        </h3>

        <div className="grid grid-cols-1 gap-3">
          {paymentMethods.map((method) => {
            const Icon = method.icon;
            const isSelected = paymentMethod === method.id;

            return (
              <button
                key={method.id}
                onClick={() => setPaymentMethod(method.id)}
                className={`
                  relative p-4 rounded-xl transition-all duration-200
                  border-2 font-semibold text-left
                  hover:scale-[1.02] active:scale-[0.98]
                  ${
                    isSelected
                      ? 'shadow-lg ring-4 ring-opacity-30'
                      : 'shadow hover:shadow-md'
                  }
                `}
                style={{
                  backgroundColor: isSelected ? method.bgColor : 'var(--bg-secondary)',
                  borderColor: isSelected ? method.borderColor : 'var(--border-secondary)',
                  color: isSelected ? method.color : 'var(--text-primary)',
                  ...(isSelected && {
                    ringColor: method.color,
                  }),
                }}
              >
                <div className="flex items-center gap-3">
                  <Icon className="w-6 h-6" />
                  <span className="text-base">{method.name}</span>
                  {isSelected && (
                    <span className="ml-auto text-2xl">✓</span>
                  )}
                </div>
              </button>
            );
          })}
        </div>

        {/* Cash Input */}
        {paymentMethod === 'cash' && (
          <div className="mt-4 space-y-3">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Efectivo Recibido
              </label>
              <Input
                type="number"
                step="0.01"
                placeholder={`${currencySymbol}0.00`}
                value={cashReceived}
                onChange={(e) => setCashReceived(e.target.value)}
                className="text-lg font-semibold"
              />
            </div>

            {/* Change Display */}
            {cashReceived && parseFloat(cashReceived) >= total && (
              <Card
                className="p-4 border-2"
                style={{
                  backgroundColor: 'var(--color-success-light)',
                  borderColor: 'var(--color-success)',
                }}
              >
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium" style={{ color: 'var(--color-success-dark)' }}>
                    Cambio:
                  </span>
                  <span className="text-2xl font-bold" style={{ color: 'var(--color-success-dark)' }}>
                    {currencySymbol}{change.toFixed(2)}
                  </span>
                </div>
              </Card>
            )}

            {/* Insufficient Cash Warning */}
            {cashReceived && parseFloat(cashReceived) < total && (
              <Card
                className="p-3 border-2"
                style={{
                  backgroundColor: 'var(--color-warning-light)',
                  borderColor: 'var(--color-warning)',
                }}
              >
                <p className="text-sm font-medium text-center" style={{ color: 'var(--color-warning-dark)' }}>
                  Efectivo insuficiente: falta {currencySymbol}{(total - parseFloat(cashReceived)).toFixed(2)}
                </p>
              </Card>
            )}
          </div>
        )}
      </Card>

      {/* Process Payment Button */}
      <Button
        onClick={handleProcessPayment}
        disabled={!canProcessPayment}
        variant="primary"
        size="lg"
        className="w-full text-lg font-bold py-6 shadow-lg hover:shadow-xl transition-all"
      >
        <Receipt className="w-6 h-6 mr-2" />
        Procesar Venta - {currencySymbol}{total.toFixed(2)}
      </Button>
    </div>
  );
};

export default POSPayment;
