/**
 * Experiment Detail Page — Live Dashboard with Bayesian Statistics
 * Shows real-time metrics, variant comparisons, and statistical results.
 */

'use client';

import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  Play,
  Pause,
  Square,
  Trophy,
  AlertTriangle,
  Users,
  BarChart3,
  TrendingUp,
  Clock,
  Sparkles,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import type { ExperimentDoc, VariantDoc, ExperimentResult } from '@/lib/experiments-types';

interface ExperimentData {
  experiment: ExperimentDoc;
  variants: VariantDoc[];
  results?: ExperimentResult;
}

export default function ExperimentDetailPage() {
  const params = useParams();
  const experimentId = params.id as string;
  const [data, setData] = useState<ExperimentData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchExperimentData = useCallback(async () => {
    try {
      const [expResponse, resultsResponse] = await Promise.all([
        fetch(`/api/experiments/${experimentId}`),
        fetch(`/api/experiments/${experimentId}/results`),
      ]);

      if (!expResponse.ok) throw new Error('Failed to fetch experiment');

      const experiment = await expResponse.json();
      const results = resultsResponse.ok ? await resultsResponse.json() : null;

      setData({ experiment, variants: experiment.variants, results });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  }, [experimentId]);

  useEffect(() => {
    fetchExperimentData();
    const interval = setInterval(fetchExperimentData, 30000); // Auto-refresh every 30s
    return () => clearInterval(interval);
  }, [fetchExperimentData]);

  async function updateStatus(status: string) {
    try {
      const response = await fetch(`/api/experiments/${experimentId}/${status}`, {
        method: 'POST',
      });
      if (!response.ok) throw new Error('Failed to update status');
      fetchExperimentData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update');
    }
  }

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="container mx-auto py-8">
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>{error || 'Experiment not found'}</AlertDescription>
        </Alert>
      </div>
    );
  }

  const { experiment, variants, results } = data;
  const daysRunning = experiment.startedAt
    ? Math.floor((Date.now() - new Date(experiment.startedAt).getTime()) / (1000 * 60 * 60 * 24))
    : 0;

  return (
    <div className="container mx-auto py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" asChild>
            <Link href="/experiments">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{experiment.name}</h1>
            <p className="text-muted-foreground text-sm">{experiment.hypothesis}</p>
          </div>
        </div>
        <div className="flex gap-2">
          {experiment.status === 'draft' && (
            <Button onClick={() => updateStatus('start')}>
              <Play className="h-4 w-4 mr-2" />
              Start Experiment
            </Button>
          )}
          {experiment.status === 'running' && (
            <>
              <Button variant="outline" onClick={() => updateStatus('pause')}>
                <Pause className="h-4 w-4 mr-2" />
                Pause
              </Button>
              <Button variant="destructive" onClick={() => updateStatus('stop')}>
                <Square className="h-4 w-4 mr-2" />
                Stop
              </Button>
            </>
          )}
          {experiment.status === 'paused' && (
            <Button onClick={() => updateStatus('start')}>
              <Play className="h-4 w-4 mr-2" />
              Resume
            </Button>
          )}
        </div>
      </div>

      {/* Status Banner */}
      {results?.earlyStopped && (
        <Alert className="mb-6 bg-yellow-50 border-yellow-200">
          <AlertTriangle className="h-4 w-4 text-yellow-600" />
          <AlertTitle>Early Stopping Triggered</AlertTitle>
          <AlertDescription>{results.stopReason}</AlertDescription>
        </Alert>
      )}

      {results?.winnerVariantId && (
        <Alert className="mb-6 bg-green-50 border-green-200">
          <Trophy className="h-4 w-4 text-green-600" />
          <AlertTitle>Winner Found!</AlertTitle>
          <AlertDescription>
            Variant has {((results.winnerProbability || 0) * 100).toFixed(1)}% probability of being
            best. Recommended action: {results.statisticalSummary.recommendedAction}.
          </AlertDescription>
        </Alert>
      )}

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <StatCard
          title="Status"
          value={experiment.status}
          badge={getStatusBadge(experiment.status)}
        />
        <StatCard
          title="Participants"
          value={experiment.totalParticipants?.toLocaleString() || '0'}
          icon={<Users className="h-4 w-4" />}
        />
        <StatCard
          title="Days Running"
          value={daysRunning.toString()}
          icon={<Clock className="h-4 w-4" />}
        />
        <StatCard
          title="Total Events"
          value={experiment.totalEvents?.toLocaleString() || '0'}
          icon={<BarChart3 className="h-4 w-4" />}
        />
      </div>

      {/* Main Content */}
      <Tabs defaultValue="variants" className="space-y-6">
        <TabsList>
          <TabsTrigger value="variants">Variant Performance</TabsTrigger>
          <TabsTrigger value="statistics">Statistical Results</TabsTrigger>
          <TabsTrigger value="ai-insights">AI Insights</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
        </TabsList>

        <TabsContent value="variants" className="space-y-4">
          {variants.map(variant => (
            <VariantCard
              key={variant.id}
              variant={variant}
              isControl={variant.isControl}
              result={results?.variantResults.find(vr => vr.variantId === variant.id)}
            />
          ))}
        </TabsContent>

        <TabsContent value="statistics">
          <Card>
            <CardHeader>
              <CardTitle>Statistical Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {results ? (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="p-4 bg-muted rounded-lg">
                      <div className="text-sm text-muted-foreground mb-1">
                        Probability Any Beats Control
                      </div>
                      <div className="text-2xl font-bold">
                        {(results.statisticalSummary.probabilityAnyBeatsControl * 100).toFixed(1)}%
                      </div>
                    </div>
                    <div className="p-4 bg-muted rounded-lg">
                      <div className="text-sm text-muted-foreground mb-1">
                        Expected Loss If Shipped
                      </div>
                      <div className="text-2xl font-bold">
                        {(results.statisticalSummary.expectedLossIfShipped * 100).toFixed(2)}%
                      </div>
                    </div>
                    <div className="p-4 bg-muted rounded-lg">
                      <div className="text-sm text-muted-foreground mb-1">Recommended Action</div>
                      <div className="text-2xl font-bold capitalize">
                        {results.statisticalSummary.recommendedAction}
                      </div>
                    </div>
                  </div>

                  <div>
                    <h4 className="font-semibold mb-4">Variant Comparison</h4>
                    <div className="space-y-3">
                      {results.variantResults.map(vr => (
                        <div
                          key={vr.variantId}
                          className="flex items-center gap-4 p-3 border rounded-lg"
                        >
                          <div className="w-32 font-medium">{vr.variantName}</div>
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="text-sm text-muted-foreground">
                                P(beats control): {(vr.probabilityBeatsControl * 100).toFixed(1)}%
                              </span>
                            </div>
                            <Progress value={vr.probabilityBeatsControl * 100} className="h-2" />
                          </div>
                          <div className="w-24 text-right">
                            <div
                              className={`text-sm font-medium ${vr.expectedLiftPercent > 0 ? 'text-green-600' : 'text-red-600'}`}
                            >
                              {vr.expectedLiftPercent > 0 ? '+' : ''}
                              {vr.expectedLiftPercent.toFixed(1)}%
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              ) : (
                <p className="text-muted-foreground">No statistical results available yet.</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="ai-insights">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Sparkles className="h-5 w-5" />
                AI-Generated Insights
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <h4 className="font-semibold mb-2">Summary</h4>
                <p className="text-sm">
                  {results?.winnerVariantId
                    ? `The ${results.variantResults.find(v => v.variantId === results.winnerVariantId)?.variantName || 'winning variant'} significantly outperformed control with ${((results.winnerProbability || 0) * 100).toFixed(1)}% probability of superiority.`
                    : 'Results are still inconclusive. Consider running the experiment longer or testing more distinct variations.'}
                </p>
              </div>

              <div>
                <h4 className="font-semibold mb-2">Recommended Follow-up Experiments</h4>
                <ul className="space-y-2">
                  <li className="flex items-center gap-2 text-sm">
                    <TrendingUp className="h-4 w-4 text-muted-foreground" />
                    Test the winning variant against additional success metrics
                  </li>
                  <li className="flex items-center gap-2 text-sm">
                    <Users className="h-4 w-4 text-muted-foreground" />
                    Run a validation experiment with a new user cohort
                  </li>
                </ul>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="settings">
          <Card>
            <CardHeader>
              <CardTitle>Experiment Configuration</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium">Allocation Strategy</label>
                  <p className="text-muted-foreground capitalize">
                    {experiment.allocationStrategy}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">Target Traffic</label>
                  <p className="text-muted-foreground">{experiment.targetPercent}%</p>
                </div>
                <div>
                  <label className="text-sm font-medium">Primary Metric</label>
                  <p className="text-muted-foreground">{experiment.primaryMetric?.name}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">Min Sample Size</label>
                  <p className="text-muted-foreground">
                    {experiment.guardrails?.minSampleSizePerVariant} per variant
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">Max Duration</label>
                  <p className="text-muted-foreground">
                    {experiment.guardrails?.maxDurationDays} days
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">Auto Stop</label>
                  <p className="text-muted-foreground">
                    {experiment.guardrails?.autoStopEnabled ? 'Enabled' : 'Disabled'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function StatCard({
  title,
  value,
  badge,
  icon,
}: {
  title: string;
  value: string;
  badge?: React.ReactNode;
  icon?: React.ReactNode;
}) {
  return (
    <Card>
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-muted-foreground">{title}</span>
          {icon}
        </div>
        <div className="flex items-center gap-2">
          <span className="text-2xl font-bold capitalize">{value}</span>
          {badge}
        </div>
      </CardContent>
    </Card>
  );
}

function VariantCard({
  variant,
  isControl,
  result,
}: {
  variant: VariantDoc;
  isControl: boolean;
  result?: {
    probabilityBeatsControl: number;
    expectedLiftPercent: number;
    credibleInterval: { lower: number; mean: number; upper: number };
  };
}) {
  const conversionRate = variant.stats?.conversionRate || 0;
  const participants = variant.stats?.participants || 0;
  const events = variant.stats?.events || 0;

  return (
    <Card className={isControl ? 'border-blue-200' : ''}>
      <CardContent className="p-6">
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <h3 className="text-lg font-semibold">{variant.name}</h3>
              {isControl && (
                <Badge variant="outline" className="border-blue-300 text-blue-700">
                  Control
                </Badge>
              )}
              {variant.bayesianResults?.probabilityBeatsControl &&
                variant.bayesianResults.probabilityBeatsControl > 0.95 && (
                  <Badge className="bg-green-500 text-white">
                    <Trophy className="h-3 w-3 mr-1" />
                    Winner
                  </Badge>
                )}
            </div>
            <p className="text-sm text-muted-foreground">{variant.description}</p>
          </div>
          <div className="text-right">
            <div className="text-2xl font-bold">{(conversionRate * 100).toFixed(1)}%</div>
            <div className="text-sm text-muted-foreground">conversion rate</div>
          </div>
        </div>

        <div className="grid grid-cols-3 gap-4 mt-4 pt-4 border-t">
          <div>
            <div className="text-2xl font-semibold">{participants.toLocaleString()}</div>
            <div className="text-sm text-muted-foreground">participants</div>
          </div>
          <div>
            <div className="text-2xl font-semibold">{events.toLocaleString()}</div>
            <div className="text-sm text-muted-foreground">events</div>
          </div>
          <div>
            <div className="text-2xl font-semibold">
              {result ? `${(result.probabilityBeatsControl * 100).toFixed(0)}%` : '-'}
            </div>
            <div className="text-sm text-muted-foreground">P(beats control)</div>
          </div>
        </div>

        {result && result.credibleInterval && (
          <div className="mt-4 pt-4 border-t">
            <div className="text-sm text-muted-foreground mb-2">95% Credible Interval</div>
            <div className="flex items-center gap-2">
              <span className="text-sm">{(result.credibleInterval.lower * 100).toFixed(1)}%</span>
              <div className="flex-1 h-2 bg-muted rounded-full relative">
                <div
                  className="absolute h-full bg-primary rounded-full"
                  style={{
                    left: `${(result.credibleInterval.lower / result.credibleInterval.upper) * 50}%`,
                    width: `${((result.credibleInterval.upper - result.credibleInterval.lower) / result.credibleInterval.upper) * 50}%`,
                  }}
                />
              </div>
              <span className="text-sm">{(result.credibleInterval.upper * 100).toFixed(1)}%</span>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

function getStatusBadge(status: string) {
  const colors: Record<string, string> = {
    draft: 'bg-gray-500',
    running: 'bg-green-500',
    paused: 'bg-yellow-500',
    stopped: 'bg-red-500',
    completed: 'bg-blue-500',
  };
  return (
    <Badge className={`${colors[status] || colors.draft} text-white capitalize`}>{status}</Badge>
  );
}
