import type { FC } from 'react';
import { useMemo, useState } from 'react';
import { useSearchParams } from 'react-router';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft, faArrowDownToLine, faMagnifyingGlass } from '@fortawesome/pro-duotone-svg-icons';

const ArrowLeft: FC<{ className?: string }> = ({ className }) => <FontAwesomeIcon icon={faArrowLeft} className={className} />;
const Download01: FC<{ className?: string }> = ({ className }) => <FontAwesomeIcon icon={faArrowDownToLine} className={className} />;
const SearchLg: FC<{ className?: string }> = ({ className }) => <FontAwesomeIcon icon={faMagnifyingGlass} className={className} />;
import { Button } from '@/components/base/buttons/button';
import { Input } from '@/components/base/input/input';
import { Tabs, TabList, Tab } from '@/components/application/tabs/tabs';
import { PaginationPageDefault } from '@/components/application/pagination/pagination';
import { TopBar } from '@/components/layout/top-bar';
import { LeadTable } from '@/components/leads/lead-table';
import { ColumnToggle, useColumnVisibility } from '@/components/application/table/column-toggle';
import { BulkActionBar } from '@/components/leads/bulk-action-bar';
import { FilterPills } from '@/components/leads/filter-pills';
import { AssignModal } from '@/components/modals/assign-modal';
import { WhatsAppSendModal } from '@/components/modals/whatsapp-send-modal';
import { MarkSpamModal } from '@/components/modals/mark-spam-modal';
import { LeadActivitySlideout } from '@/components/leads/lead-activity-slideout';
import { useLeads } from '@/hooks/use-leads';
import { useAuth } from '@/providers/auth-provider';
import { useData } from '@/providers/data-provider';
import { cx } from '@/utils/cx';
import type { Lead, LeadSource, LeadStatus } from '@/types/entities';

type TabKey = 'new' | 'my-leads' | 'all';

type ActiveFilter = {
    key: string;
    label: string;
    value: string;
};

const PAGE_SIZE = 15;

