"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import {
  ArrowLeft,
  Search,
  Plus,
  Minus,
  Trash2,
  Save,
  Loader2,
  CheckCircle,
  Truck,
  X
} from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

export default function CreatePurchaseOrderPage() {
  const router = useRouter()
  
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  
  const [suppliers, setSuppliers] = useState<any[]>([])
  const [variants, setVariants] = useState<any[]>([])

  // Form State
  const [supplierId, setSupplierId] = useState("")
  const [orderItems, setOrderItems] = useState<any[]>([]) // { variantId, quantity, unitCost, variantInfo }
  
  // Supplier Modal State
  const [isSupplierModalOpen, setIsSupplierModalOpen] = useState(false)
  const [newSupplier, setNewSupplier] = useState({ name: "", email: "", phone: "", address: "" })
  const [creatingSupplier, setCreatingSupplier] = useState(false)
  
  const [searchVariant, setSearchVariant] = useState("")

  useEffect(() => {
    async function fetchData() {
      try {
        const supRes = await api.get("/admin/suppliers")
        setSuppliers(supRes.data)
      } catch (error) {
        console.error("Failed to fetch suppliers", error)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [])

  useEffect(() => {
    const handler = setTimeout(async () => {
      if (searchVariant.trim().length < 2) {
        setVariants([])
        return
      }
      try {
        const res = await api.get(`/admin/products?search=${searchVariant}&limit=20`)
        const productsList = res.data.data || res.data
        const flatVariants: any[] = []
        productsList.forEach((p: any) => {
          if (p.variants) {
            p.variants.forEach((v: any) => {
              flatVariants.push({
                ...v,
                productTitle: p.title,
                productImage: p.thumbnail,
                sku: v.sku || `SKU-${p.id.slice(-4)}-${v.color.slice(0,2)}-${v.size}`
              })
            })
          }
        })
        setVariants(flatVariants)
      } catch(e) {
        console.error("Failed to fetch variants", e)
      }
    }, 400)
    return () => clearTimeout(handler)
  }, [searchVariant])

  // Filter for variant search
  const filteredVariants = variants.filter(v => 
    v.productTitle.toLowerCase().includes(searchVariant.toLowerCase()) || 
    v.sku.toLowerCase().includes(searchVariant.toLowerCase()) ||
    v.color.toLowerCase().includes(searchVariant.toLowerCase())
  ).slice(0, 5) // limit to 5 results to keep UI clean

  function addVariantToOrder(variant: any) {
    // Check if already added
    if (orderItems.some(i => i.variantId === variant.id)) {
      Swal.fire({ text: "This variant is already in the order.", confirmButtonColor: "#18181b" })
      return
    }

    setOrderItems([...orderItems, {
      variantId: variant.id,
      quantity: 1,
      unitCost: variant.price || 0,
      variantInfo: variant
    }])
    setSearchVariant("")
  }

  function updateOrderItem(variantId: string, field: string, value: number) {
    setOrderItems(prev => prev.map(item => 
      item.variantId === variantId ? { ...item, [field]: value } : item
    ))
  }

  function removeOrderItem(variantId: string) {
    setOrderItems(prev => prev.filter(i => i.variantId !== variantId))
  }

  async function handleSubmit() {
    if (!supplierId) {
      Swal.fire({ text: "Please select a supplier.", confirmButtonColor: "#18181b" })
      return
    }

    if (orderItems.length === 0) {
      Swal.fire({ text: "Please add at least one item to the purchase order.", confirmButtonColor: "#18181b" })
      return
    }

    try {
      setSubmitting(true)

      const payload = {
        supplierId: supplierId,
        status: 'ORDERED',
        items: orderItems.map(i => ({
          variantId: i.variantId,
          quantity: i.quantity,
          unitCost: i.unitCost
        })),
        notes: "Created via Admin Portal"
      }

      await api.post("/admin/purchases", payload)
      
      router.push("/admin/purchases")
      router.refresh()
    } catch (error) {
      console.error("Failed to create PO", error)
      Swal.fire({ text: "An error occurred while generating the Purchase Order.", confirmButtonColor: "#18181b", icon: "error" })
      setSubmitting(false)
    }
  }

  async function handleCreateSupplier(e: React.FormEvent) {
    e.preventDefault()
    if (!newSupplier.name) return
    try {
      setCreatingSupplier(true)
      const res = await api.post("/admin/suppliers", newSupplier)
      setSuppliers(prev => [...prev, res.data])
      setSupplierId(res.data.id)
      setIsSupplierModalOpen(false)
      setNewSupplier({ name: "", email: "", phone: "", address: "" })
    } catch (error) {
      console.error(error)
      Swal.fire({ text: "Failed to create supplier", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setCreatingSupplier(false)
    }
  }

  const totalCost = orderItems.reduce((sum, item) => sum + (item.quantity * item.unitCost), 0)
  const totalUnits = orderItems.reduce((sum, item) => sum + item.quantity, 0)

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-32">
        <Loader2 className="w-10 h-10 animate-spin text-indigo-600 mb-4" />
        <p className="text-sm font-bold uppercase tracking-widest text-zinc-400">Loading procurement tools...</p>
      </div>
    )
  }

  return (
    <div className="max-w-7xl mx-auto p-0">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        
        {/* LEFT COLUMN: FORM */}
        <div className="lg:col-span-2 space-y-3">
          
          <div className="bg-white rounded-2xl border border-zinc-200 p-4 shadow-sm space-y-4">
            <div className="space-y-4">
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Select Existing Supplier</label>
                <div className="flex gap-2">
                  <select 
                    value={supplierId}
                    onChange={(e) => setSupplierId(e.target.value)}
                    className="flex-1 border border-zinc-200 rounded-xl px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-xs font-medium bg-zinc-50"
                  >
                    <option value="">-- Choose a supplier --</option>
                    {suppliers.map(s => (
                      <option key={s.id} value={s.id}>{s.name}</option>
                    ))}
                  </select>
                  <button 
                    onClick={() => setIsSupplierModalOpen(true)}
                    className="w-10 h-10 rounded-xl bg-zinc-950 text-white flex items-center justify-center hover:bg-zinc-800 transition shadow-sm shrink-0"
                    title="Add New Supplier"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* ITEM SELECTION */}
          <div className="bg-white rounded-2xl border border-zinc-200 p-4 shadow-sm space-y-4">
            <div className="flex items-center gap-2 text-xs font-black uppercase tracking-widest text-zinc-900 border-b border-zinc-100 pb-3">
              <Plus className="w-4 h-4 text-emerald-500" />
              2. Add Variants to Order
            </div>

            {/* SEARCH */}
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
              <input
                type="text"
                placeholder="Search variants to add..."
                value={searchVariant}
                onChange={(e) => setSearchVariant(e.target.value)}
                className="w-full border border-zinc-200 rounded-xl pl-9 pr-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-xs bg-zinc-50 transition"
              />

              {/* SEARCH RESULTS DROPDOWN */}
              {searchVariant && (
                <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-zinc-200 rounded-2xl shadow-xl z-10 overflow-hidden">
                  {filteredVariants.length === 0 ? (
                    <div className="p-4 text-center text-xs text-zinc-500 font-bold uppercase">No variants found</div>
                  ) : (
                    <div className="divide-y divide-zinc-100">
                      {filteredVariants.map(v => (
                        <div 
                          key={v.id} 
                          onClick={() => addVariantToOrder(v)}
                          className="p-3 hover:bg-zinc-50 flex items-center gap-3 group transition cursor-pointer"
                        >
                          <div className="w-10 h-10 rounded-lg bg-zinc-100 overflow-hidden shrink-0">
                            {v.productImage && <img src={v.productImage} className="w-full h-full object-cover" />}
                          </div>
                          <div>
                            <p className="text-xs font-bold text-zinc-900 group-hover:text-indigo-600 transition">{v.productTitle}</p>
                            <div className="flex items-center gap-2 text-[10px] font-bold text-zinc-500 uppercase mt-0.5">
                              <span>{v.sku}</span> • <span>{v.color} / {v.size}</span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* ORDER ITEMS LIST */}
            {orderItems.length > 0 && (
              <div className="mt-6 border border-zinc-200 rounded-2xl overflow-hidden">
                <table className="w-full text-left">
                  <thead className="bg-zinc-50 border-b border-zinc-200 text-[9px] font-black uppercase tracking-widest text-zinc-500">
                    <tr>
                      <th className="p-4">Variant</th>
                      <th className="p-4">Quantity</th>
                      <th className="p-4">Unit Cost</th>
                      <th className="p-4 text-right">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-zinc-100">
                    {orderItems.map((item, index) => (
                      <tr key={index} className="bg-white">
                        <td className="p-4">
                          <div className="text-xs font-bold text-zinc-900">{item.variantInfo.productTitle}</div>
                          <div className="text-[10px] font-bold text-zinc-500 uppercase mt-0.5">{item.variantInfo.color} / {item.variantInfo.size}</div>
                        </td>
                        <td className="p-4">
                          <input
                            type="number"
                            min="1"
                            value={item.quantity}
                            onChange={(e) => updateOrderItem(item.variantId, 'quantity', Math.max(1, parseInt(e.target.value) || 1))}
                            className="w-16 border border-zinc-200 rounded-lg px-2 py-1 text-xs font-bold bg-zinc-50 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                          />
                        </td>
                        <td className="p-4">
                          <div className="relative">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 text-sm font-bold">$</span>
                            <input
                              type="number"
                              min="0"
                              step="0.01"
                              value={item.unitCost}
                              onChange={(e) => updateOrderItem(item.variantId, 'unitCost', Math.max(0, parseFloat(e.target.value) || 0))}
                              className="w-20 border border-zinc-200 rounded-lg pl-5 pr-2 py-1 text-xs font-bold bg-zinc-50 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                            />
                          </div>
                        </td>
                        <td className="p-4 text-right">
                          <button
                            onClick={() => removeOrderItem(item.variantId)}
                            className="w-8 h-8 inline-flex items-center justify-center rounded-lg hover:bg-rose-50 text-zinc-400 hover:text-rose-500 transition"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* RIGHT COLUMN: SUMMARY */}
        <div className="space-y-6">
          <div className="bg-zinc-950 text-white rounded-2xl p-5 shadow-2xl relative overflow-hidden">
            <div className="absolute top-0 right-0 w-24 h-24 bg-indigo-500/20 rounded-full blur-2xl -mr-8 -mt-8" />
            
            <h3 className="text-[10px] font-black uppercase tracking-widest mb-4 border-b border-zinc-800 pb-3 relative z-10">Order Summary</h3>
            
            <div className="space-y-4 relative z-10">
              <div className="flex justify-between text-sm">
                <span className="text-zinc-400 font-bold">Total Variants</span>
                <span className="font-black">{orderItems.length}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-zinc-400 font-bold">Total Units</span>
                <span className="font-black">{totalUnits}</span>
              </div>
              
              <div className="pt-4 border-t border-zinc-800 flex justify-between">
                <span className="text-[10px] font-black uppercase tracking-widest text-zinc-400 mt-1">Est. Cost</span>
                <span className="text-xl font-black text-white">${totalCost.toFixed(2)}</span>
              </div>
            </div>

            <button
              onClick={handleSubmit}
              disabled={submitting || orderItems.length === 0}
              className="w-full mt-6 bg-gradient-to-r from-violet-500 to-indigo-500 hover:from-violet-400 hover:to-indigo-400 text-white font-black py-3 rounded-xl text-[10px] uppercase tracking-widest shadow-lg shadow-indigo-500/20 transition-all flex items-center justify-center gap-1.5 disabled:opacity-50 disabled:shadow-none"
            >
              {submitting ? (
                <><Loader2 className="w-4 h-4 animate-spin" /> Processing...</>
              ) : (
                <><CheckCircle className="w-4 h-4" /> Finalize Order</>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* ADD SUPPLIER MODAL */}
      {isSupplierModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/60 backdrop-blur-sm">
          <div className="bg-white rounded-3xl w-full max-w-lg shadow-2xl overflow-hidden border border-zinc-200/50">
            <div className="p-6 border-b border-zinc-100 flex items-center justify-between bg-zinc-50/50">
              <h2 className="text-xl font-black text-zinc-900">Add New Supplier</h2>
              <button
                onClick={() => setIsSupplierModalOpen(false)}
                className="w-8 h-8 rounded-full bg-white border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-zinc-900 transition shadow-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleCreateSupplier} className="p-6 space-y-5">
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Company Name *</label>
                <input
                  type="text"
                  required
                  value={newSupplier.name}
                  onChange={(e) => setNewSupplier({ ...newSupplier, name: e.target.value })}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                  placeholder="E.g. Nexus Textiles Ltd."
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Email Address</label>
                  <input
                    type="email"
                    value={newSupplier.email}
                    onChange={(e) => setNewSupplier({ ...newSupplier, email: e.target.value })}
                    className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                    placeholder="contact@nexus.com"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Phone Number</label>
                  <input
                    type="text"
                    value={newSupplier.phone}
                    onChange={(e) => setNewSupplier({ ...newSupplier, phone: e.target.value })}
                    className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                    placeholder="+1 (555) 123-4567"
                  />
                </div>
              </div>

              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Physical Address</label>
                <textarea
                  value={newSupplier.address}
                  onChange={(e) => setNewSupplier({ ...newSupplier, address: e.target.value })}
                  rows={3}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition resize-none"
                  placeholder="123 Industrial Parkway..."
                />
              </div>

              <div className="pt-4 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsSupplierModalOpen(false)}
                  className="px-5 py-2.5 rounded-xl border border-zinc-200 text-zinc-600 font-bold text-xs uppercase tracking-widest hover:bg-zinc-50 transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={creatingSupplier}
                  className="px-6 py-2.5 rounded-xl bg-zinc-950 hover:bg-zinc-800 text-white font-black text-xs uppercase tracking-widest transition shadow-lg flex items-center gap-2 disabled:opacity-50"
                >
                  {creatingSupplier ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  Add Supplier
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  )
}
