"use client";
import { useState } from "react";
import "highlight.js/styles/github.css";
import client from "@auth";
import { Icon } from "@iconify/react";
import MasterLayout from "@/masterLayout/MasterLayout";
import Breadcrumb from "@/components/Breadcrumb";
import { useRouter, useSearchParams } from "next/navigation";
import axios from "axios";
import { Baseurl } from "@utils/BaseUrl.utils";

const AddNewProduct = () => {
    const searchParams = useSearchParams();
    const category = searchParams.get("category");
    const router = useRouter();

    const [imagePreview, setImagePreview] = useState(null);
    const [imageFile, setImageFile] = useState(null);

    const [formData, setFormData] = useState({
        menuitemname: "",
        price: 0,
        is_active: false,
        is_special: false,
        availability_time: "",
        preparation_time: 0,
        description: "",
    });

    const [errors, setErrors] = useState({});

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: type === "checkbox" ? checked : value,
        }));
    };

    const handleFileChange = (e) => {
        const file = e.target.files?.[0];
        if (file) {
            setImageFile(file);
            setImagePreview(URL.createObjectURL(file));
        }
    };

    const handleRemoveImage = () => {
        setImageFile(null);
        setImagePreview(null);
    };

    const validate = () => {
        const newErrors = {};
        if (!formData.menuitemname || formData.menuitemname.trim().length < 3) {
            newErrors.menuitemname = "Menu Item Name is required";
        }
        if (!formData.price || Number(formData.price) <= 0) {
            newErrors.price = "Price must be greater than 0";
        }
        if (!formData.availability_time) {
            newErrors.availability_time = "Availability Time is required";
        }
        if (!formData.preparation_time || Number(formData.preparation_time) <= 0) {
            newErrors.preparation_time = "Preparation Time must be greater than 0";
        }
        if (!formData.description || formData.description.trim().length < 5) {
            newErrors.description = "Description is too short";
        }
        if (!imageFile) {
            newErrors.image_item = "Image is required";
        }
        return newErrors;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const validationErrors = validate();
        if (Object.keys(validationErrors).length > 0) {
            setErrors(validationErrors);
            return;
        }
        setErrors({});

        const body =
        {
            menuitemname: formData.menuitemname,
            price: formData.price,
            is_active: formData.is_active ? 1 : 0,
            is_special: formData.is_special ? 1 : 0,
            availability_time: formData.availability_time,
            preparation_time: formData.preparation_time,
            description: formData.description,
        };

        try {
            // const formDataToSend = new FormData();
            // formDataToSend.append("endpoint", `Dine360%20Menu%20Category/${category}`);
            // formDataToSend.append("body", JSON.stringify(body));
            // formDataToSend.append("file", imageFile); // ✅ use imageFile
            // formDataToSend.append("fileid", "image_item");

            // const response = await axios.post(`${Baseurl}/Upload-Image-To-Frappe`, formDataToSend, {
            //     headers: {
            //         Authorization: "token 482beca79d9c005:b8778f51fcca82b",
            //     },
            // });
            const formDataToSend = new FormData();
            formDataToSend.append("endpoint", "Dine360 Menu Category");
            formDataToSend.append("file", imageFile); // ✅ use imageFile
            formDataToSend.append("fileid", "item_image");
            formDataToSend.append("childjson", JSON.stringify(body))
            formDataToSend.append("childkey", "menuitems_child");
            formDataToSend.append("docname", category);
             formDataToSend.append("isimageupdateorcreate", 1);
            console.log(formDataToSend)
            const response = await axios.post(`${Baseurl}/Upload-Image-To-Frappe/parent-child`, formDataToSend, {
                headers: {
                    Authorization: "token 482beca79d9c005:b8778f51fcca82b",
                },
            });

            console.log("response", response);
            alert("Form submitted successfully!");
            router.push("/admin/pos/product-list");
        } catch (error) {
            console.log("error", error);
        }
    };

    return (
        <MasterLayout>
            <Breadcrumb title="Create Product" />
            <div className="container" style={{ marginBottom: "100px" }}>
                <div className="row gy-4 d-flex justify-content-center">
                    <div className="col-xxl-6 col-xl-6 col-lg-7 col-md-9">
                        <div className="card mt-24 p-lg-3">
                            <div className="card-body">
                                <h6 className="text-xl mb-3">Add New Product</h6>
                                <form onSubmit={handleSubmit} className="d-flex flex-column gap-20">
                                    <div className="row">
                                        <div className="col-xl-6">
                                            <label className="form-label fw-bold text-neutral-900 mb-0">
                                                Menu Item Name
                                            </label>
                                            <input
                                                type="text"
                                                name="menuitemname"
                                                value={formData.menuitemname}
                                                onChange={handleChange}
                                                className="form-control border border-neutral-200 radius-8"
                                                placeholder="Enter name"
                                            />
                                            {errors.menuitemname && (
                                                <div className="text-danger small">{errors.menuitemname}</div>
                                            )}
                                        </div>
                                        <div className="col-xl-6">
                                            <label className="form-label fw-bold text-neutral-900 mb-0">Price ($)</label>
                                            <input
                                                type="number"
                                                name="price"
                                                value={formData.price}
                                                onChange={handleChange}
                                                className="form-control border border-neutral-200 radius-8"
                                            />
                                            {errors.price && (
                                                <div className="text-danger small">{errors.price}</div>
                                            )}
                                        </div>
                                    </div>

                                    <div>
                                        <label className="form-label fw-bold text-neutral-900 mb-0">
                                            Description
                                        </label>
                                        <textarea
                                            name="description"
                                            rows={4}
                                            className="form-control border border-neutral-200 radius-8"
                                            placeholder="Enter description..."
                                            value={formData.description}
                                            onChange={handleChange}
                                        ></textarea>
                                        {errors.description && (
                                            <div className="text-danger small">{errors.description}</div>
                                        )}
                                    </div>

                                    <div className="row">
                                        <div className="form-check col-6 d-flex justify-content-start gap-2 align-items-center">
                                            <input
                                                type="checkbox"
                                                name="is_active"
                                                className="form-check-input"
                                                checked={formData.is_active}
                                                onChange={handleChange}
                                                id="is_active"
                                            />
                                            <label className="form-check-label" htmlFor="is_active">
                                                Is Active
                                            </label>
                                        </div>

                                        <div className="form-check col-6 d-flex justify-content-start gap-2 align-items-center">
                                            <input
                                                type="checkbox"
                                                name="is_special"
                                                className="form-check-input"
                                                checked={formData.is_special}
                                                onChange={handleChange}
                                                id="is_special"
                                            />
                                            <label className="form-check-label" htmlFor="is_special">
                                                Is Special
                                            </label>
                                        </div>
                                    </div>

                                    <div className="row">
                                        <div className="col-xl-6">
                                            <label className="form-label fw-bold text-neutral-900 mb-0">
                                                Availability Time
                                            </label>
                                            <input
                                                type="time"
                                                name="availability_time"
                                                value={formData.availability_time}
                                                onChange={handleChange}
                                                className="form-control border border-neutral-200 radius-8"
                                            />
                                            {errors.availability_time && (
                                                <div className="text-danger small">{errors.availability_time}</div>
                                            )}
                                        </div>
                                        <div className="col-xl-6">
                                            <label className="form-label fw-bold text-neutral-900 mb-0">
                                                Preparation Time (minutes)
                                            </label>
                                            <input
                                                type="number"
                                                name="preparation_time"
                                                value={formData.preparation_time}
                                                onChange={handleChange}
                                                className="form-control border border-neutral-200 radius-8"
                                            />
                                            {errors.preparation_time && (
                                                <div className="text-danger small">{errors.preparation_time}</div>
                                            )}
                                        </div>
                                    </div>

                                    <div>
                                        <label className="form-label fw-bold text-neutral-900 mb-0">
                                            Menu Item Image
                                        </label>
                                        <div className="upload-image-wrapper">
                                            {imagePreview ? (
                                                <div className="uploaded-img position-relative h-160-px w-100 border input-form-light radius-8 overflow-hidden border-dashed bg-neutral-50">
                                                    <button
                                                        type="button"
                                                        onClick={handleRemoveImage}
                                                        className="uploaded-img__remove position-absolute top-0 end-0 z-1 text-2xxl line-height-1 me-8 mt-8 d-flex"
                                                        aria-label="Remove uploaded image"
                                                    >
                                                        <Icon icon="radix-icons:cross-2" className="text-xl text-danger-600" />
                                                    </button>
                                                    <img
                                                        id="uploaded-img__preview"
                                                        className="w-100 h-100 object-fit-cover"
                                                        src={imagePreview}
                                                        alt="Uploaded"
                                                    />
                                                </div>
                                            ) : (
                                                <label
                                                    className="upload-file h-160-px w-100 border input-form-light radius-8 overflow-hidden border-dashed bg-neutral-50 bg-hover-neutral-200 d-flex align-items-center flex-column justify-content-center gap-1"
                                                    htmlFor="upload-file"
                                                >
                                                    <Icon icon="solar:camera-outline" className="text-xl text-secondary-light" />
                                                    <span className="fw-semibold text-secondary-light">Upload</span>
                                                    <input id="upload-file" type="file" hidden onChange={handleFileChange} />
                                                </label>
                                            )}
                                            {errors.image_item && (
                                                <div className="text-danger small">{errors.image_item}</div>
                                            )}
                                        </div>
                                    </div>

                                    <div className="row">
                                        <div className="col-6">
                                            <button
                                                className="btn btn-outline-theme radius-8"
                                                style={{ width: "100%" }}
                                                onClick={() => router.push("/admin/pos/product-list")}
                                            >
                                                Cancel
                                            </button>
                                        </div>
                                        <div className="col-6">
                                            <button type="submit" className="btn btn-bg-theme radius-8" style={{ width: "100%" }}>
                                                Submit
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </MasterLayout>
    );
};

export default AddNewProduct;
