import {
  AlertTriangle,
  BarChart3,
  Briefcase,
  CheckCircle2,
  Download,
  Plus,
  TrendingUp,
} from 'lucide-react';
import { toast } from 'sonner';

import { useEffect, useRef, useState } from 'react';

import { Head, Link, router } from '@inertiajs/react';

import PageHeader from '@/Components/layout/PageHeader';
import CrossSiteTrafficChart from '@/Components/Portfolio/CrossSiteTrafficChart';
import PortfolioMetricsCards from '@/Components/Portfolio/PortfolioMetricsCards';
import SiteComparisonTable from '@/Components/Portfolio/SiteComparisonTable';
import { Alert, AlertDescription, AlertTitle } from '@/Components/ui/alert';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { LoadingButton } from '@/Components/ui/loading-button';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { PORTFOLIO_VIEWED } from '@/lib/event-catalog';
import { formatNumber } from '@/lib/format';

interface SiteWithStats {
  id: number;
  name: string;
  domain: string;
  traffic_change_percent: number;
  pending_recommendations: number;
  last_analysis_date: string | null;
  attention_flags: {
    declining_traffic: boolean;
    stale_analysis: boolean;
    has_pending_recommendations: boolean;
  };
  latest_clicks: number;
  latest_impressions: number;
  health_score: number | null;
  previous_health_score: number | null;
  health_status: string | null;
  health_trend: string | null;
  recommendations_applied_count: number;
  clicks_gained: number;
  roi_trend: 'up' | 'flat' | 'down';
  active_alerts_count: number;
}

interface AgencyStats {
  total_recommendations_applied: number;
  total_clicks_gained: number;
  sites_with_positive_roi: number;
  sites_with_active_alerts: number;
}

interface AgencyStatCardProps {
  icon: React.ReactNode;
  label: string;
  value: string | number;
  description: string;
}

