import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import IconCaretLeft from "../components/Icon/IconCaretLeft";
import IconCaretRight from "../components/Icon/IconCaretRight";
import IconStarShine from "../components/Icon/IconStarShine";
import IconTruck from "../components/Icon/IconTruck";
import IconLock from "../components/Icon/IconLock";
import Select from "react-select";
import IconWhatsapp from "../components/Icon/IconWhatsapp";
import IconInstagram from "../components/Icon/IconInstagram";
import Swal from 'sweetalert2';
import { productApi } from "../api/productApi";
import { orderApi } from "../api/orderApi";

type Channel = "whatsapp" | "instagram";
type ProductOption = {
  value: string | number;
  label: string;
  productData: any;
};

/* ── Icons ──────────────────────────────────────────────── */
const IcoWhatsApp = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719" />
  </svg>
);
const IcoInstagram = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect width="20" height="20" x="2" y="2" rx="5" ry="5" />
    <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
    <line x1="17.5" x2="17.51" y1="6.5" y2="6.5" />
  </svg>
);


/* ── Page ────────────────────────────────────────────────── */
const CustomerRegisterPortal = () => {
  const navigate = useNavigate();
  const [channel, setChannel] = useState<Channel>("whatsapp");
  
  const [products, setProducts] = useState<any[]>([]);
  const [productOptions, setProductOptions] = useState<ProductOption[]>([]);
  const [selectedProduct, setSelectedProduct] = useState<ProductOption | null>(null);
  const [selectedVariant, setSelectedVariant] = useState<any | null>(null);
  
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [address, setAddress] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [showProductModal, setShowProductModal] = useState(false);

  useEffect(() => {
    const fetchProducts = async () => {
        try {
            const res = await productApi.getAllProducts();
            if (res.success) {
                setProducts(res.data);
                const options = res.data.map((p: any) => ({
                    value: p.id,
                    label: `${p.name} (₹${Number(p.price || 0).toLocaleString("en-IN")})`,
                    productData: p
                }));
                setProductOptions(options);
                if (options.length > 0) {
                    setSelectedProduct(options[0]);
                    if (options[0].productData?.variants?.length > 0) {
                        setSelectedVariant(options[0].productData.variants[0]);
                    } else {
                        setSelectedVariant(null);
                    }
                }
            }
        } catch (error) {
            console.error("Failed to load products", error);
        }
    };
    fetchProducts();
  }, []);

  const handleProductChange = (option: any) => {
    setSelectedProduct(option);
    if (option?.productData?.variants?.length > 0) {
        setSelectedVariant(option.productData.variants[0]);
    } else {
        setSelectedVariant(null);
    }
  };

  const channelOptions: { key: Channel; label: string; icon: JSX.Element; activeColor: string; hoverBorder: string; hoverBg: string }[] = [
    { key: "whatsapp", label: "WhatsApp", icon: <IconWhatsapp />, activeColor: "text-emerald-600", hoverBorder: "hover:border-emerald-500", hoverBg: "hover:bg-emerald-50/20" },
    { key: "instagram", label: "Instagram", icon: <IconInstagram />, activeColor: "text-pink-600", hoverBorder: "hover:border-pink-500", hoverBg: "hover:bg-pink-50/20" },
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedProduct) {
        Swal.fire({ icon: 'error', title: 'Product required', toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
        return;
    }

    setIsSubmitting(true);
    
    // Use variant price/woo_id if applicable
    const price = selectedVariant ? (selectedVariant.price || selectedProduct.productData.price) : selectedProduct.productData.price;
    const wooId = selectedVariant ? selectedVariant.woo_id : selectedProduct.productData.woo_id;
    
    try {
        await orderApi.createOrder({
            channel,
            product_id: selectedProduct.productData.id,
            product_woo_id: wooId,
            customer_name: name,
            customer_phone: phone,
            customer_email: email,
            shipping_address: address,
            qty: 1, // Default qty to 1 for registration
            amount: price || 0
        });
        
        setSubmitted(true);
        Swal.fire({ icon: 'success', title: 'Reservation Submitted!', toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
        
        // Reset form
        setName("");
        setPhone("");
        setEmail("");
        setAddress("");
        setTimeout(() => setSubmitted(false), 3000);
        
    } catch (err) {
        console.error("Order failed", err);
        Swal.fire({ icon: 'error', title: 'Failed to submit', text: 'Please try again.', toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
    } finally {
        setIsSubmitting(false);
    }
  };

  const selectedProductData = selectedProduct?.productData;
  const isOutOfStock = selectedVariant 
      ? Number(selectedVariant.balance_qty || 0) <= 0 
      : Number(selectedProductData?.balance_qty || 0) <= 0;

  return (
    <div className="min-h-screen flex flex-col font-sans select-none bg-slate-100 text-slate-800">

      {/* ── Main content ── */}
      <div className="flex-1 flex items-center justify-center p-4 py-8">
        <div className="bg-white rounded-3xl w-full max-w-4xl overflow-hidden border border-slate-200 shadow-2xl flex flex-col md:grid md:grid-cols-12 relative">

          {/* ══ LEFT PANEL ══ */}
          <div
            className="md:col-span-5 text-amber-50 p-8 flex flex-col justify-between relative overflow-hidden text-left"
            style={{ background: "linear-gradient(135deg, #400000 0%, #800000 50%, #2b0000 100%)" }}
          >
            {/* radial glow overlay */}
            <div className="absolute inset-0 pointer-events-none"
              style={{ background: "radial-gradient(circle at top right, rgba(245,158,11,0.15), transparent 60%)" }} />

            <div className="space-y-6 relative z-10">
              {/* Est badge + vault label */}
              <div className="flex items-center gap-2">
                <span className="px-2 py-0.5 rounded-full bg-black/45 border border-amber-500/30 text-[9px] uppercase font-black tracking-widest text-amber-300">
                  Est. 1994
                </span>
                <span className="text-[10px] uppercase font-bold text-amber-400 tracking-wider">Exclusive Vault</span>
              </div>

              {/* Brand */}
              <div className="space-y-1">
                <h1 className="font-serif font-black text-2xl tracking-tight text-amber-400 leading-none">SHAS TRADITIONAL</h1>
                <p className="text-amber-100/70 text-xs uppercase tracking-widest leading-none font-bold">Goldsmiths &amp; Diamantaires</p>
              </div>

              {/* Description */}
              <div className="pt-6 border-t border-white/10 space-y-3">
                <h3 className="font-medium text-sm text-white">Private Patron Reservation</h3>
                <p className="text-slate-300 text-[11px] leading-relaxed opacity-90">
                  Welcome to our luxury client reservation portal. Due to high demand and strictly controlled limited stock lines,
                  we invite prospective buyers to independently register shipping details and item interest.
                </p>
              </div>

              {/* Feature bullets */}
              <div className="space-y-3.5 pt-4">
                {[
                  { icon: <IconStarShine />, title: "Live Stock Allotments", desc: "Your choices secure a temporary hold upon verified checkout review." },
                  { icon: <IconTruck />, title: "Priority Insured Dispatch", desc: "Priority delivery includes certified gemstone documentation." },
                ].map((f) => (
                  <div key={f.title} className="flex items-start gap-2.5">
                    <span className="p-1.5 rounded-lg bg-black/30 text-amber-400 shrink-0 mt-0.5">{f.icon}</span>
                    <div>
                      <h4 className="text-[11px] font-bold text-white">{f.title}</h4>
                      <p className="text-[10px] text-slate-300 leading-normal">{f.desc}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Bottom encryption note */}
            <div className="pt-8 md:pt-0 relative z-10">
              <p className="text-[9.5px] text-slate-400 font-mono flex items-center gap-1"><IconLock className="text-warning" /> Encrypted Shas Security Protocols</p>
            </div>
          </div>

          {/* ══ RIGHT FORM ══ */}
          <form
            onSubmit={handleSubmit}
            className="md:col-span-7 p-6 md:p-8 flex flex-col justify-between gap-5 bg-slate-50 text-left"
          >
            {/* Form heading */}
            <div>
              <h2 className="font-black text-sm text-slate-800 uppercase tracking-wider">Patron Registration Form</h2>
              <p className="text-[10px] text-slate-400 mt-0.5">Input your verified details to join our private waiting list.</p>
            </div>

            {/* Channel selector */}
            <div className="space-y-1.5">
              <label className="text-[10px] uppercase font-black text-slate-400 tracking-wider block">
                Communication feedback channel
              </label>
              <div className="grid grid-cols-2 gap-2.5">
                {channelOptions.map((c) => {
                  const isActive = channel === c.key;
                  return (
                    <button
                      key={c.key}
                      type="button"
                      onClick={() => setChannel(c.key)}
                      className={[
                        "p-2 rounded-xl border flex flex-col items-center justify-center gap-1 transition-all text-center cursor-pointer select-none",
                        c.activeColor,
                        c.hoverBorder,
                        c.hoverBg,
                        isActive
                          ? "ring-2 ring-[#800000] bg-[#800000]/5 border-[#800000]/30 font-bold"
                          : "bg-white opacity-70",
                      ].join(" ")}
                    >
                      {c.icon}
                      <span className="text-[10px] font-bold">{c.label}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Name / Phone / Email */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {/* Full name — full width */}
              <div className="space-y-1 sm:col-span-2">
                <label className="text-[9.5px] uppercase font-extrabold text-slate-500 tracking-wider block">Full Name *</label>
                <input
                  required
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Enter your first and last name"
                  className="w-full text-xs p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:ring-[1.5px] focus:ring-[#800000]"
                />
              </div>
              <div className="space-y-1">
                <label className="text-[9.5px] uppercase font-extrabold text-slate-500 tracking-wider block">Phone Number</label>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+91 XXXXX XXXXX"
                  className="w-full text-xs p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:ring-[1.5px] focus:ring-[#800000]"
                />
              </div>
              <div className="space-y-1">
                <label className="text-[9.5px] uppercase font-extrabold text-slate-500 tracking-wider block">Email Address</label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="patron@example.com"
                  className="w-full text-xs p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:ring-[1.5px] focus:ring-[#800000]"
                />
              </div>
            </div>

            {/* Product selector */}
            <div className="space-y-2">
              <label className="text-[9.5px] uppercase font-extrabold text-slate-500 tracking-wider block">
                Select Requested Jewellery Masterpiece
              </label>
              <div className="grid grid-cols-1 sm:grid-cols-12 gap-3">
                {/* Dropdowns */}
                <div className="sm:col-span-8 flex flex-col gap-2">
                  <Select
                    value={selectedProduct}
                    onChange={handleProductChange}
                    options={productOptions}
                    className="text-xs font-bold"
                    classNamePrefix="react-select"
                    isSearchable
                    placeholder="Search product..."
                  />
                  
                  {selectedProductData?.variants && selectedProductData.variants.length > 0 && (
                    <Select
                        value={selectedVariant ? { value: selectedVariant.id, label: `${selectedVariant.color} (₹${Number(selectedVariant.price || selectedProductData.price).toLocaleString("en-IN")})` } : null}
                        onChange={(opt: any) => {
                            const v = selectedProductData.variants.find((v: any) => v.id === opt?.value);
                            setSelectedVariant(v);
                        }}
                        options={selectedProductData.variants.map((v: any) => ({
                            value: v.id,
                            label: `${v.color} (₹${Number(v.price || selectedProductData.price).toLocaleString("en-IN")})`
                        }))}
                        className="text-xs font-bold"
                        classNamePrefix="react-select"
                        placeholder="Select Variation (e.g. Color/Size)"
                    />
                  )}
                </div>
                {/* Preview chip */}
                {selectedProductData && (
                    <div 
                      className="sm:col-span-4 flex items-center gap-2 bg-slate-100 p-2 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-200 transition-colors"
                      onClick={() => setShowProductModal(true)}
                    >
                      { (selectedVariant?.image_url || selectedProductData.image_url) ? (
                        <img 
                          src={selectedVariant?.image_url || selectedProductData.image_url} 
                          alt="Product" 
                          className="w-10 h-10 object-cover rounded-lg" 
                        />
                      ) : (
                        <div className="w-10 h-10 bg-slate-300 rounded-lg flex items-center justify-center flex-shrink-0">
                          <IconStarShine />
                        </div>
                      )}
                      <div className="min-w-0 flex-1 leading-none text-left h-full flex flex-col justify-center">
                        <p className="text-[9px] text-slate-400 font-bold truncate mb-0.5">SKU: {selectedVariant ? selectedVariant.sku : selectedProductData.sku}</p>
                        <p className="text-[10px] font-extrabold text-slate-800 truncate line-clamp-2" title={selectedProductData.name}>{selectedProductData.name}</p>
                      </div>
                    </div>
                )}
              </div>
            </div>

            {/* Address */}
            <div className="space-y-1">
              <label className="text-[9.5px] uppercase font-extrabold text-slate-500 tracking-wider block">
                Shipping Coordinates / Address
              </label>
              <textarea
                rows={2}
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                placeholder="Enter full physical address for insured delivery shipment"
                className="w-full text-xs p-2.5 bg-white border border-slate-200 rounded-xl outline-none max-h-24 resize-none focus:ring-[1.5px] focus:ring-[#800000]"
              />
            </div>

            {/* Actions */}
            <div className="flex gap-3 justify-end items-center pt-2">
              <button
                type="submit"
                disabled={isSubmitting || isOutOfStock}
                className={`px-6 py-2 text-white text-xs font-bold rounded-xl transition-all shadow-md flex items-center gap-1.5 ${isOutOfStock ? 'bg-slate-400 cursor-not-allowed' : 'bg-[#800000] hover:bg-rose-950 cursor-pointer active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed'}`}
              >
                {isOutOfStock ? "Out Of Stock" : (isSubmitting ? "Submitting..." : (submitted ? "Order Created!" : "Create Order"))}
                {!isOutOfStock && !isSubmitting && !submitted && <IconCaretRight />}
              </button>
            </div>
          </form>
          
          {/* ── Product Modal ── */}
          {showProductModal && selectedProductData && (
            <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
              <div className="bg-white rounded-3xl w-full max-w-md overflow-hidden shadow-2xl relative">
                <button 
                  onClick={() => setShowProductModal(false)}
                  className="absolute top-4 right-4 text-slate-400 hover:text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-full p-2 transition-colors z-10"
                >
                  <IconCaretLeft className="rotate-180" />
                </button>
                <div className="p-6 text-center flex flex-col items-center">
                  <div className="w-48 h-48 mb-6 rounded-2xl overflow-hidden bg-slate-100 border border-slate-200">
                    { (selectedVariant?.image_url || selectedProductData.image_url) ? (
                      <img 
                        src={selectedVariant?.image_url || selectedProductData.image_url} 
                        alt="Product" 
                        className="w-full h-full object-cover" 
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-slate-300">
                        <IconStarShine className="w-12 h-12" />
                      </div>
                    )}
                  </div>
                  <h3 className="font-bold text-lg text-slate-800 mb-1">{selectedProductData.name}</h3>
                  <p className="text-sm font-black text-amber-500 mb-4">
                     SKU: {selectedVariant ? selectedVariant.sku : selectedProductData.sku}
                  </p>
                  
                  {selectedVariant && (
                    <div className="bg-slate-50 px-4 py-2 rounded-lg border border-slate-200 mb-4 inline-block">
                        <p className="text-xs font-bold text-slate-600 uppercase">Selected Variation</p>
                        <p className="text-sm font-black text-[#800000]">{selectedVariant.color}</p>
                    </div>
                  )}

                  <div className="flex gap-4 justify-center mt-2 w-full">
                    <div className="text-center flex-1">
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wide">Price</p>
                      <p className="font-black text-slate-800">₹{Number(selectedVariant?.price || selectedProductData.price).toLocaleString("en-IN")}</p>
                    </div>
                    <div className="w-px bg-slate-200"></div>
                    <div className="text-center flex-1">
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wide">Stock</p>
                      <p className="font-bold text-emerald-600">{selectedVariant ? selectedVariant.balance_qty : selectedProductData.balance_qty} Units</p>
                    </div>
                    <div className="w-px bg-slate-200"></div>
                    <div className="text-center flex-1">
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wide">Category</p>
                      <p className="font-bold text-slate-600">{selectedProductData.category || 'N/A'}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
};

export default CustomerRegisterPortal;