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

import { Tabs, TabList, Tab, TabPanel } from '@/components/application/tabs/tabs';
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 { Button } from '@/components/base/buttons/button';
import { useCampaigns } from '@/hooks/use-campaigns';
import { useLeads } from '@/hooks/use-leads';
import { formatCurrency, formatDateOnly } from '@/lib/format';

const detailTabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'leads', label: 'Leads' },
];

export const CampaignDetailPage = () => {
    const { id } = useParams<{ id: string }>();
    const [activeTab, setActiveTab] = useState<string>('overview');

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

    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]);

    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">
            {/* Hero header */}
            <CampaignHero campaign={campaign} />

            {/* KPI strip */}
            <KpiStrip campaign={campaign} />

            {/* Tabs */}
            <div className="px-7 pt-5">
                <Tabs selectedKey={activeTab} onSelectionChange={(key) => setActiveTab(String(key))}>
                    <TabList
                        type="underline"
                        size="sm"
                        items={detailTabs}
                    >
                        {(item) => <Tab key={item.id} id={item.id} label={item.label} />}
                    </TabList>

                    <TabPanel id="overview">
                        <div className="mt-5 grid grid-cols-1 gap-5 pb-7 xl:grid-cols-[1fr_340px]">
                            {/* Left: Ads list */}
                            <div className="space-y-3">
                                <h3 className="text-md font-bold text-primary">
                                    Ads ({campaignAds.length})
                                </h3>
                                {campaignAds.map((ad) => (
                                    <AdCard key={ad.id} ad={ad} />
                                ))}
                                {campaignAds.length === 0 && (
                                    <p className="py-8 text-center text-sm text-tertiary">
                                        No ads for this campaign.
                                    </p>
                                )}
                            </div>

                            {/* Right: Details + Funnel + Source */}
                            <div className="space-y-4">
                                {/* Campaign Details card */}
                                <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>

                                {/* Conversion Funnel */}
                                <ConversionFunnel campaign={campaign} leads={campaignLeads} />

                                {/* Source Breakdown */}
                                <SourceBreakdown leads={campaignLeads} />
                            </div>
                        </div>
                    </TabPanel>

                    <TabPanel id="leads">
                        <div className="mt-5 pb-7">
                            <div className="flex flex-col items-center justify-center rounded-xl border border-secondary bg-primary p-12 text-center">
                                <p className="text-md font-bold text-primary">
                                    {campaignLeads.length} lead{campaignLeads.length !== 1 ? 's' : ''} from this campaign
                                </p>
                                <p className="mt-1 text-sm text-tertiary">
                                    View the full leads table filtered by this campaign on the All Leads page.
                                </p>
                                <div className="mt-4">
                                    <Button color="primary" size="sm" href="/leads">
                                        Go to All Leads
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </TabPanel>
                </Tabs>
            </div>
        </div>
    );
};
