"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  FlaskConical,
  Play,
  Pause,
  Trophy,
  TrendingUp,
  BarChart3,
  ChevronRight,
  RefreshCcw,
} from "lucide-react";
import type {
  Experiment,
  ExperimentMetrics,
  ExperimentStatus,
} from "@/lib/types/experiments.types";

interface ExperimentTrackerProps {
  className?: string;
}

export default function ExperimentTracker({
  className = "",
}: ExperimentTrackerProps) {
  const [experiments, setExperiments] = useState<Experiment[]>([]);
  const [metrics, setMetrics] = useState<ExperimentMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedExperiment, setSelectedExperiment] =
    useState<Experiment | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchExperiments = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch(
        "/api/staff/analytics/experiments?includeMetrics=true&status=all",
      );
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch experiments");
      }

      setExperiments(data.experiments);
      setMetrics(data.metrics);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleStatusChange = async (
    experimentId: string,
    newStatus: ExperimentStatus,
  ) => {
    try {
      setActionLoading(experimentId);
      const response = await fetch(
        `/api/staff/analytics/experiments/${experimentId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ status: newStatus }),
        },
      );

      const data = await response.json();
      if (!data.success) {
        throw new Error(data.error || "Failed to update experiment");
      }

      // Refresh data
      await fetchExperiments();
    } catch (err) {
      console.error("Error updating experiment:", err);
    } finally {
      setActionLoading(null);
    }
  };

  const handleDeclareWinner = async (
    experimentId: string,
    variantId: string,
  ) => {
    try {
      setActionLoading(experimentId);
      const response = await fetch(
        `/api/staff/analytics/experiments/${experimentId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ winner: variantId }),
        },
      );

      const data = await response.json();
      if (!data.success) {
        throw new Error(data.error || "Failed to declare winner");
      }

      // Refresh data
      await fetchExperiments();
      setSelectedExperiment(null);
    } catch (err) {
      console.error("Error declaring winner:", err);
    } finally {
      setActionLoading(null);
    }
  };

  const getStatusColor = (status: ExperimentStatus) => {
    switch (status) {
      case "running":
        return "bg-emerald-50 text-emerald-700 border-emerald-200";
      case "paused":
        return "bg-amber-50 text-amber-700 border-amber-200";
      case "completed":
        return "bg-blue-50 text-blue-700 border-blue-200";
      case "draft":
        return "bg-gray-50 text-gray-600 border-gray-200";
      default:
        return "bg-gray-50 text-gray-600 border-gray-200";
    }
  };

  const getWinningVariant = (experiment: Experiment) => {
    if (!experiment.variants.length) return null;
    return experiment.variants.reduce((best, current) =>
      current.conversionRate > best.conversionRate ? current : best,
    );
  };

  if (loading) {
    return (
      <div
        className={`rounded-3xl border border-gray-100 bg-white p-6 shadow-lg ${className}`}
      >
        <div className="animate-pulse space-y-4">
          <div className="h-6 w-48 rounded bg-gray-200" />
          <div className="h-32 rounded-xl bg-gray-100" />
          <div className="h-32 rounded-xl bg-gray-100" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        className={`rounded-3xl border border-red-100 bg-red-50 p-6 ${className}`}
      >
        <div className="flex items-center gap-3 text-red-700">
          <FlaskConical className="h-5 w-5" />
          <p className="text-sm font-medium">{error}</p>
        </div>
        <button
          onClick={fetchExperiments}
          className="mt-4 text-sm font-medium text-red-700 hover:text-red-800"
        >
          Try again
        </button>
      </div>
    );
  }

  return (
    <div
      className={`flex flex-col rounded-3xl border border-gray-100 bg-white shadow-lg ${className}`}
    >
      {/* Header */}
      <div className="flex items-center justify-between border-b border-gray-100 bg-gradient-to-r from-purple-50 to-transparent px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-purple-600/10 p-2 text-purple-600">
            <FlaskConical className="h-5 w-5" />
          </div>
          <div>
            <h3 className="text-sm font-semibold text-gray-900">
              A/B Experiments
            </h3>
            <p className="text-xs text-gray-500">Track variant performance</p>
          </div>
        </div>
        <button
          onClick={fetchExperiments}
          className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
          title="Refresh"
        >
          <RefreshCcw className="h-4 w-4" />
        </button>
      </div>

      {/* Metrics Summary */}
      {metrics && (
        <div className="grid grid-cols-4 gap-4 border-b border-gray-100 px-6 py-4">
          <div className="text-center">
            <p className="text-2xl font-bold text-gray-900">
              {metrics.activeExperiments}
            </p>
            <p className="text-xs text-gray-500">Active</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-gray-900">
              {metrics.completedExperiments}
            </p>
            <p className="text-xs text-gray-500">Completed</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-emerald-600">
              {metrics.averageLift > 0 ? "+" : ""}
              {metrics.averageLift}%
            </p>
            <p className="text-xs text-gray-500">Avg Lift</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-gray-900">
              {metrics.totalConversions.toLocaleString()}
            </p>
            <p className="text-xs text-gray-500">Conversions</p>
          </div>
        </div>
      )}

      {/* Experiments List */}
      <div className="flex-1 divide-y divide-gray-100 overflow-y-auto">
        {experiments.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <FlaskConical className="h-12 w-12 text-gray-300" />
            <p className="mt-4 text-sm text-gray-500">No experiments yet</p>
          </div>
        ) : (
          experiments.slice(0, 5).map((experiment) => {
            const winningVariant = getWinningVariant(experiment);
            const isExpanded = selectedExperiment?.id === experiment.id;

            return (
              <div key={experiment.id} className="group">
                <div
                  className="flex cursor-pointer items-center justify-between px-6 py-4 hover:bg-gray-50"
                  onClick={() =>
                    setSelectedExperiment(isExpanded ? null : experiment)
                  }
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <h4 className="truncate text-sm font-medium text-gray-900">
                        {experiment.name}
                      </h4>
                      <span
                        className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase ${getStatusColor(experiment.status)}`}
                      >
                        {experiment.status}
                      </span>
                    </div>
                    <p className="mt-1 truncate text-xs text-gray-500">
                      {experiment.description}
                    </p>
                  </div>

                  <div className="flex items-center gap-4">
                    {experiment.significance.confident && (
                      <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-1 text-xs font-medium text-emerald-700">
                        <TrendingUp className="h-3 w-3" />
                        {experiment.significance.confidenceLevel.toFixed(1)}%
                      </span>
                    )}
                    <ChevronRight
                      className={`h-4 w-4 text-gray-400 transition-transform ${isExpanded ? "rotate-90" : ""}`}
                    />
                  </div>
                </div>

                {/* Expanded View */}
                {isExpanded && (
                  <div className="border-t border-gray-100 bg-gray-50 px-6 py-4">
                    {/* Variants */}
                    <div className="space-y-3">
                      {experiment.variants.map((variant) => {
                        const isLeading = winningVariant?.id === variant.id;
                        const conversionWidth = Math.min(
                          100,
                          variant.conversionRate * 10,
                        );

                        return (
                          <div key={variant.id} className="space-y-1">
                            <div className="flex items-center justify-between text-sm">
                              <div className="flex items-center gap-2">
                                <span className="font-medium text-gray-700">
                                  {variant.name}
                                </span>
                                {isLeading &&
                                  experiment.status === "running" && (
                                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold text-emerald-700">
                                      <Trophy className="h-3 w-3" />
                                      Leading
                                    </span>
                                  )}
                                {experiment.winner === variant.id && (
                                  <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700">
                                    <Trophy className="h-3 w-3" />
                                    Winner
                                  </span>
                                )}
                              </div>
                              <span className="tabular-nums text-gray-900">
                                {variant.conversionRate.toFixed(2)}%
                              </span>
                            </div>
                            <div className="h-2 overflow-hidden rounded-full bg-gray-200">
                              <div
                                className={`h-full rounded-full transition-all ${
                                  isLeading ? "bg-emerald-500" : "bg-gray-400"
                                }`}
                                style={{ width: `${conversionWidth}%` }}
                              />
                            </div>
                            <div className="flex justify-between text-xs text-gray-500">
                              <span>
                                {variant.visitors.toLocaleString()} visitors
                              </span>
                              <span>
                                {variant.conversions.toLocaleString()}{" "}
                                conversions
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>

                    {/* Actions */}
                    <div className="mt-4 flex items-center justify-between border-t border-gray-200 pt-4">
                      <div className="flex items-center gap-2">
                        {experiment.status === "running" && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleStatusChange(experiment.id, "paused");
                            }}
                            disabled={actionLoading === experiment.id}
                            className="inline-flex items-center gap-1 rounded-lg border border-amber-200 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-700 hover:bg-amber-100 disabled:opacity-50"
                          >
                            <Pause className="h-3 w-3" />
                            Pause
                          </button>
                        )}
                        {experiment.status === "paused" && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleStatusChange(experiment.id, "running");
                            }}
                            disabled={actionLoading === experiment.id}
                            className="inline-flex items-center gap-1 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 hover:bg-emerald-100 disabled:opacity-50"
                          >
                            <Play className="h-3 w-3" />
                            Resume
                          </button>
                        )}
                        {experiment.status === "draft" && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleStatusChange(experiment.id, "running");
                            }}
                            disabled={actionLoading === experiment.id}
                            className="inline-flex items-center gap-1 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 hover:bg-emerald-100 disabled:opacity-50"
                          >
                            <Play className="h-3 w-3" />
                            Start
                          </button>
                        )}
                      </div>

                      {experiment.status === "running" &&
                        experiment.significance.confident &&
                        winningVariant && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeclareWinner(
                                experiment.id,
                                winningVariant.id,
                              );
                            }}
                            disabled={actionLoading === experiment.id}
                            className="inline-flex items-center gap-1 rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-50"
                          >
                            <Trophy className="h-3 w-3" />
                            Declare Winner
                          </button>
                        )}
                    </div>

                    {/* Significance Info */}
                    {experiment.status === "running" &&
                      !experiment.significance.confident && (
                        <p className="mt-3 text-xs text-gray-500">
                          <BarChart3 className="mr-1 inline h-3 w-3" />
                          Need{" "}
                          {experiment.significance.requiredSample -
                            experiment.significance.sampleSize}{" "}
                          more visitors for statistical significance
                        </p>
                      )}
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>

      {/* Footer */}
      {experiments.length > 5 && (
        <div className="border-t border-gray-100 px-6 py-3 text-center">
          <Link
            href="/staff/dashboard/analytics"
            className="text-sm font-medium text-purple-600 hover:text-purple-700"
          >
            View all {experiments.length} experiments →
          </Link>
        </div>
      )}
    </div>
  );
}
