import { BarChart3, FileText, Lightbulb, PenTool, TrendingUp, Zap } from 'lucide-react';

import { Suspense } from 'react';

import DataCard from '@/Components/Shared/DataCard';
import { Badge } from '@/Components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { LazyLineChart } from '@/Components/ui/charts/LazyCharts';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { formatDate, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { type Branding } from '@/types';

interface Report {
  id: number;
  name: string;
  sections: string[];
  data: Record<string, unknown> | null;
}

interface Props {
  report: Report;
}

interface TrafficOverview {
  period: { start: string; end: string };
  metrics: {
    total_clicks: number;
    total_impressions: number;
    avg_ctr: number;
    avg_position: number;
  };
  daily_metrics: Array<{
    date: string;
    clicks: number;
    impressions: number;
    ctr: number;
    position: number;
  }>;
  comparison?: {
    period: { start: string; end: string };
    metrics: {
      total_clicks: number;
      total_impressions: number;
      avg_ctr: number;
      avg_position: number;
    };
    deltas: {
      clicks_delta_pct: number;
      impressions_delta_pct: number;
      ctr_delta_pct: number;
      position_delta_pct: number;
    };
  };
}

interface TopPage {
  page_url: string;
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
}

interface Finding {
  id: number;
  type: string;
  direction: string;
  page_url: string;
  segment_type: string | null;
  segment_value: string | null;
  metric_before: number;
  metric_after: number;
  delta_absolute: number;
  delta_percent: number;
  supporting_data: Record<string, unknown>;
}

interface Recommendation {
  id: number;
  page_url: string;
  action_type: string;
  lifecycle_status: string;
  impact_score: number;
  confidence_score: number;
  title: string;
  reasoning: string;
  evidence: Record<string, unknown>;
  applied_at: string | null;
}

interface AiDraft {
  id: number;
  recommendation_id: number;
  page_url: string;
  action_type: string;
  h1: string | null;
  meta_title: string | null;
  meta_description: string | null;
  token_usage: number;
  created_at: string;
}

interface RoiSnapshot {
  recommendation_id: number;
  page_url: string;
  action_type: string;
  days_tracked: number;
  baseline_clicks: number;
  current_clicks: number;
  clicks_delta_abs: number;
  clicks_delta_pct: number;
  baseline_ctr: number;
  current_ctr: number;
  ctr_delta_pct: number;
  baseline_position: number;
  current_position: number;
  position_delta_pct: number;
  is_significant: boolean;
}

