"use client";

import { useCartStore } from "@/store/cart";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { ShieldCheck, Truck, CreditCard, ChevronRight } from "lucide-react";
import Link from "next/link";

export default function CheckoutPage() {
  const router = useRouter();
  const { items, getTotalPrice, clearCart } = useCartStore();
  const [isClient, setIsClient] = useState(false);
  const [loading, setLoading] = useState(false);

  // Form State
  const [formData, setFormData] = useState({
    customerName: "",
    customerPhone: "",
    customerEmail: "",
    shippingWilaya: "",
    shippingCommune: "",
    shippingAddress: "",
  });

  useEffect(() => {
    setIsClient(true);
    if (items.length === 0) {
      // If cart is empty, redirect back
      // router.push("/cart"); // disabled for now to avoid hydration flicker
    }
  }, [items]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handlePlaceOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...formData,
          items,
          totalAmount: getTotalPrice(),
        }),
      });

      if (!res.ok) {
        throw new Error("Failed to place order");
      }

      const data = await res.json();
      clearCart();
      router.push(`/checkout/success?id=${data.orderId}`);
    } catch (err) {
      console.error(err);
      alert("Error placing order. Please try again.");
      setLoading(false);
    }
  };

  if (!isClient || items.length === 0) return null;

  return (
    <div className="min-h-screen bg-muted/30 pt-28 pb-24">
      
      {/* Checkout Header (Amazon style) */}
      <div className="bg-white dark:bg-card border-b border-border/50 py-4 mb-8">
        <div className="max-w-5xl mx-auto px-4 flex justify-between items-center">
          <div className="font-black text-2xl tracking-tighter flex items-center text-foreground">
            <span>K </span><span className="mx-2 text-brand-accent">CREATION</span>
          </div>
          <h1 className="text-2xl font-medium hidden md:block">Paiement (<span className="text-brand-accent">{items.length} articles</span>)</h1>
          <ShieldCheck className="w-8 h-8 text-gray-400" />
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          
          {/* Main Checkout Form */}
          <div className="lg:col-span-2 space-y-6">
            
            {/* Step 1: Shipping Address */}
            <div className="bg-card rounded-xl border border-border/50 p-6 shadow-sm">
              <div className="flex items-center gap-3 mb-6">
                <span className="text-xl font-bold flex items-center gap-2 text-black">
                  <span className="bg-brand-accent text-black w-6 h-6 rounded-full flex items-center justify-center text-sm">1</span>
                  Adresse de livraison
                </span>
              </div>
              
              <form id="checkout-form" onSubmit={handlePlaceOrder} className="space-y-4 pl-8">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Nom complet</label>
                    <input type="text" name="customerName" required value={formData.customerName} onChange={handleChange} className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent" />
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Numéro de téléphone</label>
                    <input type="tel" name="customerPhone" required value={formData.customerPhone} onChange={handleChange} className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent" />
                  </div>
                </div>
                
                <div>
                  <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Adresse e-mail (optionnel)</label>
                  <input type="email" name="customerEmail" value={formData.customerEmail} onChange={handleChange} className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent" />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Wilaya</label>
                    <select name="shippingWilaya" required value={formData.shippingWilaya} onChange={handleChange} className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent">
                      <option value="">Sélectionnez la Wilaya</option>
                      <option value="16">16 - Alger</option>
                      <option value="09">09 - Blida</option>
                      <option value="31">31 - Oran</option>
                      <option value="35">35 - Boumerdes</option>
                      <option value="Other">Autre</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Commune</label>
                    <input type="text" name="shippingCommune" required value={formData.shippingCommune} onChange={handleChange} className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent" />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">Adresse complète</label>
                  <input type="text" name="shippingAddress" required value={formData.shippingAddress} onChange={handleChange} placeholder="Nom de rue, bâtiment, entreprise" className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-3 py-2 text-foreground focus:ring-2 focus:ring-brand-accent" />
                </div>
              </form>
            </div>

            {/* Step 2: Payment Method */}
            <div className="bg-card rounded-xl border border-border/50 p-6 shadow-sm">
              <div className="flex items-center gap-3 mb-6">
                <span className="text-xl font-bold flex items-center gap-2 text-black">
                  <span className="bg-brand-accent text-black w-6 h-6 rounded-full flex items-center justify-center text-sm">2</span>
                  Mode de paiement
                </span>
              </div>
              
              <div className="pl-8">
                <div className="border border-brand-accent bg-brand-accent/5 rounded-md p-4 flex items-start gap-3">
                  <input type="radio" checked readOnly className="mt-1 w-4 h-4 text-brand-accent" />
                  <div>
                    <h4 className="font-bold text-foreground">Paiement à la livraison (COD)</h4>
                    <p className="text-sm text-gray-500">Payez en toute sécurité en espèces à la livraison de votre commande.</p>
                  </div>
                </div>
                <div className="border border-border/50 rounded-md p-4 flex items-start gap-3 mt-3 opacity-50 cursor-not-allowed">
                  <input type="radio" disabled className="mt-1 w-4 h-4" />
                  <div>
                    <h4 className="font-bold text-foreground flex items-center gap-2">Carte de crédit <CreditCard className="w-4 h-4" /></h4>
                    <p className="text-sm text-gray-500">Bientôt disponible.</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Step 3: Review Items */}
            <div className="bg-card rounded-xl border border-border/50 p-6 shadow-sm">
              <div className="flex items-center gap-3 mb-6">
                <span className="text-xl font-bold flex items-center gap-2 text-black">
                  <span className="bg-brand-accent text-black w-6 h-6 rounded-full flex items-center justify-center text-sm">3</span>
                  Vérification des articles
                </span>
              </div>
              
              <div className="pl-8 space-y-4">
                {items.map(item => (
                  <div key={item.id} className="flex gap-4 border border-border/50 p-4 rounded-md">
                    <img src={item.image} className="w-20 h-20 object-contain bg-white rounded-md p-1" />
                    <div>
                      <h4 className="font-bold text-foreground">{item.name}</h4>
                      <p className="text-brand-accent font-bold">{item.price.toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2})} DZD</p>
                      <p className="text-sm text-gray-500">Qté: {item.quantity}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

          </div>

          {/* Place Order Sidebar */}
          <div className="lg:col-span-1">
            <div className="bg-card rounded-xl border border-border/50 p-6 shadow-sm sticky top-32">
              <button 
                type="submit"
                form="checkout-form"
                disabled={loading}
                className="w-full bg-brand-accent hover:bg-red-700 text-white py-3.5 rounded-md font-bold text-base flex justify-center items-center gap-2 transition-colors shadow-sm mb-4 disabled:opacity-50"
              >
                {loading ? "Traitement..." : "Confirmer la commande"}
              </button>
              
              <p className="text-xs text-gray-500 text-center mb-6 border-b border-border/50 pb-6">
                En passant votre commande, vous acceptez les conditions d'utilisation et la politique de confidentialité de K-Creation.
              </p>

              <h3 className="text-lg font-bold mb-4 text-black">Résumé de la commande</h3>
              
              <div className="space-y-2 mb-4 text-sm">
                <div className="flex justify-between text-black">
                  <span className="text-black">Articles:</span>
                  <span className="text-black">{getTotalPrice().toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2})} DZD</span>
                </div>
                <div className="flex justify-between text-black">
                  <span className="text-black">Livraison:</span>
                  <span className="text-black">0,00 DZD</span>
                </div>
              </div>

              <div className="border-t border-border/50 pt-4 mb-4">
                <div className="flex justify-between items-center text-xl text-brand-black">
                  <span className="font-bold text-brand-accent">Total:</span>
                  <span className="font-black text-brand-accent">{getTotalPrice().toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2})} DZD</span>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
