/**
 * New Experiment Wizard — Admin Dashboard
 * Multi-step wizard for creating experiments with AI suggestions.
 */

'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  ArrowRight,
  Sparkles,
  FlaskConical,
  Target,
  Sliders,
  Check,
  Lightbulb,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Progress } from '@/components/ui/progress';
import type {
  AllocationStrategy,
  CreateExperimentInput,
  ExperimentSuggestion,
  MetricType,
  PrimaryMetric,
} from '@/lib/experiments-types';

const steps = [
  { id: 'hypothesis', title: 'Hypothesis', icon: Lightbulb },
  { id: 'variants', title: 'Variants', icon: FlaskConical },
  { id: 'metrics', title: 'Metrics', icon: Target },
  { id: 'targeting', title: 'Targeting', icon: Sliders },
  { id: 'review', title: 'Review', icon: Check },
];

export default function NewExperimentPage() {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [aiSuggestions, setAiSuggestions] = useState<ExperimentSuggestion[]>([]);

  const [formData, setFormData] = useState<Partial<CreateExperimentInput>>({
    name: '',
    description: '',
    hypothesis: '',
    variants: [
      {
        key: 'control',
        name: 'Control',
        description: 'Current implementation',
        isControl: true,
        flagConfig: {},
      },
      { key: 'variant_a', name: 'Variant A', description: '', isControl: false, flagConfig: {} },
    ],
    allocationStrategy: 'random',
    targetPercent: 100,
    targeting: {},
    primaryMetric: {
      name: 'conversion',
      type: 'conversion',
      eventName: 'purchase',
      aggregation: 'count',
      direction: 'increase',
      minimumDetectableEffect: 5,
    },
    guardrails: {
      minSampleSizePerVariant: 100,
      maxDurationDays: 30,
      autoStopEnabled: true,
      winnerThreshold: 95,
      requireApprovalFor: 'none',
    },
  });

  async function loadAiSuggestions() {
    try {
      const response = await fetch('/api/ab-testing/suggestions');
      if (response.ok) {
        const data = await response.json();
        setAiSuggestions(data.slice(0, 3));
      }
    } catch {
      // Silently fail - AI suggestions are optional
    }
  }

  async function handleSubmit() {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/ab-testing/experiments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to create experiment');
      }

      const experiment = await response.json();
      router.push(`/experiments/${experiment.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create experiment');
      setLoading(false);
    }
  }

  function applyAiSuggestion(suggestion: ExperimentSuggestion) {
    setFormData(prev => ({
      ...prev,
      name: prev.name || `Experiment: ${suggestion.hypothesis.primary.slice(0, 50)}...`,
      hypothesis: suggestion.hypothesis.primary,
      description: suggestion.hypothesis.alternatives[0] || '',
      primaryMetric: suggestion.suggestedMetrics[0] || prev.primaryMetric,
    }));
  }

  const progress = ((currentStep + 1) / steps.length) * 100;

  return (
    <div className="container mx-auto py-8 max-w-4xl">
      {/* Header */}
      <div className="flex items-center gap-4 mb-8">
        <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">Create New Experiment</h1>
          <p className="text-muted-foreground text-sm">
            Step {currentStep + 1} of {steps.length}: {steps[currentStep].title}
          </p>
        </div>
      </div>

      {/* Progress */}
      <Progress value={progress} className="mb-8" />

      {/* Step Indicators */}
      <div className="flex justify-between mb-8">
        {steps.map((step, index) => {
          const Icon = step.icon;
          const isActive = index === currentStep;
          const isCompleted = index < currentStep;

          return (
            <div
              key={step.id}
              className={`flex flex-col items-center ${
                isActive ? 'text-primary' : isCompleted ? 'text-green-600' : 'text-muted-foreground'
              }`}
            >
              <div
                className={`w-10 h-10 rounded-full flex items-center justify-center mb-2 ${
                  isActive
                    ? 'bg-primary text-white'
                    : isCompleted
                      ? 'bg-green-100 text-green-600'
                      : 'bg-muted'
                }`}
              >
                <Icon className="h-5 w-5" />
              </div>
              <span className="text-xs font-medium">{step.title}</span>
            </div>
          );
        })}
      </div>

      {/* Error */}
      {error && (
        <Alert variant="destructive" className="mb-6">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Step Content */}
      <Card className="mb-6">
        <CardContent className="p-6">
          {currentStep === 0 && (
            <HypothesisStep
              formData={formData}
              setFormData={setFormData}
              aiSuggestions={aiSuggestions}
              onLoadSuggestions={loadAiSuggestions}
              onApplySuggestion={applyAiSuggestion}
            />
          )}
          {currentStep === 1 && <VariantsStep formData={formData} setFormData={setFormData} />}
          {currentStep === 2 && <MetricsStep formData={formData} setFormData={setFormData} />}
          {currentStep === 3 && <TargetingStep formData={formData} setFormData={setFormData} />}
          {currentStep === 4 && <ReviewStep formData={formData} />}
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button
          variant="outline"
          onClick={() => setCurrentStep(Math.max(0, currentStep - 1))}
          disabled={currentStep === 0}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Previous
        </Button>

        {currentStep < steps.length - 1 ? (
          <Button onClick={() => setCurrentStep(currentStep + 1)}>
            Next
            <ArrowRight className="h-4 w-4 ml-2" />
          </Button>
        ) : (
          <Button onClick={handleSubmit} disabled={loading}>
            {loading ? (
              <>
                <div className="animate-spin mr-2 h-4 w-4 border-2 border-current border-t-transparent rounded-full" />
                Creating...
              </>
            ) : (
              <>
                <Check className="h-4 w-4 mr-2" />
                Create Experiment
              </>
            )}
          </Button>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Step Components
// ─────────────────────────────────────────────────────────────────────────────

function HypothesisStep({
  formData,
  setFormData,
  aiSuggestions,
  onLoadSuggestions,
  onApplySuggestion,
}: {
  formData: Partial<CreateExperimentInput>;
  setFormData: (data: Partial<CreateExperimentInput>) => void;
  aiSuggestions: ExperimentSuggestion[];
  onLoadSuggestions: () => void;
  onApplySuggestion: (s: ExperimentSuggestion) => void;
}) {
  return (
    <div className="space-y-6">
      <div>
        <Label htmlFor="name">Experiment Name</Label>
        <Input
          id="name"
          value={formData.name}
          onChange={e => setFormData({ ...formData, name: e.target.value })}
          placeholder="e.g., Homepage Button Color Test"
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="hypothesis">Hypothesis</Label>
        <Textarea
          id="hypothesis"
          value={formData.hypothesis}
          onChange={e => setFormData({ ...formData, hypothesis: e.target.value })}
          placeholder="e.g., Changing the CTA button to green will increase click-through rate by 15% because green signals 'go' to users..."
          className="mt-1"
          rows={3}
        />
        <p className="text-sm text-muted-foreground mt-1">
          State what you expect to change and why.
        </p>
      </div>

      <div>
        <Label htmlFor="description">Description (optional)</Label>
        <Textarea
          id="description"
          value={formData.description}
          onChange={e => setFormData({ ...formData, description: e.target.value })}
          placeholder="Additional context about this experiment..."
          className="mt-1"
          rows={2}
        />
      </div>

      {/* AI Suggestions */}
      <div className="border rounded-lg p-4 bg-muted/50">
        <div className="flex items-center gap-2 mb-3">
          <Sparkles className="h-4 w-4 text-primary" />
          <h4 className="font-medium">AI-Generated Suggestions</h4>
          <Button variant="ghost" size="sm" onClick={onLoadSuggestions} className="ml-auto">
            Load Suggestions
          </Button>
        </div>

        {aiSuggestions.length > 0 ? (
          <div className="space-y-3">
            {aiSuggestions.map((suggestion, index) => (
              <Card
                key={index}
                className="cursor-pointer hover:border-primary"
                onClick={() => onApplySuggestion(suggestion)}
              >
                <CardContent className="p-3">
                  <p className="text-sm font-medium line-clamp-2">
                    {suggestion.hypothesis.primary}
                  </p>
                  <div className="flex gap-2 mt-2">
                    <Badge variant="outline" className="text-xs">
                      Impact: {suggestion.hypothesis.impactScore}/100
                    </Badge>
                    <Badge variant="outline" className="text-xs">
                      Difficulty: {suggestion.hypothesis.difficultyScore}/100
                    </Badge>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">
            Click &quot;Load Suggestions&quot; to see AI-generated experiment ideas based on your
            product usage patterns.
          </p>
        )}
      </div>
    </div>
  );
}

function VariantsStep({
  formData,
  setFormData,
}: {
  formData: Partial<CreateExperimentInput>;
  setFormData: (data: Partial<CreateExperimentInput>) => void;
}) {
  const variants = formData.variants || [];

  function addVariant() {
    const newVariant = {
      key: `variant_${String.fromCharCode(98 + variants.length - 1)}`,
      name: `Variant ${String.fromCharCode(65 + variants.length - 1)}`,
      description: '',
      isControl: false,
      flagConfig: {},
    };
    setFormData({ ...formData, variants: [...variants, newVariant] });
  }

  function updateVariant(index: number, updates: Partial<(typeof variants)[0]>) {
    const updated = variants.map((v, i) => (i === index ? { ...v, ...updates } : v));
    setFormData({ ...formData, variants: updated });
  }

  function removeVariant(index: number) {
    if (variants.length <= 2) return; // Minimum 2 variants
    const updated = variants.filter((_, i) => i !== index);
    setFormData({ ...formData, variants: updated });
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="font-medium">Experiment Variants</h3>
        <Button variant="outline" size="sm" onClick={addVariant}>
          Add Variant
        </Button>
      </div>

      {variants.map((variant, index) => (
        <Card key={index} className={variant.isControl ? 'border-blue-200' : ''}>
          <CardContent className="p-4 space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                {variant.isControl ? (
                  <Badge variant="outline" className="border-blue-300 text-blue-700">
                    Control
                  </Badge>
                ) : (
                  <Badge variant="outline">Variant</Badge>
                )}
              </div>
              {!variant.isControl && (
                <Button variant="ghost" size="sm" onClick={() => removeVariant(index)}>
                  Remove
                </Button>
              )}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Name</Label>
                <Input
                  value={variant.name}
                  onChange={e => updateVariant(index, { name: e.target.value })}
                  className="mt-1"
                />
              </div>
              <div>
                <Label>Key (slug)</Label>
                <Input
                  value={variant.key}
                  onChange={e => updateVariant(index, { key: e.target.value })}
                  className="mt-1"
                  disabled={variant.isControl}
                />
              </div>
            </div>

            <div>
              <Label>Description</Label>
              <Input
                value={variant.description}
                onChange={e => updateVariant(index, { description: e.target.value })}
                placeholder="What makes this variant different?"
                className="mt-1"
              />
            </div>
          </CardContent>
        </Card>
      ))}

      <p className="text-sm text-muted-foreground">
        You need at least 2 variants: a Control (current implementation) and at least one Treatment
        variant.
      </p>
    </div>
  );
}

function MetricsStep({
  formData,
  setFormData,
}: {
  formData: Partial<CreateExperimentInput>;
  setFormData: (data: Partial<CreateExperimentInput>) => void;
}) {
  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Primary Metric</CardTitle>
          <CardDescription>The main metric that determines experiment success.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Metric Name</Label>
              <Input
                value={formData.primaryMetric?.name}
                onChange={e =>
                  setFormData({
                    ...formData,
                    primaryMetric: { ...formData.primaryMetric!, name: e.target.value },
                  })
                }
                className="mt-1"
              />
            </div>
            <div>
              <Label>Event Name</Label>
              <Input
                value={formData.primaryMetric?.eventName}
                onChange={e =>
                  setFormData({
                    ...formData,
                    primaryMetric: { ...formData.primaryMetric!, eventName: e.target.value },
                  })
                }
                placeholder="e.g., purchase_clicked"
                className="mt-1"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Metric Type</Label>
              <Select
                value={formData.primaryMetric?.type}
                onValueChange={v =>
                  setFormData({
                    ...formData,
                    primaryMetric: { ...formData.primaryMetric!, type: v as MetricType },
                  })
                }
              >
                <SelectTrigger className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="conversion">Conversion (binary)</SelectItem>
                  <SelectItem value="count">Count (integer)</SelectItem>
                  <SelectItem value="duration">Duration (time)</SelectItem>
                  <SelectItem value="revenue">Revenue (monetary)</SelectItem>
                  <SelectItem value="custom">Custom (numeric)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Direction</Label>
              <Select
                value={formData.primaryMetric?.direction}
                onValueChange={v =>
                  setFormData({
                    ...formData,
                    primaryMetric: {
                      ...formData.primaryMetric!,
                      direction: v as PrimaryMetric['direction'],
                    },
                  })
                }
              >
                <SelectTrigger className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="increase">Higher is better</SelectItem>
                  <SelectItem value="decrease">Lower is better</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Allocation Strategy</CardTitle>
          <CardDescription>How traffic is distributed between variants.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Select
            value={formData.allocationStrategy}
            onValueChange={v =>
              setFormData({ ...formData, allocationStrategy: v as AllocationStrategy })
            }
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="random">Random (fixed 50/50)</SelectItem>
              <SelectItem value="thompson">Thompson Sampling (multi-armed bandit)</SelectItem>
              <SelectItem value="epsilon_greedy">Epsilon-Greedy (explore/exploit)</SelectItem>
              <SelectItem value="ucb">Upper Confidence Bound (UCB1)</SelectItem>
            </SelectContent>
          </Select>

          <div>
            <Label>Target Traffic %</Label>
            <Input
              type="number"
              min={1}
              max={100}
              value={formData.targetPercent}
              onChange={e => setFormData({ ...formData, targetPercent: parseInt(e.target.value) })}
              className="mt-1"
            />
            <p className="text-sm text-muted-foreground mt-1">
              Percentage of eligible users to include in this experiment.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function TargetingStep({
  formData,
  setFormData,
}: {
  formData: Partial<CreateExperimentInput>;
  setFormData: (data: Partial<CreateExperimentInput>) => void;
}) {
  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Audience Targeting</CardTitle>
          <CardDescription>Limit this experiment to specific user segments.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label>Platforms</Label>
            <div className="flex gap-2 mt-1">
              {['ios', 'android', 'web'].map(platform => (
                <Badge
                  key={platform}
                  variant={
                    formData.targeting?.platforms?.includes(platform) ? 'default' : 'outline'
                  }
                  className="cursor-pointer capitalize"
                  onClick={() => {
                    const current = formData.targeting?.platforms || [];
                    const updated = current.includes(platform)
                      ? current.filter(p => p !== platform)
                      : [...current, platform];
                    setFormData({
                      ...formData,
                      targeting: { ...formData.targeting, platforms: updated },
                    });
                  }}
                >
                  {platform}
                </Badge>
              ))}
            </div>
          </div>

          <div>
            <Label>User Segments</Label>
            <div className="flex gap-2 mt-1">
              {['free', 'pro', 'enterprise'].map(segment => (
                <Badge
                  key={segment}
                  variant={
                    formData.targeting?.userSegments?.includes(segment) ? 'default' : 'outline'
                  }
                  className="cursor-pointer capitalize"
                  onClick={() => {
                    const current = formData.targeting?.userSegments || [];
                    const updated = current.includes(segment)
                      ? current.filter(s => s !== segment)
                      : [...current, segment];
                    setFormData({
                      ...formData,
                      targeting: { ...formData.targeting, userSegments: updated },
                    });
                  }}
                >
                  {segment}
                </Badge>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Guardrails & Safety</CardTitle>
          <CardDescription>Configure automatic stopping rules.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Min Sample Size per Variant</Label>
              <Input
                type="number"
                value={formData.guardrails?.minSampleSizePerVariant}
                onChange={e =>
                  setFormData({
                    ...formData,
                    guardrails: {
                      ...formData.guardrails!,
                      minSampleSizePerVariant: parseInt(e.target.value),
                    },
                  })
                }
                className="mt-1"
              />
            </div>
            <div>
              <Label>Max Duration (days)</Label>
              <Input
                type="number"
                value={formData.guardrails?.maxDurationDays}
                onChange={e =>
                  setFormData({
                    ...formData,
                    guardrails: {
                      ...formData.guardrails!,
                      maxDurationDays: parseInt(e.target.value),
                    },
                  })
                }
                className="mt-1"
              />
            </div>
          </div>

          <div>
            <Label>Winner Threshold (%)</Label>
            <Input
              type="number"
              min={80}
              max={99}
              value={formData.guardrails?.winnerThreshold}
              onChange={e =>
                setFormData({
                  ...formData,
                  guardrails: {
                    ...formData.guardrails!,
                    winnerThreshold: parseInt(e.target.value),
                  },
                })
              }
              className="mt-1"
            />
            <p className="text-sm text-muted-foreground mt-1">
              Probability threshold for declaring a winner (95% recommended).
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function ReviewStep({ formData }: { formData: Partial<CreateExperimentInput> }) {
  return (
    <div className="space-y-6">
      <h3 className="font-medium">Review Experiment Configuration</h3>

      <div className="space-y-4">
        <ReviewItem label="Name" value={formData.name} />
        <ReviewItem label="Hypothesis" value={formData.hypothesis} />
        <ReviewItem label="Variants" value={`${formData.variants?.length || 0} variants`} />
        <ReviewItem label="Primary Metric" value={formData.primaryMetric?.name} />
        <ReviewItem label="Allocation Strategy" value={formData.allocationStrategy} />
        <ReviewItem label="Target Traffic" value={`${formData.targetPercent}%`} />
        <ReviewItem
          label="Auto Stop"
          value={formData.guardrails?.autoStopEnabled ? 'Enabled' : 'Disabled'}
        />
      </div>

      <Alert>
        <AlertDescription>
          Once created, you can start the experiment from the experiment details page.
        </AlertDescription>
      </Alert>
    </div>
  );
}

function ReviewItem({ label, value }: { label: string; value?: string | number | boolean }) {
  return (
    <div className="flex justify-between py-2 border-b">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-medium">{value || '-'}</span>
    </div>
  );
}
