import React, { useState, useEffect } from "react";
import { AutoComplete } from "primereact/autocomplete";
import axios from "axios";

const CustomerDropdown = ({
    field,
    onChange,
    onSelect,
    placeholder = "Search Customer",
    label = "Search Customer/Retailer",
    showLabel = true,
    labelClassName = "block text-sm font-medium text-gray-600 mb-2",
    className = "",
    inputClassName = "w-full h-10 rounded-lg",
    required = false,
    selectedValue ="" ,
}) => {
    // Local state for the component
    const [searchValue, setSearchValue] = useState(selectedValue);
    const [customers, setCustomers] = useState([]);

    // Function to filter customers from API
    const filterCustomers = (event) => {
        setTimeout(() => {
            axios
                .post(route("customer-search"), { data: event.query })
                .then((response) => {
                    setCustomers(response.data.customer);
                })
                .catch((error) => {
                    console.error("Error fetching customers:", error);
                });
        }, 250);
    };

    // Template for customer items in dropdown
    const customerItemTemplate = (option) => {
        return (
            <div className="flex flex-col">
                <div className="font-medium">
                    {option.name} {option.code && `(${option.code})`}
                </div>
                <div className="text-xs text-gray-500">
                    {option.user_type && `${option.user_type}`}
                    {option.number && ` • ${option.number}`}
                </div>
            </div>
        );
    };

    // Handle selection change
    const handleChange = (e) => {
        const value = e.value;
        // Update local state
        setSearchValue(
            value && value.name
                ? `${value.name} ${value.code ? `(${value.code})` : ""}`
                : value
        );

        // Call passed onChange handler
        if (onChange) {
            onChange(value);
        }

        // Call onSelect with the full customer object if a customer was selected
        if (onSelect && value && value.id) {
            onSelect(value);
        }

        // If using with React Hook Form
        if (field && field.onChange) {
            field.onChange(value && value.id ? value.id : null);
        }
    };

    // Sync selectedValue prop with local state
    useEffect(() => {
        if (selectedValue) {
            setSearchValue(selectedValue);
        }
    }, [selectedValue]);

    // Handle initial value if using with React Hook Form
    useEffect(() => {
        if (field && field.value && !searchValue) {
            // If we have a field value but no search value, we need to fetch the customer details
            axios
                .get(route("customer.get", { id: field.value }))
                .then((response) => {
                    if (response.data && response.data.customer) {
                        const customer = response.data.customer;
                        setSearchValue(
                            `${customer.name} ${
                                customer.code ? `(${customer.code})` : ""
                            }`
                        );
                    }
                })
                .catch((error) => {
                    console.error("Error fetching customer details:", error);
                });
        }
    }, [field]);

    return (
        <div className={className}>
            {showLabel && (
                <label className={labelClassName}>
                    {label}
                    {required && <span className="text-red-500 ml-1">*</span>}
                </label>
            )}
            <AutoComplete
                value={searchValue}
                suggestions={customers}
                completeMethod={filterCustomers}
                field="name"
                dropdown
                itemTemplate={customerItemTemplate}
                onChange={handleChange}
                placeholder={placeholder}
                aria-label="Search Customer"
                dropdownAriaLabel="Select Customer"
                className={inputClassName}
            />
        </div>
    );
};

export default CustomerDropdown;
