"use client"

import { useState, useEffect } from "react"
import {
  Truck,
  Search,
  Plus,
  Trash2,
  Edit2,
  Loader2,
  Save,
  X,
  Mail,
  Phone,
  MapPin
} from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

export default function SuppliersPage() {
  const [suppliers, setSuppliers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState("")

  // Form State for Create / Edit
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)
  
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    address: ""
  })

  async function fetchSuppliers() {
    try {
      setLoading(true)
      const res = await api.get("/admin/suppliers")
      setSuppliers(res.data)
    } catch (error) {
      console.error("Failed to load suppliers", error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchSuppliers()
  }, [])

  const filteredSuppliers = suppliers.filter(s => 
    s.name.toLowerCase().includes(search.toLowerCase()) ||
    (s.email && s.email.toLowerCase().includes(search.toLowerCase())) ||
    (s.phone && s.phone.toLowerCase().includes(search.toLowerCase()))
  )

  function openCreateModal() {
    setEditingId(null)
    setFormData({ name: "", email: "", phone: "", address: "" })
    setIsModalOpen(true)
  }

  function openEditModal(supplier: any) {
    setEditingId(supplier.id)
    setFormData({
      name: supplier.name || "",
      email: supplier.email || "",
      phone: supplier.phone || "",
      address: supplier.address || ""
    })
    setIsModalOpen(true)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!formData.name) {
      Swal.fire({ text: "Supplier name is required", confirmButtonColor: "#18181b" })
      return
    }

    try {
      setSubmitting(true)
      if (editingId) {
        await api.put(`/admin/suppliers/${editingId}`, formData)
      } else {
        await api.post("/admin/suppliers", formData)
      }
      setIsModalOpen(false)
      await fetchSuppliers()
    } catch (error) {
      console.error("Failed to save supplier", error)
      Swal.fire({ text: "An error occurred while saving the supplier.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSubmitting(false)
    }
  }

  async function handleDelete(id: string, name: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: `Are you sure you want to delete supplier "${name}"? This action cannot be undone.`, icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try {
      await api.delete(`/admin/suppliers/${id}`)
      await fetchSuppliers()
    } catch (error) {
      console.error("Failed to delete supplier", error)
      Swal.fire({ text: "Failed to delete supplier.", confirmButtonColor: "#18181b", icon: "error" })
    }
  }

  return (
    <div className="space-y-8 max-w-7xl mx-auto p-2 relative">
      {/* HEADER */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <div className="p-3 bg-zinc-950 text-white rounded-2xl shadow-xl">
              <Truck size={24} />
            </div>
            <h1 className="text-3xl md:text-4xl font-black tracking-tight text-zinc-900">
              Suppliers Directory
            </h1>
          </div>
          <p className="text-zinc-500 mt-2 text-sm max-w-md font-medium">
            Manage your vendor network, contact details, and procurement partners.
          </p>
        </div>

        <button
          onClick={openCreateModal}
          className="flex items-center gap-2 px-6 py-3.5 bg-zinc-950 hover:bg-zinc-800 text-white font-black rounded-2xl transition-all cursor-pointer shadow-lg text-xs uppercase tracking-widest shrink-0 hover:-translate-y-0.5"
        >
          <Plus className="w-4 h-4" />
          Add Supplier
        </button>
      </div>

      {/* SEARCH */}
      <div className="bg-white rounded-3xl border border-zinc-200 p-2 shadow-sm overflow-hidden">
        <div className="p-4 border-b border-zinc-100 bg-zinc-50/50 rounded-t-3xl">
          <div className="relative max-w-md">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 w-4 h-4" />
            <input
              type="text"
              placeholder="Search by name, email, or phone..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full border border-zinc-200 rounded-xl pl-11 pr-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:border-transparent transition bg-white text-sm shadow-sm"
            />
          </div>
        </div>

        {/* LIST */}
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-white border-b border-zinc-100 text-[10px] font-black uppercase tracking-widest text-zinc-400">
                <th className="py-4 px-6">Supplier Details</th>
                <th className="py-4 px-6">Contact Info</th>
                <th className="py-4 px-6">Address</th>
                <th className="py-4 px-6 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {loading ? (
                <tr>
                  <td colSpan={4} className="py-20 text-center">
                    <Loader2 className="w-8 h-8 animate-spin text-zinc-300 mx-auto mb-3" />
                    <p className="text-xs font-bold uppercase tracking-widest text-zinc-400">Loading Suppliers...</p>
                  </td>
                </tr>
              ) : filteredSuppliers.length === 0 ? (
                <tr>
                  <td colSpan={4} className="py-20 text-center">
                    <Truck className="w-8 h-8 text-zinc-200 mx-auto mb-3" />
                    <p className="text-xs font-bold uppercase tracking-widest text-zinc-400">No Suppliers Found</p>
                  </td>
                </tr>
              ) : (
                filteredSuppliers.map(supplier => (
                  <tr key={supplier.id} className="hover:bg-zinc-50/50 transition">
                    <td className="py-4 px-6">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center font-black text-sm shrink-0">
                          {supplier.name.charAt(0).toUpperCase()}
                        </div>
                        <div>
                          <p className="font-bold text-sm text-zinc-900">{supplier.name}</p>
                          <p className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">ID: {supplier.id.slice(-6)}</p>
                        </div>
                      </div>
                    </td>

                    <td className="py-4 px-6">
                      <div className="space-y-1.5">
                        <div className="flex items-center gap-2 text-xs text-zinc-600">
                          <Mail className="w-3.5 h-3.5 text-zinc-400" />
                          {supplier.email || <span className="text-zinc-300 italic">Not provided</span>}
                        </div>
                        <div className="flex items-center gap-2 text-xs text-zinc-600">
                          <Phone className="w-3.5 h-3.5 text-zinc-400" />
                          {supplier.phone || <span className="text-zinc-300 italic">Not provided</span>}
                        </div>
                      </div>
                    </td>

                    <td className="py-4 px-6">
                      <div className="flex gap-2 text-xs text-zinc-600">
                        <MapPin className="w-3.5 h-3.5 text-zinc-400 shrink-0 mt-0.5" />
                        <span className="max-w-[200px] truncate">{supplier.address || <span className="text-zinc-300 italic">Not provided</span>}</span>
                      </div>
                    </td>

                    <td className="py-4 px-6 text-right">
                      <div className="flex justify-end gap-2">
                        <button
                          onClick={() => openEditModal(supplier)}
                          className="w-8 h-8 rounded-lg bg-zinc-50 hover:bg-zinc-100 text-zinc-500 hover:text-zinc-900 flex items-center justify-center transition border border-zinc-200"
                          title="Edit Supplier"
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </button>
                        <button
                          onClick={() => handleDelete(supplier.id, supplier.name)}
                          className="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-500 hover:text-rose-600 flex items-center justify-center transition border border-rose-200"
                          title="Delete Supplier"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* MODAL */}
      {isModalOpen && (
        <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">
                {editingId ? "Edit Supplier" : "Add New Supplier"}
              </h2>
              <button
                onClick={() => setIsModalOpen(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={handleSubmit} 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={formData.name}
                  onChange={(e) => setFormData({ ...formData, 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={formData.email}
                    onChange={(e) => setFormData({ ...formData, 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={formData.phone}
                    onChange={(e) => setFormData({ ...formData, 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={formData.address}
                  onChange={(e) => setFormData({ ...formData, 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={() => setIsModalOpen(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={submitting}
                  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"
                >
                  {submitting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  {editingId ? "Save Changes" : "Add Supplier"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