function AgencyStatCard({ icon, label, value, description }: AgencyStatCardProps) {
  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex items-start gap-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
            {icon}
          </div>
          <div>
            <p className="text-sm text-muted-foreground">{label}</p>
            <p className="text-2xl font-bold">{value}</p>
            <p className="text-xs text-muted-foreground">{description}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

interface PortfolioPageProps {
  aggregate_metrics: {
    total_clicks: number;
    total_impressions: number;
    average_ctr: number;
  };
  agency_stats: AgencyStats;
  sites_with_stats: SiteWithStats[];
  time_series_data: Record<string, unknown>[];
}

export default function Portfolio({
  aggregate_metrics: aggregateMetrics,
  agency_stats: agencyStats,
  sites_with_stats: sitesWithStats,
  time_series_data: timeSeriesData,
}: PortfolioPageProps) {
  useEffect(() => {
    trackEvent(PORTFOLIO_VIEWED);
  }, []);

  const hasTwoOrMoreSites = sitesWithStats.length >= 2;

  const [bulkAction, setBulkAction] = useState<'analyze' | 'report' | null>(null);
  // Synchronous lock — `setBulkAction` schedules a render so the disabled state on
  // the buttons doesn't reach the DOM until React commits. The ref blocks the
  // double-submit race that opens between a rapid second click and that commit.
  const bulkActionLockRef = useRef(false);
  const isBulkActionInFlight = bulkAction !== null;

  const handleBulkAnalyze = () => {
    if (bulkActionLockRef.current) return;
    bulkActionLockRef.current = true;
    setBulkAction('analyze');
    router.post(
      route('portfolio.bulk-analyze'),
      {},
      {
        onSuccess: () => toast.success('Bulk analysis queued for all sites.'),
        onError: () =>
          toast.error("Couldn't queue bulk analysis — check your connection and try again."),
        onFinish: () => {
          setBulkAction(null);
          bulkActionLockRef.current = false;
        },
      },
    );
  };

  const handleBulkReport = () => {
    if (bulkActionLockRef.current) return;
    bulkActionLockRef.current = true;
    setBulkAction('report');
    router.post(
      route('portfolio.bulk-report'),
      {},
      {
        onSuccess: () => toast.success('Bulk report generation queued.'),
        onError: () =>
          toast.error("Couldn't queue bulk reports — check your connection and try again."),
        onFinish: () => {
          setBulkAction(null);
          bulkActionLockRef.current = false;
        },
      },
    );
  };

  const handleExportCsv = () => {
    window.location.href = route('portfolio.export');
  };

  return (
    <DashboardLayout>
      <Head title="Portfolio Overview" />

      <PageHeader title="Portfolio Overview" subtitle="Aggregate insights across all your sites" />

      <div className="container py-8">
        {/* Single site warning */}
        {sitesWithStats.length === 1 && (
          <Alert className="mb-8 border-primary/50 bg-primary/5">
            <Briefcase className="h-5 w-5 text-primary" />
            <AlertTitle className="text-lg font-semibold">
              Portfolio View Requires Multiple Sites
            </AlertTitle>
            <AlertDescription className="mt-2">
              <p className="mb-3 text-muted-foreground">
                The portfolio dashboard provides aggregate insights across multiple sites. You
                currently have 1 site. Add at least one more site to unlock portfolio-level
                analytics.
              </p>
              <Button asChild>
                <Link href="/sites/create">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Site
                </Link>
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {/* Full portfolio view — 2+ sites */}
        {hasTwoOrMoreSites && (
          <>
            {/* Agency Performance Summary */}
            <div className="mb-8">
              <div className="mb-4 flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-semibold">Agency Performance</h2>
                  <p className="text-sm text-muted-foreground">ROI proof across all client sites</p>
                </div>
                <Button variant="outline" size="sm" onClick={handleExportCsv}>
                  <Download className="mr-2 h-4 w-4" />
                  Export ROI CSV
                </Button>
              </div>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <AgencyStatCard
                  icon={<CheckCircle2 className="h-5 w-5" />}
                  label="Recommendations Applied"
                  value={agencyStats.total_recommendations_applied}
                  description="Across all sites"
                />
                <AgencyStatCard
                  icon={<TrendingUp className="h-5 w-5" />}
                  label="Total Clicks Gained"
                  value={formatNumber(agencyStats.total_clicks_gained)}
                  description="From applied recommendations"
                />
                <AgencyStatCard
                  icon={<BarChart3 className="h-5 w-5" />}
                  label="Sites with Positive ROI"
                  value={agencyStats.sites_with_positive_roi}
                  description={`of ${sitesWithStats.length} total sites`}
                />
                <AgencyStatCard
                  icon={<AlertTriangle className="h-5 w-5" />}
                  label="Sites with Active Alerts"
                  value={agencyStats.sites_with_active_alerts}
                  description="Require attention"
                />
              </div>
            </div>

            {/* Portfolio Metrics Cards */}
            <div className="mb-8">
              <PortfolioMetricsCards
                totalClicks={aggregateMetrics.total_clicks}
                totalImpressions={aggregateMetrics.total_impressions}
                averageCtr={aggregateMetrics.average_ctr}
              />
            </div>

            {/* Bulk Operations */}
            <Card className="mb-8">
              <CardHeader>
                <CardTitle>Bulk Operations</CardTitle>
                <CardDescription>
                  Run analysis or generate reports for all client sites at once
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-3">
                  <LoadingButton
                    variant="outline"
                    onClick={handleBulkAnalyze}
                    loading={bulkAction === 'analyze'}
                    disabled={isBulkActionInFlight}
                    loadingText="Queueing analysis…"
                  >
                    Run Analysis on All Sites
                  </LoadingButton>
                  <LoadingButton
                    variant="outline"
                    onClick={handleBulkReport}
                    loading={bulkAction === 'report'}
                    disabled={isBulkActionInFlight}
                    loadingText="Queueing reports…"
                  >
                    Generate Reports for All Sites
                  </LoadingButton>
                </div>
              </CardContent>
            </Card>

            {/* Site Comparison Table */}
            <Card className="mb-8">
              <CardHeader>
                <CardTitle>Site Comparison</CardTitle>
                <CardDescription>
                  Compare traffic changes, ROI, and pending actions across all your sites
                </CardDescription>
              </CardHeader>
              <CardContent>
                <SiteComparisonTable sites={sitesWithStats} />
              </CardContent>
            </Card>

            {/* Cross-Site Traffic Chart */}
            <Card>
              <CardHeader>
                <CardTitle>Traffic Trends</CardTitle>
                <CardDescription>
                  Performance trends across all sites over the last 30 days
                </CardDescription>
              </CardHeader>
              <CardContent>
                {timeSeriesData.length > 0 ? (
                  <CrossSiteTrafficChart timeSeriesData={timeSeriesData} sites={sitesWithStats} />
                ) : (
                  <EmptyState
                    icon={Briefcase}
                    title="No Traffic Data Available"
                    description="Sync your sites with Google Search Console to see traffic trends"
                    size="sm"
                    animated={false}
                  />
                )}
              </CardContent>
            </Card>
          </>
        )}

        {/* Empty state — no sites */}
        {sitesWithStats.length === 0 && (
          <EmptyState
            icon={Briefcase}
            title="No Sites Found"
            description="Add your first site to start building your portfolio"
            action={
              <Button asChild>
                <Link href="/sites/create">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Your First Site
                </Link>
              </Button>
            }
          />
        )}
      </div>
    </DashboardLayout>
  );
}
