'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { PageHeader } from '@bytelyst/dashboard-components';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { LoadingSpinner, EmptyState } from '@bytelyst/dashboard-components';
import {
  Beaker,
  Plus,
  Play,
  Square,
  BarChart3,
  Target,
  Users,
  TrendingUp,
  AlertTriangle,
  CheckCircle2,
} from 'lucide-react';

interface Experiment {
  id: string;
  name: string;
  description: string;
  status: 'draft' | 'running' | 'paused' | 'stopped' | 'completed';
  totalParticipants: number;
  totalEvents: number;
  primaryMetric: {
    name: string;
    type: string;
  };
  allocationStrategy: string;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
}

interface Variant {
  id: string;
  name: string;
  isControl: boolean;
  currentAllocationPercent: number;
  stats: {
    participants: number;
    events: number;
    primaryMetricValue: number;
  };
  bayesianResults?: {
    probabilityBeatsControl: number;
    expectedLiftPercent: number;
  };
}

export default function ABTestingPage() {
  const router = useRouter();
  const [experiments, setExperiments] = useState<Experiment[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedExperiment, setSelectedExperiment] = useState<Experiment | null>(null);
  const [variants, setVariants] = useState<Variant[]>([]);

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

  const loadExperiments = async () => {
    try {
      const res = await fetch('/api/ab-testing/experiments');
      if (res.ok) {
        const data = await res.json();
        setExperiments(data);
      }
    } catch (error) {
      console.error('Failed to load experiments:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadVariants = async (experimentId: string) => {
    try {
      const res = await fetch(`/api/ab-testing/experiments/${experimentId}/variants`);
      if (res.ok) {
        const data = await res.json();
        setVariants(data);
      }
    } catch (error) {
      console.error('Failed to load variants:', error);
    }
  };

  const handleExperimentClick = (exp: Experiment) => {
    setSelectedExperiment(exp);
    loadVariants(exp.id);
  };

  const handleCreateExperiment = () => {
    router.push('/ops/ab-testing/new');
  };

  const handleStartExperiment = async (id: string) => {
    try {
      const res = await fetch(`/api/ab-testing/experiments/${id}/start`, { method: 'POST' });
      if (res.ok) {
        loadExperiments();
      }
    } catch (error) {
      console.error('Failed to start experiment:', error);
    }
  };

  const handleStopExperiment = async (id: string) => {
    try {
      const res = await fetch(`/api/ab-testing/experiments/${id}/stop`, { method: 'POST' });
      if (res.ok) {
        loadExperiments();
      }
    } catch (error) {
      console.error('Failed to stop experiment:', error);
    }
  };

  const getStatusBadge = (status: Experiment['status']) => {
    const variants = {
      draft: { variant: 'secondary', label: 'Draft' },
      running: { variant: 'default', label: 'Running' },
      paused: { variant: 'warning', label: 'Paused' },
      stopped: { variant: 'destructive', label: 'Stopped' },
      completed: { variant: 'success', label: 'Completed' },
    };
    const config = variants[status];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return <Badge variant={config.variant as any}>{config.label}</Badge>;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="A/B Testing"
        breadcrumbs={[{ label: 'Ops', href: '/ops' }, { label: 'A/B Testing' }]}
        actions={
          <Button onClick={handleCreateExperiment}>
            <Plus className="w-4 h-4 mr-2" />
            New Experiment
          </Button>
        }
      />

      <Tabs defaultValue="experiments">
        <TabsList>
          <TabsTrigger value="experiments">Experiments</TabsTrigger>
          <TabsTrigger value="results">Results</TabsTrigger>
          <TabsTrigger value="suggestions">AI Suggestions</TabsTrigger>
        </TabsList>

        <TabsContent value="experiments" className="space-y-4">
          {experiments.length === 0 ? (
            <EmptyState
              icon={<Beaker className="w-8 h-8 text-gray-500" />}
              title="No experiments yet"
              description="Create your first A/B test to start optimizing your product."
              action={{
                label: 'Create Experiment',
                onClick: handleCreateExperiment,
              }}
            />
          ) : (
            <div className="grid gap-4">
              {experiments.map(exp => (
                <Card
                  key={exp.id}
                  className={`cursor-pointer transition-colors ${
                    selectedExperiment?.id === exp.id ? 'border-blue-500' : 'hover:border-gray-400'
                  }`}
                  onClick={() => handleExperimentClick(exp)}
                >
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Beaker className="w-5 h-5 text-blue-500" />
                        <div>
                          <CardTitle className="text-lg">{exp.name}</CardTitle>
                          <p className="text-sm text-gray-500">{exp.description}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {getStatusBadge(exp.status)}
                        {exp.status === 'draft' && (
                          <Button
                            size="sm"
                            onClick={e => {
                              e.stopPropagation();
                              handleStartExperiment(exp.id);
                            }}
                          >
                            <Play className="w-4 h-4 mr-1" />
                            Start
                          </Button>
                        )}
                        {exp.status === 'running' && (
                          <Button
                            size="sm"
                            variant="destructive"
                            onClick={e => {
                              e.stopPropagation();
                              handleStopExperiment(exp.id);
                            }}
                          >
                            <Square className="w-4 h-4 mr-1" />
                            Stop
                          </Button>
                        )}
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-4 gap-4 text-sm">
                      <div>
                        <div className="text-gray-500">Participants</div>
                        <div className="font-medium">{exp.totalParticipants.toLocaleString()}</div>
                      </div>
                      <div>
                        <div className="text-gray-500">Events</div>
                        <div className="font-medium">{exp.totalEvents.toLocaleString()}</div>
                      </div>
                      <div>
                        <div className="text-gray-500">Primary Metric</div>
                        <div className="font-medium">{exp.primaryMetric.name}</div>
                      </div>
                      <div>
                        <div className="text-gray-500">Strategy</div>
                        <div className="font-medium capitalize">{exp.allocationStrategy}</div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          {selectedExperiment && variants.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle>Variant Performance</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {variants.map(variant => (
                    <div
                      key={variant.id}
                      className={`p-4 rounded-lg border ${
                        variant.isControl ? 'bg-gray-50 dark:bg-gray-900' : ''
                      }`}
                    >
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{variant.name}</span>
                          {variant.isControl && <Badge variant="secondary">Control</Badge>}
                        </div>
                        <div className="flex items-center gap-4 text-sm">
                          <div className="flex items-center gap-1">
                            <Users className="w-4 h-4 text-gray-500" />
                            <span>{variant.stats.participants.toLocaleString()}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Target className="w-4 h-4 text-gray-500" />
                            <span>{variant.stats.events.toLocaleString()}</span>
                          </div>
                        </div>
                      </div>

                      {variant.bayesianResults && !variant.isControl && (
                        <div className="grid grid-cols-2 gap-4 mt-3 pt-3 border-t">
                          <div>
                            <div className="text-sm text-gray-500">Probability vs Control</div>
                            <div
                              className={`text-lg font-semibold ${
                                variant.bayesianResults.probabilityBeatsControl > 0.95
                                  ? 'text-green-600'
                                  : variant.bayesianResults.probabilityBeatsControl > 0.8
                                    ? 'text-yellow-600'
                                    : 'text-gray-600'
                              }`}
                            >
                              {(variant.bayesianResults.probabilityBeatsControl * 100).toFixed(1)}%
                            </div>
                          </div>
                          <div>
                            <div className="text-sm text-gray-500">Expected Lift</div>
                            <div
                              className={`text-lg font-semibold ${
                                variant.bayesianResults.expectedLiftPercent > 0
                                  ? 'text-green-600'
                                  : 'text-red-600'
                              }`}
                            >
                              {variant.bayesianResults.expectedLiftPercent > 0 ? '+' : ''}
                              {variant.bayesianResults.expectedLiftPercent.toFixed(1)}%
                            </div>
                          </div>
                        </div>
                      )}

                      {variant.isControl && (
                        <div className="mt-3 pt-3 border-t text-sm text-gray-500">
                          Baseline: {variant.stats.primaryMetricValue.toFixed(2)}{' '}
                          {selectedExperiment.primaryMetric.name}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="results">
          <Card>
            <CardHeader>
              <CardTitle>Experiment Results</CardTitle>
            </CardHeader>
            <CardContent>
              <EmptyState
                icon={<BarChart3 className="w-8 h-8 text-gray-500" />}
                title="Select an experiment"
                description="Click on an experiment from the Experiments tab to view detailed results."
              />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="suggestions">
          <Card>
            <CardHeader>
              <CardTitle>AI-Generated Experiment Suggestions</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="p-4 border rounded-lg">
                  <div className="flex items-start gap-3">
                    <TrendingUp className="w-5 h-5 text-blue-500 mt-0.5" />
                    <div>
                      <h4 className="font-medium">Optimize Onboarding Flow</h4>
                      <p className="text-sm text-gray-500 mt-1">
                        Based on 34% drop-off at step 2, test a simplified onboarding with reduced
                        form fields.
                      </p>
                      <div className="flex items-center gap-2 mt-3">
                        <Badge variant="secondary">Predicted Impact: +15%</Badge>
                        <Badge variant="outline">Confidence: High</Badge>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="p-4 border rounded-lg">
                  <div className="flex items-start gap-3">
                    <AlertTriangle className="w-5 h-5 text-yellow-500 mt-0.5" />
                    <div>
                      <h4 className="font-medium">Test Error Recovery Flow</h4>
                      <p className="text-sm text-gray-500 mt-1">
                        12% of users encountering sync errors churn. Test an improved error message
                        with direct support contact.
                      </p>
                      <div className="flex items-center gap-2 mt-3">
                        <Badge variant="secondary">Predicted Impact: +8%</Badge>
                        <Badge variant="outline">Confidence: Medium</Badge>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="p-4 border rounded-lg">
                  <div className="flex items-start gap-3">
                    <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5" />
                    <div>
                      <h4 className="font-medium">Feature Flag Rollout</h4>
                      <p className="text-sm text-gray-500 mt-1">
                        New telemetry system shows 99.9% reliability. Ready for 50% rollout with
                        automated monitoring.
                      </p>
                      <div className="flex items-center gap-2 mt-3">
                        <Badge variant="secondary">Risk: Low</Badge>
                        <Badge variant="outline">Auto-Rollback: Enabled</Badge>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
