"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { photoUrl } from "@/lib/media";

interface Photo {
  id: number;
  photo: string | null;
}

interface ABTest {
  id: number;
  photo_a_id: number;
  photo_b_id: number;
  photo_a_url: string | null;
  photo_b_url: string | null;
  clicks_a: number;
  clicks_b: number;
  started_at: string;
  ends_at: string;
  status: string;
}

export default function ABTestPage() {
  const { status } = useSession();
  const router = useRouter();
  const [tests, setTests] = useState<ABTest[]>([]);
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [photoAId, setPhotoAId] = useState("");
  const [photoBId, setPhotoBId] = useState("");

  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
  }, [status, router]);

  useEffect(() => {
    loadTests();
    loadPhotos();
  }, []);

  async function loadTests() {
    try {
      const res = await fetch("/api/ab-test");
      if (res.ok) {
        const data = await res.json();
        setTests(data.data || []);
      }
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }

  async function loadPhotos() {
    try {
      const res = await fetch("/api/manage/photos");
      if (res.ok) {
        const data = await res.json();
        setPhotos(data.data || []);
      }
    } catch {
      // silently fail
    }
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!photoAId || !photoBId) return;

    setSubmitting(true);
    setError(null);
    setSuccess(null);

    try {
      const res = await fetch("/api/ab-test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ photo_a_id: Number(photoAId), photo_b_id: Number(photoBId) }),
      });

      if (res.ok) {
        setSuccess("A/B test started! Results will be available in 7 days.");
        setPhotoAId("");
        setPhotoBId("");
        loadTests();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to create test");
      }
    } catch {
      setError("Network error");
    } finally {
      setSubmitting(false);
    }
  }

  function getMediaUrl(photoPath: string | null): string {
    if (!photoPath) return "/placeholder-avatar.svg";
    return photoUrl(photoPath);
  }

  if (status === "loading" || loading) {
    return (
      <div className="max-w-3xl mx-auto space-y-6">
        <div className="h-8 w-64 bg-surface-light rounded animate-pulse" />
        <div className="bg-surface rounded-xl p-6 animate-pulse space-y-4">
          <div className="h-32 bg-surface-light rounded" />
        </div>
      </div>
    );
  }

  const activeTest = tests.find((t) => t.status === "active");

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <h1 className="text-2xl font-bold">A/B Test Profile Photos</h1>
      <p className="text-text-muted text-sm">
        Select two photos from your gallery. Visitors will randomly see one, and after 7 days you can compare click performance.
      </p>

      {/* Create new test */}
      {!activeTest && (
        <form onSubmit={handleCreate} className="bg-surface rounded-xl p-6 border border-white/5 space-y-4">
          <h2 className="text-lg font-semibold">Start New Test</h2>

          {error && (
            <div className="bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-2.5 text-sm text-red-400">
              {error}
            </div>
          )}
          {success && (
            <div className="bg-green-500/10 border border-green-500/20 rounded-lg px-4 py-2.5 text-sm text-green-400">
              {success}
            </div>
          )}

          {photos.length < 2 ? (
            <p className="text-text-muted text-sm">You need at least 2 photos to run an A/B test.</p>
          ) : (
            <>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-text-muted mb-2">Photo A</label>
                  <select
                    value={photoAId}
                    onChange={(e) => setPhotoAId(e.target.value)}
                    required
                    className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
                  >
                    <option value="">Select photo...</option>
                    {photos.map((p) => (
                      <option key={p.id} value={p.id}>Photo #{p.id}</option>
                    ))}
                  </select>
                  {photoAId && (
                    <img
                      src={getMediaUrl(photos.find((p) => p.id === Number(photoAId))?.photo || null)}
                      alt="Photo A"
                      className="mt-2 w-full h-40 object-cover rounded-lg"
                    />
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-text-muted mb-2">Photo B</label>
                  <select
                    value={photoBId}
                    onChange={(e) => setPhotoBId(e.target.value)}
                    required
                    className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
                  >
                    <option value="">Select photo...</option>
                    {photos.filter((p) => String(p.id) !== photoAId).map((p) => (
                      <option key={p.id} value={p.id}>Photo #{p.id}</option>
                    ))}
                  </select>
                  {photoBId && (
                    <img
                      src={getMediaUrl(photos.find((p) => p.id === Number(photoBId))?.photo || null)}
                      alt="Photo B"
                      className="mt-2 w-full h-40 object-cover rounded-lg"
                    />
                  )}
                </div>
              </div>

              <button
                type="submit"
                disabled={submitting || !photoAId || !photoBId}
                className="gradient-gold text-background px-6 py-2.5 rounded-lg font-semibold disabled:opacity-40 hover:opacity-90 transition-opacity"
              >
                {submitting ? "Starting..." : "Start A/B Test (7 days)"}
              </button>
            </>
          )}
        </form>
      )}

      {/* Test results */}
      <div className="bg-surface rounded-xl p-6 border border-white/5">
        <h2 className="text-lg font-semibold mb-4">Test Results</h2>

        {tests.length === 0 ? (
          <p className="text-text-muted text-sm">No tests yet. Start one above.</p>
        ) : (
          <div className="space-y-6">
            {tests.map((test) => {
              const totalClicks = test.clicks_a + test.clicks_b;
              const pctA = totalClicks > 0 ? Math.round((test.clicks_a / totalClicks) * 100) : 50;
              const pctB = totalClicks > 0 ? Math.round((test.clicks_b / totalClicks) * 100) : 50;
              const isActive = test.status === "active";
              const winner = test.clicks_a > test.clicks_b ? "A" : test.clicks_b > test.clicks_a ? "B" : "Tie";

              return (
                <div key={test.id} className="border border-white/5 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-3">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${
                      isActive ? "bg-green-500/10 text-green-400" : "bg-surface-light text-text-muted"
                    }`}>
                      {isActive ? "Active" : "Completed"}
                    </span>
                    <span className="text-xs text-text-muted">
                      {new Date(test.started_at).toLocaleDateString()} - {new Date(test.ends_at).toLocaleDateString()}
                    </span>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="text-center">
                      <img
                        src={getMediaUrl(test.photo_a_url)}
                        alt="Photo A"
                        className="w-full h-32 object-cover rounded-lg mb-2"
                      />
                      <p className="text-sm font-medium text-text">Photo A</p>
                      <p className="text-lg font-bold text-gold">{test.clicks_a} clicks</p>
                      <p className="text-xs text-text-muted">{pctA}%</p>
                    </div>
                    <div className="text-center">
                      <img
                        src={getMediaUrl(test.photo_b_url)}
                        alt="Photo B"
                        className="w-full h-32 object-cover rounded-lg mb-2"
                      />
                      <p className="text-sm font-medium text-text">Photo B</p>
                      <p className="text-lg font-bold text-gold">{test.clicks_b} clicks</p>
                      <p className="text-xs text-text-muted">{pctB}%</p>
                    </div>
                  </div>

                  {/* Progress bar */}
                  <div className="flex h-3 rounded-full overflow-hidden bg-surface-light">
                    <div className="bg-primary transition-all" style={{ width: `${pctA}%` }} />
                    <div className="bg-gold transition-all" style={{ width: `${pctB}%` }} />
                  </div>

                  {!isActive && totalClicks > 0 && (
                    <p className="text-sm text-text mt-2 text-center">
                      Winner: <span className="font-bold text-gold">Photo {winner}</span>
                      {winner !== "Tie" && (
                        <span className="text-text-muted"> with {Math.max(test.clicks_a, test.clicks_b)} clicks</span>
                      )}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
