"use client"

import { useEffect, useState } from "react"
import { useForm } from "react-hook-form"
import { Plus, Trash2, Tag, Loader2, Pencil, X, Check } from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

type Brand = { id: string; name: string; slug: string; image?: string }
type FormValues = { name: string; slug: string; image: string }

function slugify(s: string) {
  return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")
}

export default function BrandsPage() {
  const [brands, setBrands] = useState<Brand[]>([])
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [editingBrand, setEditingBrand] = useState<Brand | null>(null)
  const [editSubmitting, setEditSubmitting] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const { register, handleSubmit, reset, setValue } = useForm<FormValues>()
  const editForm = useForm<FormValues>()

  async function fetchBrands() {
    try { setLoading(true); const res = await api.get("/admin/brands"); setBrands(res.data) }
    catch (e) { console.log(e) } finally { setLoading(false) }
  }

  async function onSubmit(data: FormValues) {
    try { setSubmitting(true); await api.post("/admin/brands", data); reset(); fetchBrands() }
    catch (e: any) { Swal.fire({ text: e.response?.data?.message || "Failed to create brand.", confirmButtonColor: "#18181b", icon: "error" }) }
    finally { setSubmitting(false) }
  }

  async function onEditSubmit(data: FormValues) {
    if (!editingBrand) return
    try { setEditSubmitting(true); await api.patch(`/admin/brands/${editingBrand.id}`, data); setEditingBrand(null); fetchBrands() }
    catch (e: any) { Swal.fire({ text: e.response?.data?.message || "Failed to update brand.", confirmButtonColor: "#18181b", icon: "error" }) }
    finally { setEditSubmitting(false) }
  }

  function openEdit(b: Brand) { setEditingBrand(b); editForm.reset({ name: b.name, slug: b.slug, image: b.image || "" }) }

  async function handleDelete(id: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Delete this brand?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try { setDeletingId(id); await api.delete(`/admin/brands/${id}`); fetchBrands() }
    catch (e: any) { Swal.fire({ text: e.response?.data?.message || "Failed to delete brand.", confirmButtonColor: "#18181b", icon: "error" }) }
    finally { setDeletingId(null) }
  }

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

  return (
    <>
      {editingBrand && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm px-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 relative">
            <button onClick={() => setEditingBrand(null)} className="absolute top-4 right-4 p-1.5 rounded-lg text-zinc-400 hover:text-zinc-700 hover:bg-zinc-100 transition cursor-pointer"><X size={18} /></button>
            <div className="flex items-center gap-2.5 mb-5">
              <div className="p-2 bg-indigo-50 rounded-xl"><Pencil className="w-4 h-4 text-indigo-600" /></div>
              <div><h2 className="text-base font-bold text-zinc-900">Edit Brand</h2><p className="text-xs text-zinc-400">Update brand details</p></div>
            </div>
            <form onSubmit={editForm.handleSubmit(onEditSubmit)} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Brand Name</label>
                <input {...editForm.register("name", { required: true, onChange: (e) => editForm.setValue("slug", slugify(e.target.value)) })} placeholder="e.g. Nike" className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-zinc-50" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Slug</label>
                <input {...editForm.register("slug", { required: true })} className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-zinc-50 font-mono text-zinc-500" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Logo URL</label>
                <input {...editForm.register("image")} placeholder="https://..." className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-zinc-50" />
              </div>
              <div className="flex gap-3 pt-1">
                <button type="button" onClick={() => setEditingBrand(null)} className="flex-1 py-2.5 rounded-xl border border-zinc-200 text-sm font-medium text-zinc-600 hover:bg-zinc-50 transition cursor-pointer">Cancel</button>
                <button type="submit" disabled={editSubmitting} className="flex-1 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-semibold hover:bg-indigo-700 transition flex items-center justify-center gap-2 disabled:opacity-50 cursor-pointer">
                  {editSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />} Save Changes
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <div className="space-y-6 max-w-7xl mx-auto p-2">
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-zinc-900 text-white rounded-xl shadow-lg"><Tag size={20} /></div>
          <div>
            <h1 className="text-2xl font-extrabold tracking-tight text-zinc-900">Brands</h1>
            <p className="text-zinc-400 text-xs mt-0.5">Manage fashion brands, vendors, and labels</p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
          <div className="lg:col-span-1 bg-white rounded-2xl border border-zinc-100 p-5 shadow-sm sticky top-6">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-1.5 bg-zinc-100 rounded-lg"><Plus className="w-4 h-4 text-zinc-700" /></div>
              <h2 className="text-sm font-bold text-zinc-900">Add Brand</h2>
            </div>
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Name</label>
                <input {...register("name", { required: true, onChange: (e) => setValue("slug", slugify(e.target.value)) })} placeholder="e.g. Nike, Zara" className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-900 bg-zinc-50" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Slug</label>
                <input {...register("slug", { required: true })} placeholder="auto-generated" className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-900 bg-zinc-50 font-mono text-zinc-500" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-1.5">Logo URL</label>
                <input {...register("image")} placeholder="https://..." className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-900 bg-zinc-50" />
              </div>
              <button type="submit" disabled={submitting} className="w-full bg-zinc-900 text-white text-sm font-semibold py-2.5 rounded-xl hover:bg-zinc-700 transition flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50">
                {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                {submitting ? "Creating..." : "Create Brand"}
              </button>
            </form>
          </div>

          <div className="lg:col-span-2">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-16 bg-white rounded-2xl border border-zinc-100">
                <Loader2 className="w-7 h-7 animate-spin text-zinc-400 mb-3" />
                <span className="text-zinc-400 text-sm">Loading brands...</span>
              </div>
            ) : brands.length === 0 ? (
              <div className="text-center py-16 bg-white rounded-2xl border border-zinc-100 flex flex-col items-center">
                <Tag className="text-zinc-200 w-12 h-12 mb-3" />
                <h3 className="text-sm font-bold text-zinc-700">No brands yet</h3>
                <p className="text-zinc-400 mt-1 text-xs">Create your first brand using the form.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {brands.map((brand) => (
                  <div key={brand.id} className="group bg-white rounded-xl border border-zinc-100 hover:border-zinc-200 shadow-sm hover:shadow-md transition-all duration-200 flex items-center gap-3 p-3 pr-4">
                    <div className="w-11 h-11 rounded-lg bg-zinc-100 overflow-hidden shrink-0 flex items-center justify-center">
                      {brand.image ? <img src={brand.image} alt={brand.name} className="w-full h-full object-cover" /> : <span className="text-sm font-extrabold text-zinc-700">{brand.name.substring(0,2).toUpperCase()}</span>}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-semibold text-zinc-900 truncate group-hover:text-indigo-600 transition">{brand.name}</p>
                      <p className="text-xs font-mono text-zinc-400 truncate">/{brand.slug}</p>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      <button onClick={() => openEdit(brand)} className="p-1.5 rounded-lg text-zinc-400 hover:text-indigo-600 hover:bg-indigo-50 transition cursor-pointer"><Pencil size={14} /></button>
                      <button onClick={() => handleDelete(brand.id)} disabled={deletingId === brand.id} className="p-1.5 rounded-lg text-zinc-400 hover:text-red-500 hover:bg-red-50 transition cursor-pointer disabled:opacity-40">
                        {deletingId === brand.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  )
}