export const AllLeadsPage = () => {
    const { user } = useAuth();
    const [searchParams] = useSearchParams();
    const initialSource = searchParams.get('source') as LeadSource | null;
    const [tab, setTab] = useState<TabKey>('new');
    const [selectedIds, setSelectedIds] = useState<string[]>([]);
    const [sortField, setSortField] = useState('createdAt');
    const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
    const [sourceFilter, setSourceFilter] = useState<LeadSource | null>(initialSource);
    const [searchQuery, setSearchQuery] = useState('');
    const [currentPage, setCurrentPage] = useState(1);

    const statusFilter: LeadStatus | undefined = tab === 'new' ? 'NEW' : undefined;
    const myLeadsOnly = tab === 'my-leads';

    const { leads: filteredLeads, total, updateLead } = useLeads({
        source: sourceFilter ?? undefined,
        status: statusFilter,
        search: searchQuery || undefined,
    });

    const { agents, templates, leadActivities, campaigns } = useData();
    const [campaignFilter, setCampaignFilter] = useState<string | null>(null);

    const columnDefs = [
        { id: 'phone', label: 'Phone', defaultVisible: true },
        { id: 'name', label: 'Name', defaultVisible: true },
        { id: 'email', label: 'Email', defaultVisible: true },
        { id: 'campaign', label: 'Campaign', defaultVisible: false },
        { id: 'ad', label: 'Ad', defaultVisible: false },
        { id: 'source', label: 'Source', defaultVisible: true },
        { id: 'firstContactedAt', label: 'First Contact', defaultVisible: false },
        { id: 'lastContactedAt', label: 'Last Contact', defaultVisible: true },
        { id: 'status', label: 'Status', defaultVisible: true },
        { id: 'createdAt', label: 'Age', defaultVisible: true },
        { id: 'spamScore', label: 'Spam', defaultVisible: false },
        { id: 'dups', label: 'Dups', defaultVisible: false },
    ];
    const { visibleColumns, toggle: toggleColumn } = useColumnVisibility(columnDefs);

    // Client-side sorting
    const sortedLeads = useMemo(() => {
        const sorted = [...filteredLeads];
        sorted.sort((a, b) => {
            let aVal: string | number | null = null;
            let bVal: string | number | null = null;

            switch (sortField) {
                case 'phone':
                    aVal = a.contactPhone?.[0]?.number ?? '';
                    bVal = b.contactPhone?.[0]?.number ?? '';
                    break;
                case 'name':
                    aVal = `${a.contactName?.firstName ?? ''} ${a.contactName?.lastName ?? ''}`.trim();
                    bVal = `${b.contactName?.firstName ?? ''} ${b.contactName?.lastName ?? ''}`.trim();
                    break;
                case 'source':
                    aVal = a.leadSource ?? '';
                    bVal = b.leadSource ?? '';
                    break;
                case 'firstContactedAt':
                    aVal = a.firstContactedAt ?? '';
                    bVal = b.firstContactedAt ?? '';
                    break;
                case 'lastContactedAt':
                    aVal = a.lastContactedAt ?? '';
                    bVal = b.lastContactedAt ?? '';
                    break;
                case 'status':
                    aVal = a.leadStatus ?? '';
                    bVal = b.leadStatus ?? '';
                    break;
                case 'createdAt':
                    aVal = a.createdAt ?? '';
                    bVal = b.createdAt ?? '';
                    break;
                case 'spamScore':
                    aVal = a.spamScore ?? 0;
                    bVal = b.spamScore ?? 0;
                    break;
                default:
                    return 0;
            }

            if (typeof aVal === 'number' && typeof bVal === 'number') {
                return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
            }

            const aStr = String(aVal);
            const bStr = String(bVal);
            return sortDirection === 'asc' ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr);
        });
        return sorted;
    }, [filteredLeads, sortField, sortDirection]);

    // Apply "My Leads" + campaign filter
    const displayLeads = useMemo(() => {
        let result = sortedLeads;
        if (myLeadsOnly) {
            result = result.filter((l) => l.assignedAgent === user.name);
        }
        if (campaignFilter) {
            result = campaignFilter === '__none__'
                ? result.filter((l) => !l.campaignId)
                : result.filter((l) => l.campaignId === campaignFilter);
        }
        return result;
    }, [sortedLeads, myLeadsOnly, user.name, campaignFilter]);

    // Client-side pagination
    const totalPages = Math.max(1, Math.ceil(displayLeads.length / PAGE_SIZE));
    const pagedLeads = displayLeads.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

    const handleSort = (field: string) => {
        if (field === sortField) {
            setSortDirection((prev) => (prev === 'asc' ? 'desc' : 'asc'));
        } else {
            setSortField(field);
            setSortDirection('asc');
        }
        setCurrentPage(1);
    };

    const handleTabChange = (key: string | number) => {
        setTab(key as TabKey);
        setCurrentPage(1);
        setSelectedIds([]);
    };

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
        setSelectedIds([]);
    };

    // Build active filters for pills display
    const activeFilters: ActiveFilter[] = [];
    if (sourceFilter) {
        activeFilters.push({ key: 'source', label: 'Source', value: sourceFilter });
    }
    if (searchQuery) {
        activeFilters.push({ key: 'search', label: 'Search', value: searchQuery });
    }

    const handleRemoveFilter = (key: string) => {
        if (key === 'source') setSourceFilter(null);
        if (key === 'search') setSearchQuery('');
        setCurrentPage(1);
    };

    const handleClearAllFilters = () => {
        setSourceFilter(null);
        setSearchQuery('');
        setCurrentPage(1);
    };

    const myLeadsCount = sortedLeads.filter((l) => l.assignedAgent === user.name).length;

    const tabItems = [
        { id: 'new', label: 'New', badge: tab === 'new' ? total : undefined },
        { id: 'my-leads', label: 'My Leads', badge: tab === 'my-leads' ? myLeadsCount : undefined },
        { id: 'all', label: 'All Leads', badge: tab === 'all' ? total : undefined },
    ];

    // Bulk action modal state
    const [isAssignOpen, setIsAssignOpen] = useState(false);
    const [isWhatsAppOpen, setIsWhatsAppOpen] = useState(false);
    const [isSpamOpen, setIsSpamOpen] = useState(false);

    const selectedLeadsForAction = useMemo(
        () => displayLeads.filter((l) => selectedIds.includes(l.id)),
        [displayLeads, selectedIds],
    );

    const handleBulkAssign = () => setIsAssignOpen(true);
    const handleBulkWhatsApp = () => setIsWhatsAppOpen(true);
    const handleBulkSpam = () => setIsSpamOpen(true);

    // Activity slideout state
    const [activityLead, setActivityLead] = useState<Lead | null>(null);
    const [isActivityOpen, setIsActivityOpen] = useState(false);

    const handleViewActivity = (lead: Lead) => {
        setActivityLead(lead);
        setIsActivityOpen(true);
    };

    return (
        <div className="flex flex-1 flex-col overflow-hidden">
            <TopBar title="All Leads" subtitle={`${total} total`} />

            <div className="flex flex-1 flex-col overflow-hidden">
                {/* Tabs + Controls row */}
                <div className="flex shrink-0 items-center justify-between px-6 py-3 border-b border-secondary">
                    <div className="flex items-center gap-3">
                        <Button
                            href="/"
                            color="secondary"
                            size="sm"
                            iconLeading={ArrowLeft}
                            aria-label="Back to workspace"
                        />

                        <Tabs selectedKey={tab} onSelectionChange={handleTabChange}>
                            <TabList items={tabItems} type="button-gray" size="sm">
                                {(item) => (
                                    <Tab key={item.id} id={item.id} label={item.label} badge={item.badge} />
                                )}
                            </TabList>
                        </Tabs>
                    </div>

                    <div className="flex items-center gap-2">
                        <div className="w-56">
                            <Input
                                placeholder="Search leads..."
                                icon={SearchLg}
                                size="sm"
                                value={searchQuery}
                                onChange={(value) => {
                                    setSearchQuery(value);
                                    setCurrentPage(1);
                                }}
                                aria-label="Search leads"
                            />
                        </div>
                        <ColumnToggle columns={columnDefs} visibleColumns={visibleColumns} onToggle={toggleColumn} />
                        <Button
                            size="sm"
                            color="secondary"
                            iconLeading={Download01}
                        >
                            Export CSV
                        </Button>
                    </div>
                </div>

                {/* Active filters */}
                {activeFilters.length > 0 && (
                    <div className="shrink-0 px-6 pt-2">
                        <FilterPills
                            filters={activeFilters}
                            onRemove={handleRemoveFilter}
                            onClearAll={handleClearAllFilters}
                        />
                    </div>
                )}

                {/* Campaign filter pills */}
                {campaigns.length > 0 && (
                    <div className="flex shrink-0 items-center gap-1.5 px-6 py-2 border-b border-secondary overflow-x-auto">
                        <button
                            onClick={() => { setCampaignFilter(null); setCurrentPage(1); }}
                            className={cx(
                                'shrink-0 rounded-full px-3 py-1 text-xs font-medium transition duration-100 ease-linear',
                                !campaignFilter
                                    ? 'bg-brand-solid text-white'
                                    : 'bg-secondary text-tertiary hover:text-secondary hover:bg-secondary_hover',
                            )}
                        >
                            All
                        </button>
                        {campaigns.map(c => {
                            const isActive = campaignFilter === c.id;
                            const count = filteredLeads.filter(l => l.campaignId === c.id).length;
                            return (
                                <button
                                    key={c.id}
                                    onClick={() => { setCampaignFilter(isActive ? null : c.id); setCurrentPage(1); }}
                                    className={cx(
                                        'shrink-0 rounded-full px-3 py-1 text-xs font-medium transition duration-100 ease-linear',
                                        isActive
                                            ? 'bg-brand-solid text-white'
                                            : 'bg-secondary text-tertiary hover:text-secondary hover:bg-secondary_hover',
                                    )}
                                >
                                    {c.campaignName ?? 'Untitled'} ({count})
                                </button>
                            );
                        })}
                        <button
                            onClick={() => { setCampaignFilter(campaignFilter === '__none__' ? null : '__none__'); setCurrentPage(1); }}
                            className={cx(
                                'shrink-0 rounded-full px-3 py-1 text-xs font-medium transition duration-100 ease-linear',
                                campaignFilter === '__none__'
                                    ? 'bg-brand-solid text-white'
                                    : 'bg-secondary text-tertiary hover:text-secondary hover:bg-secondary_hover',
                            )}
                        >
                            No Campaign ({filteredLeads.filter(l => !l.campaignId).length})
                        </button>
                    </div>
                )}

                {/* Bulk action bar */}
                {selectedIds.length > 0 && (
                    <div className="shrink-0 px-6 pt-2">
                        <BulkActionBar
                            selectedCount={selectedIds.length}
                            onAssign={handleBulkAssign}
                            onWhatsApp={handleBulkWhatsApp}
                            onMarkSpam={handleBulkSpam}
                            onDeselect={() => setSelectedIds([])}
                        />
                    </div>
                )}

                {/* Table — fills remaining space, scrolls internally */}
                <div className="flex flex-1 flex-col min-h-0 overflow-hidden px-4 pt-2">
                    <LeadTable
                        leads={pagedLeads}
                        onSelectionChange={setSelectedIds}
                        selectedIds={selectedIds}
                        sortField={sortField}
                        sortDirection={sortDirection}
                        onSort={handleSort}
                        onViewActivity={handleViewActivity}
                        visibleColumns={visibleColumns}
                    />
                </div>

                {/* Pagination — pinned at bottom */}
                {totalPages > 1 && (
                    <div className="shrink-0 border-t border-secondary px-6 py-3">
                        <PaginationPageDefault
                            page={currentPage}
                            total={totalPages}
                            onPageChange={handlePageChange}
                        />
                    </div>
                )}
            </div>

            {/* Bulk action modals */}
            {selectedLeadsForAction.length > 0 && (
                <>
                    <AssignModal
                        isOpen={isAssignOpen}
                        onOpenChange={setIsAssignOpen}
                        selectedLeads={selectedLeadsForAction}
                        agents={agents}
                        onAssign={(agentId) => {
                            const agentName = agents.find((a) => a.id === agentId)?.name ?? null;
                            selectedIds.forEach((id) => {
                                updateLead(id, { assignedAgent: agentName, leadStatus: 'CONTACTED' });
                            });
                            setIsAssignOpen(false);
                            setSelectedIds([]);
                        }}
                    />
                    <WhatsAppSendModal
                        isOpen={isWhatsAppOpen}
                        onOpenChange={setIsWhatsAppOpen}
                        selectedLeads={selectedLeadsForAction}
                        templates={templates.filter((t) => t.approvalStatus === 'APPROVED')}
                        onSend={() => {
                            setIsWhatsAppOpen(false);
                            setSelectedIds([]);
                        }}
                    />
                </>
            )}

            {/* Bulk spam: use first selected lead for the single-lead MarkSpamModal */}
            {selectedLeadsForAction.length > 0 && selectedLeadsForAction[0] && (
                <MarkSpamModal
                    isOpen={isSpamOpen}
                    onOpenChange={setIsSpamOpen}
                    lead={selectedLeadsForAction[0]}
                    onConfirm={() => {
                        selectedIds.forEach((id) => {
                            updateLead(id, { isSpam: true, leadStatus: 'LOST' });
                        });
                        setIsSpamOpen(false);
                        setSelectedIds([]);
                    }}
                />
            )}

            {/* Activity slideout */}
            {activityLead && (
                <LeadActivitySlideout
                    isOpen={isActivityOpen}
                    onOpenChange={setIsActivityOpen}
                    lead={activityLead}
                    activities={leadActivities}
                />
            )}
        </div>
    );
};
