/**
 * Experiments List Page — Admin Dashboard
 * Shows all A/B experiments with status, metrics, and quick actions.
 */

'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  FlaskConical,
  Plus,
  Play,
  Pause,
  Square,
  BarChart3,
  Users,
  Clock,
  CheckCircle,
  AlertCircle,
  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 { Alert, AlertDescription } from '@/components/ui/alert';
import type { ExperimentDoc } from '@/lib/experiments-types';

const statusConfig: Record<string, { color: string; icon: typeof Play; label: string }> = {
  draft: { color: 'bg-gray-500', icon: AlertCircle, label: 'Draft' },
  running: { color: 'bg-green-500', icon: Play, label: 'Running' },
  paused: { color: 'bg-yellow-500', icon: Pause, label: 'Paused' },
  stopped: { color: 'bg-red-500', icon: Square, label: 'Stopped' },
  completed: { color: 'bg-blue-500', icon: CheckCircle, label: 'Completed' },
};

export default function ExperimentsPage() {
  const router = useRouter();
  const [experiments, setExperiments] = useState<ExperimentDoc[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [now] = useState(() => Date.now());

  useEffect(() => {
    fetchExperiments();
  }, []);

  async function fetchExperiments() {
    try {
      const response = await fetch('/api/experiments');
      if (!response.ok) throw new Error('Failed to fetch experiments');
      const data = await response.json();
      setExperiments(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  }

  const runningCount = experiments.filter(e => e.status === 'running').length;
  const completedCount = experiments.filter(e => e.status === 'completed').length;
  const totalParticipants = experiments.reduce((sum, e) => sum + (e.totalParticipants || 0), 0);

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

  return (
    <div className="container mx-auto py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold flex items-center gap-3">
            <FlaskConical className="h-8 w-8" />
            A/B Experiments
          </h1>
          <p className="text-muted-foreground mt-1">
            Intelligent experimentation with Bayesian statistics and auto-allocation
          </p>
        </div>
        <div className="flex gap-3">
          <Button variant="outline" asChild>
            <Link href="/experiments/suggestions">
              <Sparkles className="h-4 w-4 mr-2" />
              AI Suggestions
            </Link>
          </Button>
          <Button onClick={() => router.push('/experiments/new')}>
            <Plus className="h-4 w-4 mr-2" />
            New Experiment
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Experiments
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{experiments.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Running</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-green-600">{runningCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Completed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-blue-600">{completedCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Participants
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{totalParticipants.toLocaleString()}</div>
          </CardContent>
        </Card>
      </div>

      {error && (
        <Alert variant="destructive" className="mb-6">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Tabs */}
      <Tabs defaultValue="all" className="space-y-6">
        <TabsList>
          <TabsTrigger value="all">All ({experiments.length})</TabsTrigger>
          <TabsTrigger value="running">Running ({runningCount})</TabsTrigger>
          <TabsTrigger value="completed">Completed ({completedCount})</TabsTrigger>
          <TabsTrigger value="draft">
            Drafts ({experiments.filter(e => e.status === 'draft').length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="space-y-4">
          {experiments.map(experiment => (
            <ExperimentCard key={experiment.id} experiment={experiment} now={now} />
          ))}
          {experiments.length === 0 && (
            <div className="text-center py-12 text-muted-foreground">
              <FlaskConical className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>No experiments yet. Create your first experiment to get started.</p>
            </div>
          )}
        </TabsContent>

        <TabsContent value="running" className="space-y-4">
          {experiments
            .filter(e => e.status === 'running')
            .map(experiment => (
              <ExperimentCard key={experiment.id} experiment={experiment} now={now} />
            ))}
        </TabsContent>

        <TabsContent value="completed" className="space-y-4">
          {experiments
            .filter(e => e.status === 'completed')
            .map(experiment => (
              <ExperimentCard key={experiment.id} experiment={experiment} now={now} />
            ))}
        </TabsContent>

        <TabsContent value="draft" className="space-y-4">
          {experiments
            .filter(e => e.status === 'draft')
            .map(experiment => (
              <ExperimentCard key={experiment.id} experiment={experiment} now={now} />
            ))}
        </TabsContent>
      </Tabs>
    </div>
  );
}

function ExperimentCard({ experiment, now }: { experiment: ExperimentDoc; now: number }) {
  const status = statusConfig[experiment.status] || statusConfig.draft;
  const StatusIcon = status.icon;

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

  return (
    <Card className="hover:shadow-md transition-shadow">
      <CardContent className="p-6">
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <div className="flex items-center gap-3 mb-2">
              <h3 className="text-lg font-semibold">
                <Link href={`/experiments/${experiment.id}`} className="hover:underline">
                  {experiment.name}
                </Link>
              </h3>
              <Badge className={`${status.color} text-white`}>
                <StatusIcon className="h-3 w-3 mr-1" />
                {status.label}
              </Badge>
              {experiment.aiGeneratedHypothesis && (
                <Badge variant="outline">
                  <Sparkles className="h-3 w-3 mr-1" />
                  AI Generated
                </Badge>
              )}
            </div>
            <p className="text-muted-foreground text-sm mb-4">{experiment.hypothesis}</p>

            <div className="flex items-center gap-6 text-sm">
              <div className="flex items-center gap-2 text-muted-foreground">
                <BarChart3 className="h-4 w-4" />
                <span>Metric: {experiment.primaryMetric?.name || 'Not set'}</span>
              </div>
              <div className="flex items-center gap-2 text-muted-foreground">
                <Users className="h-4 w-4" />
                <span>{experiment.totalParticipants?.toLocaleString() || 0} participants</span>
              </div>
              {experiment.status === 'running' && (
                <div className="flex items-center gap-2 text-muted-foreground">
                  <Clock className="h-4 w-4" />
                  <span>{daysRunning} days running</span>
                </div>
              )}
            </div>
          </div>

          <div className="flex gap-2">
            <Button variant="outline" size="sm" asChild>
              <Link href={`/experiments/${experiment.id}`}>
                <BarChart3 className="h-4 w-4 mr-2" />
                Results
              </Link>
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
