import React, { useEffect, useState } from 'react';
import { OptionsOrGroups } from 'react-select';
import AsyncSelect from 'react-select/async';
import CheckSwitch from '@/components/Switch';

interface Product {
    product_title: string;
    product_sort_description: string;
    product_meta_description: string;
    product_is_purchasable: boolean;
    product_is_new: boolean;
    product_is_pre_order: boolean;
    product_is_coming_soon: boolean;
    product_pre_order_text: string;
    product_sold_count: number;
    product_search_count: number;
    product_view_count: number;
    product_similar: [];
    product_link: string;
    product_is_sni: boolean;
    product_show_in_page: boolean;
    product_is_searchable: boolean;
    product_wedding_text_preview: string;
}

interface ProductProps {
    detail: Product;
    setDetail: React.Dispatch<React.SetStateAction<Product>>;
    showLastChange: boolean;
    setIsLastChange: React.Dispatch<React.SetStateAction<boolean>>;
    isLastChange: boolean;
}

const DetailForm: React.FC<ProductProps> = ({ detail, setDetail, showLastChange, setIsLastChange, isLastChange }) => {
    const handleProduct = (e: any) => {
        setDetail((prev) => ({
            ...prev,
            [e.target.name]: e.target.value,
        }));
    };

    const [selectedProducts, setSelectedProducts] = useState<any>([]);

    useEffect(() => {
        const formattedProductSimilar = selectedProducts.map((product: any) => product.value);
        setDetail((prev) => ({
            ...prev,
            product_similar: formattedProductSimilar,
        }));
    }, [selectedProducts]);

    const getListProducts = async () => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/product-list`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    products: detail.product_similar,
                }),
                credentials: 'include', // Include this option
            });
            const data = await response.json();
            const formattedData = data.map((item: any) => ({ value: item.id, label: item.product_title }));

            setSelectedProducts(formattedData);
        } catch (error) {
            console.error('Error fetching data:', error);
            return [];
        }
    };
    useEffect(() => {
        if (detail.product_similar.length > 0) {
            getListProducts();
        }
    }, []);

    const fetchData = async (inputValue: string) => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/product-list?q=${inputValue}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();
            return data.map((item: any) => ({ value: item.id, label: item.product_title }));
        } catch (error) {
            console.error('Error fetching data:', error);
            return [];
        }
    };

    let debounceTimeout: any;

    const loadOptions = async (inputValue: string): Promise<OptionsOrGroups<any, any>> => {
        return new Promise<OptionsOrGroups<any, any>>((resolve) => {
            clearTimeout(debounceTimeout);

            if (inputValue.length >= 3) {
                debounceTimeout = setTimeout(async () => {
                    try {
                        const options = await fetchData(inputValue);
                        const filteredOptions = options.filter((option: any) => !detail.product_similar.some((item: any) => item.item_id === option.value));

                        resolve(filteredOptions);
                    } catch (error) {
                        console.error('Error loading options:', error);
                        resolve([]);
                    }
                }, 1000);
            } else {
                resolve([]);
            }
        });
    };

    return (
        <div className="w-full lg:w-full">
            <div className=" m-4 flex items-center">
                <label htmlFor="product_title" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Name
                </label>
                <input
                    id="product_title"
                    type="text"
                    name="product_title"
                    className="form-input w-2/3"
                    placeholder="Masukan Nama Produk"
                    value={detail ? detail.product_title : ''}
                    onChange={handleProduct}
                />
            </div>
            <div className="m-4 flex items-center ">
                <label htmlFor="product_meta_description" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Meta Description (SEO)
                </label>
                <textarea
                    id="product_meta_description"
                    name="product_meta_description"
                    rows={2}
                    value={detail ? detail.product_meta_description : ''}
                    onChange={handleProduct}
                    className="form-input w-2/3"
                    placeholder="Meta Deskripsi Produk...."
                ></textarea>
            </div>
            <div className="m-4 flex items-center ">
                <label htmlFor="product_sort_description" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Description
                </label>
                <textarea
                    id="product_sort_description"
                    name="product_sort_description"
                    rows={5}
                    value={detail ? detail.product_sort_description : ''}
                    onChange={handleProduct}
                    className="form-input w-2/3"
                    placeholder="Deskripsi Produk...."
                ></textarea>
            </div>

            <div className="m-4 flex items-start">
                <label className="mb-0 flex-1 pt-3 font-semibold ltr:mr-2 rtl:ml-2 ">
                    Product Options
                </label>
                <div className="w-2/3 rounded-lg border border-slate-200 dark:border-slate-800  p-4">
                    <div className="grid grid-cols-2 gap-2">
                        {[
                            { id: 'product_is_new', label: 'Product Is New', key: 'product_is_new' as const, defaultChecked: false },
                            { id: 'product_is_pre_order', label: 'Product Is Pre-Order', key: 'product_is_pre_order' as const, defaultChecked: false },
                            { id: 'product_is_sni', label: 'Product Is SNI', key: 'product_is_sni' as const, defaultChecked: false },
                            { id: 'product_is_coming_soon', label: 'Product Is Coming Soon', key: 'product_is_coming_soon' as const, defaultChecked: false },
                            { id: 'product_is_purchasable', label: 'Product Is Purchasable', key: 'product_is_purchasable' as const, defaultChecked: false },
                            { id: 'product_show_in_page', label: 'Product Show in Page', key: 'product_show_in_page' as const, defaultChecked: true },
                            { id: 'product_is_searchable', label: 'Product Is Searchable', key: 'product_is_searchable' as const, defaultChecked: true },
                        ].map(({ id, label, key, defaultChecked }) => (
                            <label
                                key={key}
                                htmlFor={id}
                                className="flex cursor-pointer items-center justify-between rounded-md border border-slate-200 dark:border-slate-800 bg-white dark:bg-[#121E32]  px-4 py-3 transition-colors "
                            >
                                <span className="text-sm font-medium ">{label}</span>
                                <CheckSwitch
                                    id={id}
                                    checked={detail[key] ?? defaultChecked}
                                    onChange={(e) => setDetail((prev) => ({ ...prev, [key]: e.target.checked }))}
                                />
                            </label>
                        ))}
                        {showLastChange && (
                            <label
                                htmlFor="product_show_last_change"
                                className="flex cursor-pointer items-center justify-between rounded-md border border-slate-200 dark:border-slate-800 bg-white dark:bg-[#121E32]  px-4 py-3 transition-colors "
                            >
                                <span className="text-sm font-medium ">Show in Last Change Page</span>
                                <CheckSwitch id="product_show_last_change" checked={isLastChange ?? false} onChange={(e) => setIsLastChange(e.target.checked)} />
                            </label>
                        )}
                    </div>
                </div>
            </div>

            {detail.product_is_pre_order && (
                <div className=" m-4 flex items-center">
                    <label htmlFor="product_title" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                        Pre-order Text
                    </label>
                    <input
                        id="product_pre_order_text"
                        type="text"
                        name="product_pre_order_text"
                        className="form-input w-2/3"
                        placeholder="Pre-order dalam x hari"
                        value={detail ? detail.product_pre_order_text : ''}
                        onChange={handleProduct}
                    />
                </div>
            )}
            <div className=" m-4 flex items-center">
                <label htmlFor="product_title" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Sold Count
                </label>
                <input id="product_sold_count" type="number" name="product_sold_count" className="form-input w-2/3" value={detail ? detail.product_sold_count : ''} onChange={handleProduct} />
            </div>
            <div className=" m-4 flex items-center">
                <label htmlFor="product_view_count" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product View Count
                </label>
                <input id="product_view_count" type="number" name="product_view_count" className="form-input w-2/3" value={detail ? detail.product_view_count : ''} onChange={handleProduct} />
            </div>
            <div className=" m-4 flex items-center">
                <label htmlFor="product_search_count" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Search Count
                </label>
                <input id="product_search_count" type="number" name="product_search_count" className="form-input w-2/3" value={detail ? detail.product_search_count : ''} onChange={handleProduct} />
            </div>
            <div className=" m-4 flex items-center">
                <label htmlFor="product_link" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Link
                </label>
                <input id="product_link" type="text" name="product_link" className="form-input w-2/3" value={detail ? detail.product_link : ''} onChange={handleProduct} placeholder="shopee link" />
            </div>
            <div className=" m-4 flex items-center">
                <label htmlFor="product_search_count" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Similar Items
                </label>
                <div className="custom-select  flex w-2/3 items-center">
                    <AsyncSelect
                        isMulti
                        loadOptions={loadOptions}
                        className="w-full"
                        placeholder="Search for product"
                         classNamePrefix="user-form-select"
                        value={selectedProducts}
                        onChange={(selectedItems: any) => {
                            setSelectedProducts(selectedItems);
                        }}
                    />
                </div>
            </div>
            <div className=" m-4 flex items-center">
                <label htmlFor="product_wedding_text_preview" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                    Product Wedding Text Preview
                </label>
                <input id="product_wedding_text_preview" type="text" name="product_wedding_text_preview" className="form-input w-2/3" value={detail ? detail.product_wedding_text_preview : ''} onChange={handleProduct} placeholder="Wedding Text Preview" />
            </div>
        </div>
    );
};

export default DetailForm;
