"use client"

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

type Color = { id: string; name: string; value: string }
type FormValues = { name: string; value: string }

export default function ColorsPage() {
  const [colors, setColors] = useState<Color[]>([])
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [editingColor, setEditingColor] = useState<Color | null>(null)
  const [editSubmitting, setEditSubmitting] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const { register, handleSubmit, reset, setValue, watch } = useForm<FormValues>({ defaultValues: { value: "#6366f1" } })
  const editForm = useForm<FormValues>()
  const watchedValue = watch("value")
  const watchedEditValue = editForm.watch("value")

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

  async function onSubmit(data: FormValues) {
    try { setSubmitting(true); await api.post("/admin/colors", data); reset({ value: "#6366f1", name: "" }); fetchColors() }
    catch (e: any) { Swal.fire({ text: e.response?.data?.message || "Failed to add color.", confirmButtonColor: "#18181b", icon: "error" }) }
    finally { setSubmitting(false) }
  }

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

  function openEdit(c: Color) { setEditingColor(c); editForm.reset({ name: c.name, value: c.value }) }

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

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

  return (
    <>
      {/* EDIT MODAL */}
      {editingColor && (
        <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={() => setEditingColor(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 Color</h2><p className="text-xs text-zinc-400">Update color name and value</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">Color Name</label>
                <input {...editForm.register("name", { required: true })} placeholder="e.g. Midnight Black" 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">Hex Value</label>
                <div className="flex gap-3 items-center">
                  <div className="w-10 h-10 rounded-lg overflow-hidden border border-zinc-200 shrink-0 cursor-pointer relative">
                    <input type="color" value={watchedEditValue} onChange={(e) => editForm.setValue("value", e.target.value, { shouldValidate: true })} className="absolute inset-0 w-[200%] h-[200%] -translate-x-[25%] -translate-y-[25%] cursor-pointer border-none p-0 outline-none" />
                  </div>
                  <input {...editForm.register("value", { required: true })} className="flex-1 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" />
                </div>
              </div>
              <div className="flex gap-3 pt-1">
                <button type="button" onClick={() => setEditingColor(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">
        {/* HEADER */}
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-zinc-900 text-white rounded-xl shadow-lg"><Palette size={20} /></div>
          <div>
            <h1 className="text-2xl font-extrabold tracking-tight text-zinc-900">Colors</h1>
            <p className="text-zinc-400 text-xs mt-0.5">Define color swatches for product variants</p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
          {/* ADD FORM */}
          <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 Color</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 })} placeholder="e.g. Classic Crimson" 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">Hex Value</label>
                <div className="flex gap-3 items-center">
                  <div className="w-10 h-10 rounded-lg overflow-hidden border border-zinc-200 shrink-0 cursor-pointer relative">
                    <input type="color" value={watchedValue} onChange={(e) => setValue("value", e.target.value, { shouldValidate: true })} className="absolute inset-0 w-[200%] h-[200%] -translate-x-[25%] -translate-y-[25%] cursor-pointer border-none p-0 outline-none" />
                  </div>
                  <input {...register("value", { required: true })} className="flex-1 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" />
                </div>
                {/* Swatch Preview */}
                <div className="mt-3 flex items-center gap-3 p-3 rounded-xl bg-zinc-50 border border-dashed border-zinc-200">
                  <div style={{ backgroundColor: watchedValue }} className="w-8 h-8 rounded-full border border-black/10 shadow-sm shrink-0" />
                  <span className="text-xs font-mono text-zinc-500">{watchedValue?.toUpperCase()}</span>
                </div>
              </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 ? "Saving..." : "Save Color"}
              </button>
            </form>
          </div>

          {/* COLOR LIST */}
          <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 colors...</span>
              </div>
            ) : colors.length === 0 ? (
              <div className="text-center py-16 bg-white rounded-2xl border border-zinc-100 flex flex-col items-center">
                <Palette className="text-zinc-200 w-12 h-12 mb-3" />
                <h3 className="text-sm font-bold text-zinc-700">No colors yet</h3>
                <p className="text-zinc-400 mt-1 text-xs">Create your first color swatch using the form.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {colors.map((color) => (
                  <div key={color.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">
                    {/* Swatch */}
                    <div style={{ backgroundColor: color.value }} className="w-11 h-11 rounded-lg border border-black/10 shadow-sm shrink-0 group-hover:scale-105 transition duration-200" />
                    {/* Info */}
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-semibold text-zinc-900 truncate group-hover:text-indigo-600 transition">{color.name}</p>
                      <p className="text-xs font-mono text-zinc-400">{color.value.toUpperCase()}</p>
                    </div>
                    {/* Actions */}
                    <div className="flex items-center gap-1 shrink-0">
                      <button onClick={() => openEdit(color)} 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(color.id)} disabled={deletingId === color.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 === color.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  )
}
