'use client';

import React, { useState } from 'react';
import { Smartphone, Banknote, CreditCard, SplitSquareHorizontal, CheckCircle2, Loader2, Printer, RotateCcw } from 'lucide-react';
import { toast } from 'sonner';
import { CartItem } from './posData';
import MpesaModal from './MpesaModal';
import Icon from '@/components/ui/AppIcon';


type PaymentMethod = 'cash' | 'mpesa' | 'card' | 'split';

interface PaymentPanelProps {
  grandTotal: number;
  cart: CartItem[];
  customer: { id: string; name: string; phone: string } | null;
  onComplete: () => void;
}

const paymentMethods = [
  { id: 'pm-cash', key: 'cash' as PaymentMethod, label: 'Cash', icon: Banknote, color: 'text-success', activeBg: 'bg-success/10 border-success/40' },
  { id: 'pm-mpesa', key: 'mpesa' as PaymentMethod, label: 'M-Pesa', icon: Smartphone, color: 'text-info', activeBg: 'bg-info/10 border-info/40' },
  { id: 'pm-card', key: 'card' as PaymentMethod, label: 'Card', icon: CreditCard, color: 'text-primary', activeBg: 'bg-primary/10 border-primary/40' },
  { id: 'pm-split', key: 'split' as PaymentMethod, label: 'Split', icon: SplitSquareHorizontal, color: 'text-warning', activeBg: 'bg-warning/10 border-warning/40' },
];

const quickAmounts = [500, 1000, 2000, 5000];

