"use client"

import { useState, useEffect } from "react"
import api from "@/lib/axios"
import { Plus, Layers } from "lucide-react"
import Swal from "sweetalert2";

type Variant = {
  size: string
  color: string
  length?: string
  stock: number
  sku: string
  image?: string
  images: any
}

type Props = {
  onAdd: (variant: Variant) => void
}

type DBSize = {
  id: string
  name: string
  value: string
}

type DBColor = {
  id: string
  name: string
  value: string
}

type DBLength = {
  id: string
  name: string
  value: string
}

export default function VariantForm({ onAdd }: Props) {
  const [size, setSize] = useState("")
  const [color, setColor] = useState("")
  const [length, setLength] = useState("")
  const [stock, setStock] = useState(0)
  const [image, setImage] = useState("")
  const [images, setImages] = useState<string[]>([])
  const [uploading, setUploading] = useState(false)

  const [dbSizes, setDbSizes] = useState<DBSize[]>([])
  const [dbColors, setDbColors] = useState<DBColor[]>([])
  const [dbLengths, setDbLengths] = useState<DBLength[]>([])

  useEffect(() => {
    async function loadOptions() {
      try {
        const sizesRes = await api.get("/admin/sizes")
        setDbSizes(sizesRes.data)
        const colorsRes = await api.get("/admin/colors")
        setDbColors(colorsRes.data)
        const lengthsRes = await api.get("/admin/lengths")
        setDbLengths(lengthsRes.data)
      } catch (error) {
        console.log("Error loading variants options:", error)
      }
    }
    loadOptions()
  }, [])

  function handleAdd() {
    if (!size || !color) {
      Swal.fire({ text: "Please select both size and color for the variant.", confirmButtonColor: "#18181b" })
      return
    }

    onAdd({
      size,
      color,
      length: length || undefined,
      stock,
      sku: `SKU-${Date.now()}`,
      image: images.length > 0 ? images[0] : (image || undefined),
      images: [...images, ...(image ? [image] : [])].filter(Boolean),
    })

    setSize("")
    setColor("")
    setLength("")
    setStock(0)
    setImage("")
    setImages([])
  }

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = e.target.files
    if (!files || files.length === 0) return

    setUploading(true)
    try {
      const formData = new FormData()
      for (let i = 0; i < files.length; i++) {
        formData.append("files", files[i])
      }
      const res = await api.post("/admin/upload", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      })
      const urls = res.data.urls as string[]
      setImages((prev) => [...prev, ...urls])
      e.target.value = ""
    } catch (err) {
      console.error(err)
      Swal.fire({ text: "Failed to upload variant images", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setUploading(false)
    }
  }

  function removeImage(index: number) {
    setImages(prev => prev.filter((_, i) => i !== index))
  }

  return (
    <div className="bg-zinc-50 border border-zinc-200/60 rounded-2xl p-4 space-y-4">
      <div className="flex items-center gap-2 pb-2 border-b border-zinc-200/40">
        <Layers className="text-zinc-950 w-4 h-4" />
        <h4 className="font-bold text-xs text-zinc-950 uppercase tracking-wider">Add Stock Variant</h4>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
        {/* SIZE SELECT */}
        <div className="relative">
          <select
            value={size}
            onChange={(e) => setSize(e.target.value)}
            className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 bg-white text-xs font-semibold transition"
          >
            <option value="">Select Size</option>
            {dbSizes.map((s) => (
              <option key={s.id} value={s.value}>
                {s.name} ({s.value})
              </option>
            ))}
          </select>
        </div>

        {/* COLOR SELECT */}
        <div className="relative">
          <select
            value={color}
            onChange={(e) => setColor(e.target.value)}
            className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 bg-white text-xs font-semibold transition"
          >
            <option value="">Select Color</option>
            {dbColors.map((c) => (
              <option key={c.id} value={c.name}>
                {c.name}
              </option>
            ))}
          </select>
        </div>

        {/* LENGTH SELECT (PREMIUM DYNAMIC FEATURE) */}
        <div className="relative">
          <select
            value={length}
            onChange={(e) => setLength(e.target.value)}
            className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 bg-white text-xs font-semibold transition text-zinc-900"
          >
            <option value="">No Length / Standard</option>
            {dbLengths.map((l) => (
              <option key={l.id} value={l.value}>
                {l.name} ({l.value})
              </option>
            ))}
          </select>
        </div>

        {/* STOCK INPUT */}
        <div>
          <input
            type="number"
            value={stock}
            onChange={(e) => setStock(Math.max(0, Number(e.target.value)))}
            placeholder="Available Units"
            className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:border-transparent transition bg-white text-xs font-semibold"
          />
        </div>

        {/* IMAGE UPLOAD & URL INPUT */}
        <div className="md:col-span-4 mt-2 space-y-3">
          <div className="flex gap-2">
            <input
              type="text"
              value={image}
              onChange={(e) => setImage(e.target.value)}
              placeholder="Paste Image URL (or upload files ->)"
              className="flex-1 border border-zinc-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:border-transparent transition bg-white text-xs font-semibold placeholder:text-zinc-400"
            />
            <label className={`bg-zinc-100 border border-zinc-200 hover:bg-zinc-200 text-zinc-800 font-bold py-2.5 px-4 rounded-xl cursor-pointer text-xs transition flex items-center justify-center gap-2 ${uploading ? 'opacity-50' : ''}`}>
              {uploading ? "Uploading..." : "Upload Files"}
              <input 
                type="file" 
                multiple 
                accept="image/*"
                onChange={handleFileUpload}
                disabled={uploading}
                className="hidden" 
              />
            </label>
          </div>
          
          {images.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {images.map((img, idx) => (
                <div key={idx} className="relative w-16 h-16 border border-zinc-200 rounded-lg overflow-hidden group">
                  <img src={img} alt="Variant" className="w-full h-full object-cover" />
                  <button 
                    type="button"
                    onClick={() => removeImage(idx)}
                    className="absolute inset-0 bg-red-500/80 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition"
                  >
                    X
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <button
        type="button"
        onClick={handleAdd}
        className="w-full md:w-auto bg-zinc-950 text-white font-bold py-2.5 px-5 rounded-xl hover:bg-zinc-800 transition flex items-center justify-center gap-1.5 cursor-pointer text-[10px] uppercase tracking-wider shadow-md"
      >
        <Plus className="w-3.5 h-3.5" />
        Add Variant Line
      </button>
    </div>
  )
}