import { useMemo, useState } from 'react';
import { useParams } from 'react-router';

import { CampaignHero } from '@/components/campaigns/campaign-hero';
import { KpiStrip } from '@/components/campaigns/kpi-strip';
import { AdCard } from '@/components/campaigns/ad-card';
import { ConversionFunnel } from '@/components/campaigns/conversion-funnel';
import { SourceBreakdown } from '@/components/campaigns/source-breakdown';
import { BudgetBar } from '@/components/campaigns/budget-bar';
import { HealthIndicator } from '@/components/campaigns/health-indicator';
import { LeadTable } from '@/components/leads/lead-table';
import { LeadActivitySlideout } from '@/components/leads/lead-activity-slideout';
import { useCampaigns } from '@/hooks/use-campaigns';
import { useLeads } from '@/hooks/use-leads';
import { useData } from '@/providers/data-provider';
import { formatCurrency, formatDateOnly } from '@/lib/format';
import type { Lead } from '@/types/entities';

export const CampaignDetailPage = () => {
    const { id } = useParams<{ id: string }>();

    const { campaigns, ads } = useCampaigns();
    const { leads } = useLeads();
    const { leadActivities } = useData();

    const campaign = campaigns.find((c) => c.id === id);

    const campaignAds = useMemo(() => ads.filter((ad) => ad.campaignId === id), [ads, id]);
    const campaignLeads = useMemo(() => leads.filter((lead) => lead.campaignId === id), [leads, id]);

    const [selectedIds, setSelectedIds] = useState<string[]>([]);
    const [sortField, setSortField] = useState('createdAt');
    const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
    const [activityLead, setActivityLead] = useState<Lead | null>(null);

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

    const sortedLeads = useMemo(() => {
        const copy = [...campaignLeads];
        const dir = sortDirection === 'asc' ? 1 : -1;
        copy.sort((a, b) => {
            const av = (a as any)[sortField] ?? '';
            const bv = (b as any)[sortField] ?? '';
            if (av === bv) return 0;
            return av > bv ? dir : -dir;
        });
        return copy;
    }, [campaignLeads, sortField, sortDirection]);

    if (!campaign) {
        return (
            <div className="flex flex-1 items-center justify-center p-8">
                <p className="text-tertiary">Campaign not found.</p>
            </div>
        );
    }

    const formatDateShort = (dateStr: string | null) => {
        if (!dateStr) return '--';
        return formatDateOnly(dateStr);
    };

    return (
        <div className="flex flex-1 flex-col overflow-y-auto">
            <CampaignHero campaign={campaign} />

            <KpiStrip campaign={campaign} />

            {/* Main body: leads table on the left, campaign details + funnel + source on the right */}
            <div className="px-7 pt-5 pb-7">
                <div className="grid grid-cols-1 gap-5 xl:grid-cols-[1fr_340px]">
                    <div className="space-y-6">
                        <div>
                            <div className="mb-3 flex items-center justify-between">
                                <h3 className="text-md font-bold text-primary">
                                    Leads ({campaignLeads.length})
                                </h3>
                            </div>
                            {campaignLeads.length === 0 ? (
                                <div className="rounded-xl border border-secondary bg-primary p-8 text-center text-sm text-tertiary">
                                    No leads from this campaign yet.
                                </div>
                            ) : (
                                <LeadTable
                                    leads={sortedLeads}
                                    selectedIds={selectedIds}
                                    onSelectionChange={setSelectedIds}
                                    sortField={sortField}
                                    sortDirection={sortDirection}
                                    onSort={handleSort}
                                    onViewActivity={(lead) => setActivityLead(lead)}
                                />
                            )}
                        </div>

                        {campaignAds.length > 0 && (
                            <div>
                                <h3 className="mb-3 text-md font-bold text-primary">
                                    Ads ({campaignAds.length})
                                </h3>
                                <div className="space-y-3">
                                    {campaignAds.map((ad) => (
                                        <AdCard key={ad.id} ad={ad} />
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="space-y-4">
                        <div className="rounded-xl border border-secondary bg-primary p-4">
                            <h4 className="mb-3 text-sm font-bold text-primary">Campaign Details</h4>
                            <dl className="space-y-2 text-xs">
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Type</dt>
                                    <dd className="font-medium text-secondary">
                                        {campaign.campaignType?.replace(/_/g, ' ') ?? '--'}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Platform</dt>
                                    <dd className="font-medium text-secondary">
                                        {campaign.platform ?? '--'}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Start Date</dt>
                                    <dd className="font-medium text-secondary">
                                        {formatDateShort(campaign.startDate)}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">End Date</dt>
                                    <dd className="font-medium text-secondary">
                                        {formatDateShort(campaign.endDate)}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Budget</dt>
                                    <dd className="font-medium text-secondary">
                                        {campaign.budget
                                            ? formatCurrency(campaign.budget.amountMicros, campaign.budget.currencyCode)
                                            : '--'}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Impressions</dt>
                                    <dd className="font-medium text-secondary">
                                        {campaign.impressionCount?.toLocaleString('en-IN') ?? '--'}
                                    </dd>
                                </div>
                                <div className="flex justify-between">
                                    <dt className="text-quaternary">Clicks</dt>
                                    <dd className="font-medium text-secondary">
                                        {campaign.clickCount?.toLocaleString('en-IN') ?? '--'}
                                    </dd>
                                </div>
                            </dl>

                            <div className="mt-4 space-y-3">
                                <BudgetBar spent={campaign.amountSpent} budget={campaign.budget} />
                                <HealthIndicator campaign={campaign} leads={campaignLeads} />
                            </div>
                        </div>

                        <ConversionFunnel campaign={campaign} leads={campaignLeads} />

                        <SourceBreakdown leads={campaignLeads} />
                    </div>
                </div>
            </div>

            {activityLead && (
                <LeadActivitySlideout
                    isOpen={!!activityLead}
                    onOpenChange={(open) => !open && setActivityLead(null)}
                    lead={activityLead}
                    activities={leadActivities}
                />
            )}
        </div>
    );
};
