'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { CreditCard, Banknote, Truck, MessageCircle, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { useCart } from '@/components/CartProvider';
import { formatPrice } from '@/lib/utils';
import { submitOrder } from '@/app/checkout/actions';

const paymentOptions = [
  { id: 'mpesa', label: 'M-Pesa', icon: CreditCard },
  { id: 'bank', label: 'Bank Transfer', icon: Banknote },
  { id: 'cod', label: 'Cash on Delivery', icon: Truck },
  { id: 'whatsapp', label: 'Order via WhatsApp', icon: MessageCircle },
];

export default function CheckoutPage() {
  const { items, total, clearCart } = useCart();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState('mpesa');

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (items.length === 0) {
      toast.error('Your cart is empty');
      return;
    }

    setLoading(true);
    const formData = new FormData(e.currentTarget);
    formData.set('paymentMethod', paymentMethod);
    formData.set('items', JSON.stringify(items));

    try {
      const result = await submitOrder(formData);
      clearCart();

      if (result.paymentMethod === 'whatsapp' && result.whatsapp?.whatsappNumber) {
        const url = `https://wa.me/${result.whatsapp.whatsappNumber.replace(/\D/g, '')}?text=${encodeURIComponent(result.whatsapp.message)}`;
        window.open(url, '_blank');
      }

      if (result.paymentMethod === 'mpesa') {
        toast.message(result.mpesa?.message || 'M-Pesa prompt sent');
      } else {
        toast.success('Order placed successfully. Check your email for confirmation.');
      }

      router.push(`/thank-you?order=${result.orderNumber}`);
    } catch (err: any) {
      toast.error(err.message || 'Order failed. Please try again.');
      setLoading(false);
    }
  }

  if (items.length === 0) {
    return (
      <div className="container mx-auto px-4 py-16 text-center">
        <h1 className="text-2xl font-bold">Your cart is empty</h1>
        <p className="mt-2 text-muted-foreground">
          Add products to your cart before checkout.
        </p>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-10">
      <h1 className="text-2xl font-bold">Checkout</h1>

      <div className="mt-8 grid gap-8 lg:grid-cols-3">
        <form onSubmit={handleSubmit} className="space-y-6 lg:col-span-2">
          <div className="rounded-xl border bg-card p-6">
            <h2 className="text-lg font-semibold">Delivery Information</h2>
            <p className="text-sm text-muted-foreground">
              No account required — just fill in your details.
            </p>

            <div className="mt-4 grid gap-4 md:grid-cols-2">
              <div className="space-y-1">
                <label className="text-sm font-medium">Full name</label>
                <input
                  name="name"
                  required
                  className="w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="John Doe"
                />
              </div>
              <div className="space-y-1">
                <label className="text-sm font-medium">Phone</label>
                <input
                  name="phone"
                  type="tel"
                  required
                  className="w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="07XX XXX XXX"
                />
              </div>
              <div className="space-y-1 md:col-span-2">
                <label className="text-sm font-medium">Email (optional)</label>
                <input
                  name="email"
                  type="email"
                  className="w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="john@example.com"
                />
              </div>
              <div className="space-y-1 md:col-span-2">
                <label className="text-sm font-medium">Delivery address</label>
                <textarea
                  name="address"
                  required
                  rows={3}
                  className="w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="Street, building, town..."
                />
              </div>
              <div className="space-y-1 md:col-span-2">
                <label className="text-sm font-medium">Order notes (optional)</label>
                <textarea
                  name="notes"
                  rows={2}
                  className="w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="Any special instructions"
                />
              </div>
            </div>
          </div>

          <div className="rounded-xl border bg-card p-6">
            <h2 className="text-lg font-semibold">Payment Method</h2>

            <div className="mt-4 grid gap-3 sm:grid-cols-2">
              {paymentOptions.map((opt) => {
                const Icon = opt.icon;
                return (
                  <label
                    key={opt.id}
                    className={`flex cursor-pointer items-center gap-3 rounded-lg border p-4 transition-colors ${
                      paymentMethod === opt.id
                        ? 'border-primary bg-primary/5'
                        : 'hover:bg-muted'
                    }`}
                  >
                    <input
                      type="radio"
                      name="paymentMethod"
                      value={opt.id}
                      checked={paymentMethod === opt.id}
                      onChange={() => setPaymentMethod(opt.id)}
                      className="h-4 w-4"
                    />
                    <Icon className="h-5 w-5 text-muted-foreground" />
                    <span className="font-medium">{opt.label}</span>
                  </label>
                );
              })}
            </div>

            {paymentMethod === 'mpesa' && (
              <div className="mt-4">
                <label className="text-sm font-medium">M-Pesa number</label>
                <input
                  name="mpesaPhone"
                  type="tel"
                  defaultValue={''}
                  className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
                  placeholder="2547XX XXX XXX (defaults to phone)"
                />
                <p className="mt-1 text-xs text-muted-foreground">
                  Leave blank to use the phone number above.
                </p>
              </div>
            )}
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-primary py-3 font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
          >
            {loading ? (
              <span className="inline-flex items-center justify-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" /> Processing...
              </span>
            ) : (
              'Place order'
            )}
          </button>
        </form>

        <div className="rounded-xl border bg-card p-6">
          <h2 className="text-lg font-semibold">Order Summary</h2>
          <div className="mt-4 space-y-4">
            {items.map((item) => (
              <div key={item.productId} className="flex items-center gap-3">
                <div className="relative h-14 w-14 overflow-hidden rounded-md bg-muted">
                  <Image
                    src={item.image}
                    alt={item.name}
                    fill
                    className="object-cover"
                  />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium">{item.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {formatPrice(item.price)} x {item.quantity}
                  </p>
                </div>
                <p className="font-semibold">
                  {formatPrice(item.price * item.quantity)}
                </p>
              </div>
            ))}
          </div>
          <div className="mt-6 border-t pt-4">
            <div className="flex items-center justify-between text-lg font-bold">
              <span>Total</span>
              <span>{formatPrice(total)}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
