import { useMemo } from 'react';

import type { Lead, LeadSource, LeadStatus } from '@/types/entities';
import { useData } from '@/providers/data-provider';

type UseLeadsFilters = {
    source?: LeadSource;
    excludeSources?: Set<LeadSource>;
    status?: LeadStatus;
    search?: string;
};

type UseLeadsResult = {
    leads: Lead[];
    total: number;
    updateLead: (id: string, updates: Partial<Lead>) => void;
};

export const useLeads = (filters: UseLeadsFilters = {}): UseLeadsResult => {
    const { leads, updateLead } = useData();
    const { source, excludeSources, status, search } = filters;

    const filteredLeads = useMemo(() => {
        return leads.filter((lead) => {
            if (source !== undefined && lead.leadSource !== source) {
                return false;
            }

            if (excludeSources && lead.leadSource && excludeSources.has(lead.leadSource)) {
                return false;
            }

            if (status !== undefined && lead.leadStatus !== status) {
                return false;
            }

            if (search !== undefined && search.trim() !== '') {
                const query = search.trim().toLowerCase();
                const firstName = lead.contactName?.firstName?.toLowerCase() ?? '';
                const lastName = lead.contactName?.lastName?.toLowerCase() ?? '';
                const fullName = `${firstName} ${lastName}`.trim();
                const phones = (lead.contactPhone ?? []).map((p) => p.number.toLowerCase());

                const matchesName = firstName.includes(query) || lastName.includes(query) || fullName.includes(query);
                const matchesPhone = phones.some((phone) => phone.includes(query));

                if (!matchesName && !matchesPhone) {
                    return false;
                }
            }

            return true;
        });
    }, [leads, source, excludeSources, status, search]);

    return {
        leads: filteredLeads,
        total: filteredLeads.length,
        updateLead,
    };
};
