import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import { toast } from "sonner";
import { UploadCloud, X } from "lucide-react";

import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

export default function CategorySelect({ selectedCategory, setSelectedCategory }) {
    const [categories, setCategories] = useState([]);
    const [newCategoryName, setNewCategoryName] = useState("");
    const [newCategoryDesc, setNewCategoryDesc] = useState("");
    const [newCategoryImage, setNewCategoryImage] = useState(null);
    const [imagePreview, setImagePreview] = useState(null);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);

    const fileInputRef = useRef(null);
    const API_URL = import.meta.env.VITE_API_URL;

    /* -------------------- FETCH CATEGORIES -------------------- */
    useEffect(() => {
        fetchCategories();
    }, []);

    const fetchCategories = async () => {
        try {
            const res = await axios.get(`${API_URL}/api/category/allcategory`);
            const list = res.data.categories || res.data;

            if (!Array.isArray(list)) return setCategories([]);

            setCategories(list);
        } catch (error) {
            console.error("Error loading categories:", error);
            toast.error("Failed to load categories");
        }
    };

    /* -------------------- ADD CATEGORY -------------------- */
    const handleAddCategory = async () => {
        if (!newCategoryName.trim()) return toast.error("Category name required");
        if (!newCategoryImage) return toast.error("Category image required");

        try {
            setLoading(true);

            const formData = new FormData();
            formData.append("name", newCategoryName);
            formData.append("description", newCategoryDesc);
            formData.append("image", newCategoryImage);

            const res = await axios.post(
                `${API_URL}/api/category/createcategory`,
                formData,
                { headers: { "Content-Type": "multipart/form-data" } }
            );

            toast.success("Category created!");

            const created = res.data.category;

            if (created && created._id) {
                setCategories((prev) => [...prev, created]);
                setSelectedCategory(created._id);
            } else {
                fetchCategories();
            }

            // Reset
            setNewCategoryName("");
            setNewCategoryDesc("");
            setNewCategoryImage(null);
            setImagePreview(null);
            setOpen(false);

        } catch (err) {
            console.error("Error creating category:", err);
            toast.error("Failed to create category");
        } finally {
            setLoading(false);
        }
    };

    /* -------------------- FIND SELECTED CATEGORY -------------------- */
    const selectedCatData =
        categories.find((cat) => cat._id === selectedCategory) || null;

    return (
        <div className="bg-white rounded-xl shadow-sm p-6">
            <h2 className="text-2xl font-semibold mb-4">Category</h2>
            <hr className="mb-4" />

            {/* CATEGORY SELECT */}
            <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                <SelectTrigger className="bg-white mt-1">
                    <SelectValue placeholder="Select category" />
                </SelectTrigger>

                <SelectContent className="bg-white">
                    {loading ? (
                        <SelectItem disabled value="loading">Loading...</SelectItem>
                    ) : categories.length > 0 ? (
                        categories.map((cat) => (
                            <SelectItem key={cat._id} value={cat._id}>
                                {cat.name}
                            </SelectItem>
                        ))
                    ) : (
                        <SelectItem disabled value="empty">No categories found</SelectItem>
                    )}
                </SelectContent>
            </Select>

            {/* SELECTED CATEGORY PREVIEW */}
            {selectedCatData && (
                <div className="mt-4 flex items-center gap-3 border rounded-lg p-2 bg-gray-50">
                    {selectedCatData.image && (
                        <img
                            src={
                                selectedCatData.image.startsWith("http")
                                    ? selectedCatData.image
                                    : `${API_URL}${selectedCatData.image}`
                            }
                            alt={selectedCatData.name}
                            className="w-12 h-12 object-cover rounded-md"
                        />
                    )}
                    <p className="font-medium">{selectedCatData.name}</p>
                </div>
            )}

            {/* ADD CATEGORY BUTTON */}
            <Button variant="outline" className="w-full mt-4" onClick={() => setOpen(true)}>
                + Add Category
            </Button>

            {/* -------------------- ADD CATEGORY POPUP -------------------- */}
            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-white rounded-lg">
                    <DialogHeader>
                        <DialogTitle>Add New Category</DialogTitle>
                    </DialogHeader>

                    {/* NAME */}
                    <label className="text-sm mt-2 block">Category Name</label>
                    <Input
                        placeholder="Enter name"
                        value={newCategoryName}
                        onChange={(e) => setNewCategoryName(e.target.value)}
                    />

                    {/* DESCRIPTION */}
                    <label className="text-sm mt-3 block">Description</label>
                    <textarea
                        className="w-full border rounded-lg p-2 text-sm"
                        placeholder="Enter description"
                        value={newCategoryDesc}
                        onChange={(e) => setNewCategoryDesc(e.target.value)}
                    />

                    {/* -------------------- IMAGE UPLOAD -------------------- */}
                    <label className="text-sm mt-3 block">Image</label>

                    <div
                        className="border-2 border-dashed rounded-lg h-40 w-full relative cursor-pointer overflow-hidden bg-gray-50 flex items-center justify-center"
                        onClick={() => !imagePreview && fileInputRef.current.click()}
                    >
                        {/* BEFORE Upload */}
                        {!imagePreview && (
                            <div className="flex flex-col items-center">
                                <UploadCloud size={40} className="text-orange-500 mb-2" />
                                <p className="text-sm text-gray-600">Click to upload</p>
                            </div>
                        )}

                        {/* AFTER Upload — image replaces upload box */}
                        {imagePreview && (
                            <img
                                src={imagePreview}
                                alt="Preview"
                                className="absolute inset-0 w-full h-full object-contain bg-white p-2 rounded-lg"
                            />
                        )}

                        {/* Remove image button */}
                        {imagePreview && (
                            <button
                                className="absolute top-2 right-2 bg-black/60 text-white p-1 rounded-full"
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setNewCategoryImage(null);
                                    setImagePreview(null);
                                }}
                            >
                                <X size={14} />
                            </button>
                        )}
                    </div>

                    {/* HIDDEN FILE INPUT */}
                    <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        ref={fileInputRef}
                        onChange={(e) => {
                            const file = e.target.files[0];
                            if (!file) return;
                            setNewCategoryImage(file);
                            setImagePreview(URL.createObjectURL(file));
                        }}
                    />

                    <DialogFooter className="mt-4">
                        <Button
                            disabled={loading}
                            onClick={handleAddCategory}
                            className="bg-orange-500 hover:bg-orange-600 text-white"
                        >
                            {loading ? "Adding..." : "Add Category"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