export default function PaymentPanel({ grandTotal, cart, customer, onComplete }: PaymentPanelProps) {
  const [method, setMethod] = useState<PaymentMethod>('cash');
  const [tendered, setTendered] = useState('');
  const [mpesaOpen, setMpesaOpen] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [completed, setCompleted] = useState(false);
  const [receiptNo, setReceiptNo] = useState('');

  // Split payment state
  const [splitCash, setSplitCash] = useState('');
  const [splitMpesa, setSplitMpesa] = useState('');

  const tenderedNum = parseFloat(tendered) || 0;
  const change = Math.max(0, tenderedNum - grandTotal);
  const cartEmpty = cart.length === 0;

  const handleNumpad = (val: string) => {
    if (val === 'C') { setTendered(''); return; }
    if (val === '⌫') { setTendered((prev) => prev.slice(0, -1)); return; }
    if (val === '.' && tendered.includes('.')) return;
    setTendered((prev) => prev + val);
  };

  // Backend integration point: POST /api/sales/complete
  const processPayment = async () => {
    if (cartEmpty) { toast.error('Add products to the cart first'); return; }
    if (method === 'mpesa') { setMpesaOpen(true); return; }
    if (method === 'cash' && tenderedNum < grandTotal) {
      toast.error(`Insufficient cash — need KES ${(grandTotal - tenderedNum).toFixed(0)} more`);
      return;
    }
    if (method === 'split') {
      const splitTotal = (parseFloat(splitCash) || 0) + (parseFloat(splitMpesa) || 0);
      if (splitTotal < grandTotal) {
        toast.error(`Split total KES ${splitTotal} is less than grand total KES ${grandTotal.toFixed(0)}`);
        return;
      }
    }

    setProcessing(true);
    await new Promise((r) => setTimeout(r, 1400));
    const ref = `S-${20848 + Math.floor(Math.random() * 10)}`;
    setReceiptNo(ref);
    setProcessing(false);
    setCompleted(true);
    toast.success(`Sale ${ref} completed — KES ${grandTotal.toLocaleString()} received`);
  };

  const handleNewSale = () => {
    setCompleted(false);
    setTendered('');
    setSplitCash('');
    setSplitMpesa('');
    setReceiptNo('');
    setMethod('cash');
    onComplete();
  };

  const numpadKeys = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '.', '0', '⌫'];

  if (completed) {
    return (
      <div className="flex flex-col items-center justify-center h-full bg-success-bg/30 px-5 text-center">
        <div className="w-16 h-16 rounded-full bg-success/20 flex items-center justify-center mb-4">
          <CheckCircle2 size={36} className="text-success" />
        </div>
        <h3 className="text-lg font-700 text-foreground mb-1">Sale Complete!</h3>
        <p className="text-sm text-muted-foreground mb-1">Receipt: <span className="font-mono font-700 text-foreground">{receiptNo}</span></p>
        <p className="text-2xl font-800 text-foreground font-tabular mb-1">KES {grandTotal.toLocaleString()}</p>
        {method === 'cash' && change > 0 && (
          <div className="badge-warning px-3 py-1.5 rounded-lg mb-4">
            <p className="text-sm font-700">Change: KES {change.toLocaleString()}</p>
          </div>
        )}
        <div className="flex flex-col gap-2 w-full mt-4">
          <button
            onClick={() => toast.success('Receipt sent to printer')}
            className="w-full flex items-center justify-center gap-2 h-10 border border-border rounded-lg text-sm font-600 text-foreground hover:bg-muted transition-colors"
          >
            <Printer size={15} />
            Print Receipt
          </button>
          <button
            onClick={handleNewSale}
            className="w-full flex items-center justify-center gap-2 h-10 btn-primary rounded-lg text-sm font-600 text-white"
          >
            <RotateCcw size={15} />
            New Sale
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-card">
      {/* Header */}
      <div className="px-4 py-3 border-b border-border flex-shrink-0">
        <h2 className="text-sm font-700 text-foreground">Payment</h2>
        {cartEmpty ? (
          <p className="text-xs text-muted-foreground mt-0.5">Add items to the cart to proceed</p>
        ) : (
          <p className="text-xs text-muted-foreground mt-0.5">
            Total: <span className="font-700 text-primary font-tabular">KES {grandTotal.toLocaleString()}</span>
          </p>
        )}
      </div>

      <div className="flex-1 overflow-y-auto scrollbar-thin px-4 py-3 space-y-4">
        {/* Payment method selector */}
        <div>
          <p className="text-xs font-600 uppercase tracking-wide text-muted-foreground mb-2">Payment Method</p>
          <div className="grid grid-cols-2 gap-2">
            {paymentMethods.map((pm) => {
              const Icon = pm.icon;
              const active = method === pm.key;
              return (
                <button
                  key={pm.id}
                  onClick={() => setMethod(pm.key)}
                  className={`flex items-center gap-2 px-3 py-2.5 rounded-lg border text-sm font-600 transition-all duration-150 ${
                    active
                      ? `${pm.activeBg} ${pm.color}`
                      : 'border-border text-muted-foreground hover:bg-muted hover:text-foreground'
                  }`}
                >
                  <Icon size={15} />
                  {pm.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Cash inputs */}
        {method === 'cash' && (
          <div className="space-y-3">
            <div>
              <label className="block text-xs font-600 text-foreground mb-1.5">Amount Tendered (KES)</label>
              <input
                type="text"
                value={tendered}
                readOnly
                placeholder="0.00"
                className="w-full h-11 px-3 text-right text-lg font-800 font-tabular bg-muted border border-border rounded-lg outline-none text-foreground"
              />
            </div>
            {tenderedNum >= grandTotal && grandTotal > 0 && (
              <div className="flex items-center justify-between bg-success-bg border border-green-200 rounded-lg px-3 py-2">
                <span className="text-xs font-600 text-success">Change</span>
                <span className="text-lg font-800 text-success font-tabular">KES {change.toLocaleString()}</span>
              </div>
            )}
            <div>
              <p className="text-xs font-600 text-muted-foreground mb-1.5">Quick Amounts</p>
              <div className="grid grid-cols-4 gap-1.5">
                {quickAmounts.map((amt) => (
                  <button
                    key={`quick-${amt}`}
                    onClick={() => setTendered(amt.toString())}
                    className="h-8 rounded-md bg-muted hover:bg-border text-xs font-600 text-foreground transition-colors font-tabular"
                  >
                    {amt >= 1000 ? `${amt / 1000}k` : amt}
                  </button>
                ))}
              </div>
            </div>
            <button
              onClick={() => setTendered(grandTotal.toFixed(0))}
              className="w-full h-8 rounded-md border border-primary/30 bg-primary/5 text-xs font-600 text-primary hover:bg-primary/10 transition-colors"
            >
              Exact Amount (KES {grandTotal.toLocaleString()})
            </button>
          </div>
        )}

        {/* M-Pesa */}
        {method === 'mpesa' && (
          <div className="space-y-3">
            <div className="bg-info-bg border border-blue-200 rounded-lg p-3">
              <div className="flex items-center gap-2 mb-1">
                <Smartphone size={15} className="text-info" />
                <p className="text-xs font-700 text-info">M-Pesa STK Push</p>
              </div>
              <p className="text-xs text-muted-foreground leading-relaxed">
                A payment prompt will be sent to the customer's phone. They will enter their M-Pesa PIN to confirm KES {grandTotal.toLocaleString()}.
              </p>
            </div>
            <div>
              <label className="block text-xs font-600 text-foreground mb-1.5">Customer Phone Number</label>
              <input
                type="tel"
                defaultValue={customer?.phone ?? ''}
                placeholder="07XXXXXXXX"
                className="w-full h-10 px-3 text-sm bg-card border border-border rounded-lg outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 text-foreground placeholder:text-muted-foreground"
              />
              <p className="text-xs text-muted-foreground mt-1">Safaricom number registered with M-Pesa</p>
            </div>
          </div>
        )}

        {/* Card */}
        {method === 'card' && (
          <div className="bg-primary/5 border border-primary/20 rounded-lg p-3 space-y-2">
            <div className="flex items-center gap-2">
              <CreditCard size={15} className="text-primary" />
              <p className="text-xs font-700 text-primary">Card / POS Machine</p>
            </div>
            <p className="text-xs text-muted-foreground">
              Swipe or insert card on the POS machine. Confirm KES {grandTotal.toLocaleString()} on the card terminal, then click Process Payment.
            </p>
            <div className="flex items-center gap-2 mt-2">
              {['Visa', 'Mastercard', 'Amex'].map((brand) => (
                <span key={`card-brand-${brand.toLowerCase()}`} className="px-2 py-0.5 bg-card border border-border rounded text-xs font-600 text-muted-foreground">
                  {brand}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* Split payment */}
        {method === 'split' && (
          <div className="space-y-3">
            <p className="text-xs text-muted-foreground">Allocate total KES {grandTotal.toLocaleString()} across payment methods</p>
            <div>
              <label className="block text-xs font-600 text-foreground mb-1.5">Cash Amount (KES)</label>
              <input
                type="number"
                value={splitCash}
                onChange={(e) => setSplitCash(e.target.value)}
                placeholder="0"
                className="w-full h-9 px-3 text-sm bg-card border border-border rounded-lg outline-none focus:border-primary text-foreground placeholder:text-muted-foreground"
              />
            </div>
            <div>
              <label className="block text-xs font-600 text-foreground mb-1.5">M-Pesa Amount (KES)</label>
              <input
                type="number"
                value={splitMpesa}
                onChange={(e) => setSplitMpesa(e.target.value)}
                placeholder="0"
                className="w-full h-9 px-3 text-sm bg-card border border-border rounded-lg outline-none focus:border-primary text-foreground placeholder:text-muted-foreground"
              />
            </div>
            {(parseFloat(splitCash) || 0) + (parseFloat(splitMpesa) || 0) > 0 && (
              <div className="flex items-center justify-between text-xs">
                <span className="text-muted-foreground">Allocated</span>
                <span className={`font-700 font-tabular ${
                  (parseFloat(splitCash) || 0) + (parseFloat(splitMpesa) || 0) >= grandTotal
                    ? 'text-success' :'text-danger'
                }`}>
                  KES {((parseFloat(splitCash) || 0) + (parseFloat(splitMpesa) || 0)).toLocaleString()} / {grandTotal.toLocaleString()}
                </span>
              </div>
            )}
          </div>
        )}

        {/* Numpad — only for cash */}
        {method === 'cash' && (
          <div>
            <div className="grid grid-cols-3 gap-1.5">
              {numpadKeys.map((key) => (
                <button
                  key={`numpad-${key}`}
                  onClick={() => handleNumpad(key)}
                  className={`h-10 rounded-lg text-sm font-700 transition-all duration-100 active:scale-95 ${
                    key === '⌫' ?'bg-danger/10 text-danger hover:bg-danger/20'
                      : key === 'C' ?'bg-warning/10 text-warning hover:bg-warning/20' :'bg-muted hover:bg-border text-foreground'
                  }`}
                >
                  {key}
                </button>
              ))}
              <button
                onClick={() => handleNumpad('C')}
                className="col-span-3 h-10 rounded-lg text-sm font-700 bg-warning/10 text-warning hover:bg-warning/20 transition-colors active:scale-95"
              >
                Clear
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Process Payment button */}
      <div className="px-4 py-4 border-t border-border flex-shrink-0 space-y-2">
        <button
          onClick={processPayment}
          disabled={processing || cartEmpty}
          className={`w-full h-12 rounded-xl text-sm font-700 flex items-center justify-center gap-2 transition-all duration-150 ${
            cartEmpty
              ? 'bg-muted text-muted-foreground cursor-not-allowed'
              : processing
              ? 'bg-primary/70 text-white cursor-not-allowed' :'btn-primary text-white'
          }`}
        >
          {processing ? (
            <>
              <Loader2 size={16} className="animate-spin" />
              Processing…
            </>
          ) : (
            <>
              <CheckCircle2 size={16} />
              Process Payment · KES {grandTotal > 0 ? grandTotal.toLocaleString() : '0'}
            </>
          )}
        </button>
      </div>

      {/* M-Pesa modal */}
      <MpesaModal
        open={mpesaOpen}
        onClose={() => setMpesaOpen(false)}
        amount={grandTotal}
        phone={customer?.phone ?? ''}
        onSuccess={() => {
          setMpesaOpen(false);
          const ref = `S-${20848 + Math.floor(Math.random() * 10)}`;
          setReceiptNo(ref);
          setCompleted(true);
          toast.success(`M-Pesa payment confirmed — ${ref}`);
        }}
      />
    </div>
  );
}