export default function ReportPreview({ report }: Props) {
  const data = report.data;

  if (!data) {
    return null;
  }

  const branding = data.branding as Branding | null | undefined;
  const showRankwizBranding = !branding?.remove_rankwiz_branding;

  const hasSection = (section: string) => report.sections.includes(section);

  return (
    <div className="space-y-8" id="report-content">
      {/* Report Header */}
      <div className="rounded-lg border bg-card p-6 print:border-0 print:shadow-none">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold">{report.name}</h2>
            <p className="text-sm text-muted-foreground mt-1">
              Generated on {formatDate((data.generated_at as string) ?? '')}
            </p>
          </div>
          <div className="text-right">
            {!showRankwizBranding && branding?.logo_url ? (
              <img
                src={branding.logo_url}
                alt={branding.company_name ?? 'Company logo'}
                className="h-8 max-w-[200px] object-contain ml-auto"
              />
            ) : !showRankwizBranding && branding?.company_name ? (
              <p className="text-sm font-semibold" style={{ color: branding.primary_color }}>
                {branding.company_name}
              </p>
            ) : (
              <>
                <p className="text-sm font-medium">{(data.site as { name: string })?.name}</p>
                <p className="text-sm text-muted-foreground">
                  {(data.site as { domain: string })?.domain}
                </p>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Traffic Overview Section */}
      {hasSection('traffic_overview') && !!data.traffic_overview && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="h-5 w-5" />
              Traffic Overview
            </CardTitle>
            <CardDescription>
              Performance metrics from {(data.traffic_overview as TrafficOverview).period.start} to{' '}
              {(data.traffic_overview as TrafficOverview).period.end}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Metrics Cards */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <DataCard
                title="Total Clicks"
                value={formatNumber(
                  (data.traffic_overview as TrafficOverview).metrics.total_clicks,
                )}
                delta={
                  (data.traffic_overview as TrafficOverview).comparison?.deltas.clicks_delta_pct
                }
                deltaFormat="percent"
              />
              <DataCard
                title="Total Impressions"
                value={formatNumber(
                  (data.traffic_overview as TrafficOverview).metrics.total_impressions,
                )}
                delta={
                  (data.traffic_overview as TrafficOverview).comparison?.deltas
                    .impressions_delta_pct
                }
                deltaFormat="percent"
              />
              <DataCard
                title="Avg CTR"
                value={`${(data.traffic_overview as TrafficOverview).metrics.avg_ctr.toFixed(2)}%`}
                delta={(data.traffic_overview as TrafficOverview).comparison?.deltas.ctr_delta_pct}
                deltaFormat="percent"
              />
              <DataCard
                title="Avg Position"
                value={(data.traffic_overview as TrafficOverview).metrics.avg_position.toFixed(1)}
                delta={
                  (data.traffic_overview as TrafficOverview).comparison?.deltas.position_delta_pct
                }
                deltaFormat="percent"
              />
            </div>

            {/* Daily Metrics Chart */}
            {(data.traffic_overview as TrafficOverview).daily_metrics &&
              (data.traffic_overview as TrafficOverview).daily_metrics.length > 0 && (
                <div className="space-y-2">
                  <h3 className="text-sm font-medium">Daily Traffic Trend</h3>
                  <Suspense fallback={<Skeleton className="h-[250px] w-full" />}>
                    <LazyLineChart
                      data={(data.traffic_overview as TrafficOverview).daily_metrics}
                      xKey="date"
                      yKeys={['clicks', 'impressions']}
                      height={250}
                      showLegend
                      aria-label="Daily traffic trends showing clicks and impressions over time"
                    />
                  </Suspense>
                </div>
              )}

            {/* Comparison Period */}
            {(data.traffic_overview as TrafficOverview).comparison && (
              <div className="rounded-lg border bg-muted/30 p-4">
                <h3 className="text-sm font-medium mb-3">Comparison Period</h3>
                <p className="text-xs text-muted-foreground mb-2">
                  {(data.traffic_overview as TrafficOverview).comparison!.period.start} to{' '}
                  {(data.traffic_overview as TrafficOverview).comparison!.period.end}
                </p>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div>
                    <p className="text-xs text-muted-foreground">Clicks</p>
                    <p className="text-sm font-medium">
                      {formatNumber(
                        (data.traffic_overview as TrafficOverview).comparison!.metrics.total_clicks,
                      )}
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">Impressions</p>
                    <p className="text-sm font-medium">
                      {formatNumber(
                        (data.traffic_overview as TrafficOverview).comparison!.metrics
                          .total_impressions,
                      )}
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">CTR</p>
                    <p className="text-sm font-medium">
                      {(
                        data.traffic_overview as TrafficOverview
                      ).comparison!.metrics.avg_ctr.toFixed(2)}
                      %
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">Position</p>
                    <p className="text-sm font-medium">
                      {(
                        data.traffic_overview as TrafficOverview
                      ).comparison!.metrics.avg_position.toFixed(1)}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Top Pages Section */}
      {hasSection('top_pages') && !!data.top_pages && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5" />
              Top Performing Pages
            </CardTitle>
            <CardDescription>Pages with the highest traffic in the selected period</CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Page URL</TableHead>
                  <TableHead className="text-right">Clicks</TableHead>
                  <TableHead className="text-right">Impressions</TableHead>
                  <TableHead className="text-right">CTR</TableHead>
                  <TableHead className="text-right">Position</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(data.top_pages as TopPage[]).map((page, idx) => (
                  <TableRow key={idx}>
                    <TableCell className="max-w-md truncate font-mono text-xs">
                      {page.page_url}
                    </TableCell>
                    <TableCell className="text-right font-medium">
                      {formatNumber(page.clicks)}
                    </TableCell>
                    <TableCell className="text-right">{formatNumber(page.impressions)}</TableCell>
                    <TableCell className="text-right">{page.ctr.toFixed(2)}%</TableCell>
                    <TableCell className="text-right">{page.position.toFixed(1)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Findings Section */}
      {hasSection('findings') && !!data.findings && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Zap className="h-5 w-5" />
              Traffic Findings
            </CardTitle>
            <CardDescription>Significant traffic changes detected during analysis</CardDescription>
          </CardHeader>
          <CardContent>
            {(data.findings as { findings: Finding[] }).findings.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                No significant findings detected
              </p>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Page / Segment</TableHead>
                    <TableHead className="text-right">Before</TableHead>
                    <TableHead className="text-right">After</TableHead>
                    <TableHead className="text-right">Change</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {(data.findings as { findings: Finding[] }).findings
                    .slice(0, 20)
                    .map((finding) => (
                      <TableRow key={finding.id}>
                        <TableCell className="max-w-md">
                          <p className="font-mono text-xs truncate">{finding.page_url}</p>
                          {finding.segment_value && (
                            <Badge variant="outline" className="mt-1 text-xs">
                              {finding.segment_type}: {finding.segment_value}
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          {formatNumber(finding.metric_before)}
                        </TableCell>
                        <TableCell className="text-right">
                          {formatNumber(finding.metric_after)}
                        </TableCell>
                        <TableCell className="text-right">
                          <span
                            className={cn(
                              'font-medium',
                              finding.direction === 'winner'
                                ? 'text-green-600 dark:text-green-400'
                                : 'text-red-600 dark:text-red-400',
                            )}
                          >
                            {finding.delta_percent > 0 ? '+' : ''}
                            {finding.delta_percent.toFixed(1)}%
                          </span>
                        </TableCell>
                      </TableRow>
                    ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}

      {/* Recommendations Section */}
      {hasSection('recommendations') && !!data.recommendations && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Lightbulb className="h-5 w-5" />
              SEO Recommendations
            </CardTitle>
            <CardDescription>
              Actionable recommendations based on traffic analysis (
              {(data.recommendations as { total_count: number }).total_count} total)
            </CardDescription>
          </CardHeader>
          <CardContent>
            {(data.recommendations as { recommendations: Recommendation[] }).recommendations
              .length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                No recommendations available
              </p>
            ) : (
              <div className="space-y-4">
                {(data.recommendations as { recommendations: Recommendation[] }).recommendations
                  .slice(0, 10)
                  .map((rec) => (
                    <div key={rec.id} className="rounded-lg border p-4">
                      <div className="flex items-start justify-between gap-4">
                        <div className="flex-1 space-y-2">
                          <div className="flex items-center gap-2">
                            <Badge variant="outline">{rec.action_type.replace(/_/g, ' ')}</Badge>
                            <Badge
                              variant={
                                rec.lifecycle_status === 'applied'
                                  ? 'default'
                                  : rec.lifecycle_status === 'approved'
                                    ? 'secondary'
                                    : 'outline'
                              }
                            >
                              {rec.lifecycle_status}
                            </Badge>
                          </div>
                          <h3 className="font-medium">{rec.title}</h3>
                          <p className="text-sm text-muted-foreground font-mono">{rec.page_url}</p>
                          <p className="text-sm">{rec.reasoning}</p>
                        </div>
                        <div className="flex flex-col items-end gap-1">
                          <div className="text-right">
                            <p className="text-xs text-muted-foreground">Impact</p>
                            <p className="text-lg font-semibold">
                              {(rec.impact_score * 100).toFixed(0)}
                            </p>
                          </div>
                          <div className="text-right">
                            <p className="text-xs text-muted-foreground">Confidence</p>
                            <p className="text-sm">{(rec.confidence_score * 100).toFixed(0)}%</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* AI Drafts Section */}
      {hasSection('ai_drafts') && !!data.ai_drafts && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <PenTool className="h-5 w-5" />
              AI-Generated Content Drafts
            </CardTitle>
            <CardDescription>
              Content rewrites and optimizations (
              {(data.ai_drafts as { total_count: number }).total_count} total)
            </CardDescription>
          </CardHeader>
          <CardContent>
            {(data.ai_drafts as { drafts: AiDraft[] }).drafts.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                No AI drafts generated
              </p>
            ) : (
              <div className="space-y-4">
                {(data.ai_drafts as { drafts: AiDraft[] }).drafts.slice(0, 5).map((draft) => (
                  <div key={draft.id} className="rounded-lg border p-4">
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{draft.action_type.replace(/_/g, ' ')}</Badge>
                        <span className="text-xs text-muted-foreground">
                          {formatNumber(draft.token_usage)} tokens
                        </span>
                      </div>
                      <p className="text-sm font-mono text-muted-foreground">{draft.page_url}</p>
                      {draft.h1 && (
                        <div>
                          <p className="text-xs font-medium text-muted-foreground mb-1">H1</p>
                          <p className="text-sm">{draft.h1}</p>
                        </div>
                      )}
                      {draft.meta_title && (
                        <div>
                          <p className="text-xs font-medium text-muted-foreground mb-1">
                            Meta Title
                          </p>
                          <p className="text-sm">{draft.meta_title}</p>
                        </div>
                      )}
                      {draft.meta_description && (
                        <div>
                          <p className="text-xs font-medium text-muted-foreground mb-1">
                            Meta Description
                          </p>
                          <p className="text-sm text-muted-foreground">{draft.meta_description}</p>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ROI Metrics Section */}
      {hasSection('roi_metrics') && !!data.roi_metrics && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              ROI Tracking
            </CardTitle>
            <CardDescription>
              Performance impact of applied recommendations (
              {(data.roi_metrics as { total_applied: number }).total_applied} tracked)
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Summary Metrics */}
            <div className="grid grid-cols-3 gap-4">
              <DataCard
                title="Applied Recommendations"
                value={(data.roi_metrics as { total_applied: number }).total_applied}
              />
              <DataCard
                title="Total Clicks Gained"
                value={formatNumber(
                  (data.roi_metrics as { total_clicks_gained: number }).total_clicks_gained,
                )}
              />
              <DataCard
                title="Avg Performance"
                value={`${((data.roi_metrics as { avg_performance_multiplier: number }).avg_performance_multiplier * 100).toFixed(0)}%`}
              />
            </div>

            {/* ROI Snapshots */}
            {(data.roi_metrics as { snapshots: RoiSnapshot[] }).snapshots &&
              (data.roi_metrics as { snapshots: RoiSnapshot[] }).snapshots.length > 0 && (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Page</TableHead>
                      <TableHead className="text-right">Days Tracked</TableHead>
                      <TableHead className="text-right">Clicks Change</TableHead>
                      <TableHead className="text-right">CTR Change</TableHead>
                      <TableHead className="text-right">Position Change</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(data.roi_metrics as { snapshots: RoiSnapshot[] }).snapshots
                      .slice(0, 10)
                      .map((snapshot, idx) => (
                        <TableRow key={idx}>
                          <TableCell className="max-w-md">
                            <p className="font-mono text-xs truncate">{snapshot.page_url}</p>
                            <Badge variant="outline" className="mt-1 text-xs">
                              {snapshot.action_type.replace(/_/g, ' ')}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">{snapshot.days_tracked}</TableCell>
                          <TableCell className="text-right">
                            <span
                              className={cn(
                                'font-medium',
                                snapshot.clicks_delta_pct > 0
                                  ? 'text-green-600 dark:text-green-400'
                                  : snapshot.clicks_delta_pct < 0
                                    ? 'text-red-600 dark:text-red-400'
                                    : '',
                              )}
                            >
                              {snapshot.clicks_delta_pct > 0 ? '+' : ''}
                              {snapshot.clicks_delta_pct.toFixed(1)}%
                            </span>
                          </TableCell>
                          <TableCell className="text-right">
                            <span
                              className={cn(
                                'font-medium',
                                snapshot.ctr_delta_pct > 0
                                  ? 'text-green-600 dark:text-green-400'
                                  : snapshot.ctr_delta_pct < 0
                                    ? 'text-red-600 dark:text-red-400'
                                    : '',
                              )}
                            >
                              {snapshot.ctr_delta_pct > 0 ? '+' : ''}
                              {snapshot.ctr_delta_pct.toFixed(1)}%
                            </span>
                          </TableCell>
                          <TableCell className="text-right">
                            <span
                              className={cn(
                                'font-medium',
                                snapshot.position_delta_pct < 0
                                  ? 'text-green-600 dark:text-green-400'
                                  : snapshot.position_delta_pct > 0
                                    ? 'text-red-600 dark:text-red-400'
                                    : '',
                              )}
                            >
                              {snapshot.position_delta_pct > 0 ? '+' : ''}
                              {snapshot.position_delta_pct.toFixed(1)}%
                            </span>
                          </TableCell>
                        </TableRow>
                      ))}
                  </TableBody>
                </Table>
              )}
          </CardContent>
        </Card>
      )}

      {/* Branding Footer */}
      <div className="rounded-lg border bg-muted/30 p-4 text-center">
        <p className="text-sm text-muted-foreground">
          {showRankwizBranding ? (
            <>
              Report generated with{' '}
              <span className="font-semibold text-foreground">RankWiz AI</span>
            </>
          ) : (
            <>
              Report generated by{' '}
              <span className="font-semibold text-foreground">
                {branding?.company_name || 'Your Company'}
              </span>
            </>
          )}
        </p>
      </div>
    </div>
  );
}
