'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, Plus, X, Loader2 } from 'lucide-react';
import apis from '@/utils/apis';
import { Input } from '@/components/ui/input';

interface Customer {
    _id: string;
    name: string;
    email?: string;
    country_code?: string;
    phone?: string;
    gst_no?: string; // Sometimes gst/gst_no
    [key: string]: any;
}

interface CustomerSearchProps {
    onSelect: (customer: {
        _id: string;
        name: string;
        phone: string;
        email: string;
        gst: string;
        country_code: string;
        customer_id?: string;
    }) => void;
    onAddNew: () => void;
    selectedValue?: string;
    onClear?: () => void;
}

export default function CustomerSearch({ onSelect, onAddNew, selectedValue, onClear }: CustomerSearchProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isFetchingMore, setIsFetchingMore] = useState(false);

    const dropdownRef = useRef<HTMLDivElement>(null);
    const scrollContainerRef = useRef<HTMLDivElement>(null);

    // Fetch customers from API
    const fetchCustomers = useCallback(async (query: string, pageNum: number, append: boolean = false) => {
        if (pageNum === 1) {
            setLoading(true);
        } else {
            setIsFetchingMore(true);
        }
        try {
            const res = await apis.Customer.listing(`search=${encodeURIComponent(query)}&page=${pageNum}&limit=20`);
            if (res && res.data) {
                setCustomers(prev => {
                    const newList = append ? [...prev, ...res.data] : res.data;
                    const totalCount = res.count || 0;
                    setHasMore(newList.length < totalCount);
                    return newList;
                });
                setPage(pageNum);
            }
        } catch (error) {
            console.error('Error fetching customers:', error);
        } finally {
            setLoading(false);
            setIsFetchingMore(false);
        }
    }, []);

    // Fetch initial list when dropdown is opened or search query changes
    useEffect(() => {
        if (isOpen) {
            const delayDebounceFn = setTimeout(() => {
                fetchCustomers(searchQuery, 1, false);
            }, 300); // 300ms debounce to prevent API spamming

            return () => clearTimeout(delayDebounceFn);
        }
    }, [isOpen, searchQuery, fetchCustomers]);

    // Handle clicks outside dropdown to close it
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    // Handle container scroll for pagination
    const handleScroll = () => {
        if (!scrollContainerRef.current || loading || isFetchingMore || !hasMore) return;

        const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
        // Trigger load when user scrolls near the bottom of the list
        if (scrollHeight - scrollTop - clientHeight < 15) {
            fetchCustomers(searchQuery, page + 1, true);
        }
    };

    // Handle customer selection
    const handleSelect = (customer: Customer) => {
        onSelect({
            _id: customer._id || '',
            name: customer.name || '',
            phone: customer.phone || '',
            email: customer.email || '',
            gst: customer.gst_no || customer.gst || '',
            country_code: customer.country_code ? `+${customer.country_code.replace('+', '')}` : '+91',
            customer_id: customer.custom_id || customer.customer_id || customer.user_id || customer.referral?.referral_code || customer._id || ''
        });
        setSearchQuery('');
        setIsOpen(false);
    };

    return (
        <div ref={dropdownRef} className="relative flex-1">
            <div className="relative">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                <Input
                    placeholder="Search Customer"
                    className="bg-gray-50 pl-10 pr-10 h-10 w-full rounded-xl border border-gray-200 focus-visible:ring-[var(--orange-500)] text-sm"
                    value={selectedValue || searchQuery}
                    onChange={(e) => {
                        setSearchQuery(e.target.value);
                        if (onClear && selectedValue) {
                            onClear();
                        }
                    }}
                    onFocus={() => setIsOpen(true)}
                />
                {(selectedValue || searchQuery) && (
                    <button
                        onClick={() => {
                            setSearchQuery('');
                            if (onClear) onClear();
                        }}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                        type="button"
                    >
                        <X className="h-4 w-4" />
                    </button>
                )}
            </div>

            {isOpen && (
                <div className="absolute left-0 right-0 z-50 mt-1 max-h-[300px] overflow-hidden rounded-2xl border border-gray-100 bg-white p-2 shadow-xl flex flex-col">
                    {loading && customers.length === 0 ? (
                        <div className="flex items-center justify-center p-6 text-xs text-gray-400">
                            <Loader2 className="mr-2 h-4 w-4 animate-spin text-[var(--orange-500)]" />
                            Loading customers...
                        </div>
                    ) : (
                        <>
                            <div
                                ref={scrollContainerRef}
                                onScroll={handleScroll}
                                className="flex-1 overflow-y-auto max-h-[220px] custom-scrollbar"
                            >
                                {customers.map((customer) => {
                                    const code = customer.country_code ? `+${customer.country_code.replace('+', '')}` : '+91';
                                    const displayPhone = customer.phone ? `${code} ${customer.phone}` : '';
                                    const referralCode = customer.referral?.referral_code;
                                    return (
                                        <button
                                            key={customer._id}
                                            onClick={() => handleSelect(customer)}
                                            className="w-full text-left px-4 py-3 rounded-xl hover:bg-gray-50 transition-colors flex flex-col gap-0.5"
                                            type="button"
                                        >
                                            <span className="font-bold text-sm text-gray-800">
                                                {customer.name}
                                            </span>
                                            {displayPhone && (
                                                <span className="text-xs text-gray-400">
                                                    {displayPhone}
                                                </span>
                                            )}
                                            {referralCode && (
                                                <span className="text-[10px] font-bold text-[var(--orange-500)] bg-[var(--orange-50)] px-2 py-0.5 rounded-md whitespace-nowrap w-fit mt-0.5">
                                                    Ref: {referralCode}
                                                </span>
                                            )}
                                        </button>
                                    );
                                })}

                                {isFetchingMore && (
                                    <div className="flex items-center justify-center p-3 text-xs text-gray-400">
                                        <Loader2 className="mr-2 h-3 w-3 animate-spin text-[var(--orange-500)]" />
                                        Loading more...
                                    </div>
                                )}

                                {customers.length === 0 && !loading && (
                                    <div className="p-6 text-center text-xs text-gray-400">
                                        No customers found
                                    </div>
                                )}
                            </div>

                            <button
                                onClick={() => {
                                    onAddNew();
                                    setIsOpen(false);
                                }}
                                className="w-full mt-1 border-t border-gray-100 pt-2 pb-1 text-center font-bold text-sm text-[var(--orange-500)] hover:text-[var(--orange-500)]/90 transition-colors flex items-center justify-center gap-1 cursor-pointer"
                                type="button"
                            >
                                <Plus className="h-4 w-4" />
                                Add New Customer
                            </button>
                        </>
                    )}
                </div>
            )}
        </div>
    );
}
