"use client";

import { useEffect, useState, Fragment } from 'react';
import { useCRMFilter } from '@/contexts/CRMFilterContext';
import { Combobox, Transition } from '@headlessui/react';
import {
    FunnelIcon,
    XMarkIcon,
    CheckIcon,
    ChevronUpDownIcon,
    MagnifyingGlassIcon
} from '@heroicons/react/24/outline';

interface Customer {
    id: string;
    name: string;
    company?: string;
    logo_url?: string;
}

export function CRMCustomerFilter() {
    const { selectedCustomerId, setSelectedCustomerId, customers, setCustomers, loading, setLoading } = useCRMFilter();
    const [query, setQuery] = useState('');

    console.log('🔍 CRMCustomerFilter render, selectedCustomerId:', selectedCustomerId);

    useEffect(() => {
        fetchCustomers();
    }, []);

    const fetchCustomers = async () => {
        try {
            setLoading(true);
            const response = await fetch('/api/crm/customers', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                setCustomers(data.customers || []);
            }
        } catch (error) {
            console.error('Error fetching customers:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleClearFilter = () => {
        setSelectedCustomerId(null);
        setQuery('');
    };

    const selectedCustomer = customers.find(c => c.id === selectedCustomerId);

    const filteredCustomers =
        query === ''
            ? customers
            : customers.filter((customer: Customer) => {
                const nameMatch = customer.name.toLowerCase().includes(query.toLowerCase());
                const companyMatch = customer.company?.toLowerCase().includes(query.toLowerCase());
                return nameMatch || companyMatch;
            });

    return (
        <div className="flex items-center gap-2">
            <div className="hidden md:flex items-center gap-1 text-gray-400 mr-1">
                <FunnelIcon className="w-4 h-4" />
                <span className="text-xs font-medium uppercase tracking-wider">Filtro CRM</span>
            </div>

            <Combobox
                value={selectedCustomerId}
                onChange={(value) => {
                    console.log('🎯 CRMCustomerFilter: Selecting customer ID:', value);
                    setSelectedCustomerId(value);
                    setQuery('');
                }}
                disabled={loading}
            >
                <div className="relative">
                    <div className="relative w-full min-w-[320px]">
                        <Combobox.Input
                            className="w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 py-2.5 pl-10 pr-10 text-sm leading-5 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:bg-white dark:focus:bg-gray-800 transition-all duration-200"
                            displayValue={(customerId: string) => {
                                const customer = customers.find(c => c.id === customerId);
                                if (!customer) return '';
                                return customer.company
                                    ? `${customer.name} (${customer.company})`
                                    : customer.name;
                            }}
                            onChange={(event) => setQuery(event.target.value)}
                            placeholder="Pesquisar por nome ou empresa..."
                        />
                        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                            {selectedCustomer?.logo_url ? (
                                <img
                                    src={selectedCustomer.logo_url}
                                    className="h-5 w-5 rounded-full object-cover border border-gray-200 dark:border-gray-700"
                                    alt=""
                                    onError={(e) => {
                                        (e.target as HTMLImageElement).style.display = 'none';
                                    }}
                                />
                            ) : (
                                <MagnifyingGlassIcon
                                    className="h-4 w-4 text-gray-400"
                                    aria-hidden="true"
                                />
                            )}
                        </div>
                        <Combobox.Button className="absolute inset-y-0 right-0 flex items-center pr-2">
                            <ChevronUpDownIcon
                                className="h-5 w-5 text-gray-400 hover:text-gray-600 transition-colors"
                                aria-hidden="true"
                            />
                        </Combobox.Button>
                    </div>
                    <Transition
                        as={Fragment}
                        leave="transition ease-in duration-100"
                        leaveFrom="opacity-100"
                        leaveTo="opacity-0"
                        afterLeave={() => setQuery('')}
                    >
                        <Combobox.Options className="absolute z-50 mt-2 max-h-80 w-full overflow-auto rounded-xl bg-white dark:bg-gray-800 py-1 text-base shadow-2xl ring-1 ring-black/5 dark:ring-white/10 focus:outline-none sm:text-sm border border-gray-100 dark:border-gray-700">
                            <Combobox.Option
                                value={null}
                                className={({ active }) =>
                                    `relative cursor-pointer select-none py-3 pl-10 pr-4 ${active
                                        ? 'bg-brand-50 dark:bg-brand-900/20 text-brand-900 dark:text-brand-100'
                                        : 'text-gray-900 dark:text-white'
                                    }`
                                }
                            >
                                {({ selected, active }) => (
                                    <>
                                        <span className={`block truncate ${selected ? 'font-semibold' : 'font-normal'}`}>
                                            Todos os Clientes (Visão Geral)
                                        </span>
                                        {selected ? (
                                            <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-brand-600">
                                                <CheckIcon className="h-5 w-5" aria-hidden="true" />
                                            </span>
                                        ) : null}
                                    </>
                                )}
                            </Combobox.Option>

                            <div className="px-3 py-2 text-[10px] font-bold text-gray-400 uppercase tracking-widest border-t border-gray-50 dark:border-gray-700/50 mt-1">
                                Clientes Disponíveis
                            </div>

                            {filteredCustomers.length === 0 && query !== '' ? (
                                <div className="relative cursor-default select-none py-4 px-4 text-center text-gray-500 dark:text-gray-400">
                                    <p className="text-sm">Nenhum cliente encontrado</p>
                                    <p className="text-xs mt-1">Tente outro termo de busca</p>
                                </div>
                            ) : (
                                filteredCustomers.map((customer: Customer) => (
                                    <Combobox.Option
                                        key={customer.id}
                                        value={customer.id}
                                        className={({ active }) =>
                                            `relative cursor-pointer select-none py-3 pl-10 pr-4 transition-colors ${active
                                                ? 'bg-brand-50 dark:bg-brand-900/20 text-brand-900 dark:text-brand-100'
                                                : 'text-gray-900 dark:text-white'
                                            }`
                                        }
                                    >
                                        {({ selected, active }) => (
                                            <>
                                                <div className="flex items-center gap-3">
                                                    {customer.logo_url ? (
                                                        <img
                                                            src={customer.logo_url}
                                                            alt={customer.name}
                                                            className="w-8 h-8 rounded-full object-cover border border-gray-200 dark:border-gray-700"
                                                            onError={(e) => {
                                                                (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${encodeURIComponent(customer.name)}&background=random`;
                                                            }}
                                                        />
                                                    ) : (
                                                        <div className="w-8 h-8 rounded-full bg-brand-100 dark:bg-brand-900/30 flex items-center justify-center text-brand-700 dark:text-brand-300 text-xs font-bold">
                                                            {customer.name.substring(0, 2).toUpperCase()}
                                                        </div>
                                                    )}
                                                    <div className="flex flex-col">
                                                        <span className={`block truncate ${selected ? 'font-semibold text-brand-700 dark:text-brand-400' : 'font-medium'}`}>
                                                            {customer.name}
                                                        </span>
                                                        {customer.company && (
                                                            <span className={`block truncate text-xs ${active ? 'text-brand-600/70 dark:text-brand-400/70' : 'text-gray-500 dark:text-gray-400'}`}>
                                                                {customer.company}
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                                {selected ? (
                                                    <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-brand-600">
                                                        <CheckIcon className="h-5 w-5" aria-hidden="true" />
                                                    </span>
                                                ) : null}
                                            </>
                                        )}
                                    </Combobox.Option>
                                ))
                            )}
                        </Combobox.Options>
                    </Transition>
                </div>
            </Combobox>

            {selectedCustomerId && (
                <button
                    onClick={handleClearFilter}
                    className="p-2 hover:bg-red-50 dark:hover:bg-red-900/20 text-gray-400 hover:text-red-600 rounded-xl transition-all duration-200 flex-shrink-0 border border-transparent hover:border-red-100 dark:hover:border-red-900/30"
                    title="Limpar filtro"
                >
                    <XMarkIcon className="w-5 h-5" />
                </button>
            )}
        </div>
    );
}
