import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "../services/api";
import { useAuth } from "../hooks/useAuth";
import { usePageTitle } from "../hooks/usePageTitle";
import { toast } from "react-toastify";
import { motion, AnimatePresence } from "motion/react";
import { Rocket, PartyPopper, ArrowRight } from "lucide-react";

const STEPS = ["Welcome", "Gitea Connection", "AWS Setup", "Your Webhook", "Enable a Repo", "Done"];

const AWS_REGIONS = [
  "us-east-1", "us-east-2", "us-west-1", "us-west-2",
  "eu-west-1", "eu-west-2", "eu-central-1",
  "ap-southeast-1", "ap-southeast-2", "ap-northeast-1",
];

export function SetupWizard() {
  const [step, setStep] = useState(0);
  const { user, refresh } = useAuth();
  const navigate = useNavigate();

  const [giteaUrl, setGiteaUrl] = useState(user?.giteaInstanceUrl || "");
  const [giteaUsername, setGiteaUsername] = useState(user?.giteaUsername || "");
  const [giteaPAT, setGiteaPAT] = useState("");
  const [awsKeyId, setAwsKeyId] = useState("");
  const [awsSecret, setAwsSecret] = useState("");
  const [awsRegion, setAwsRegion] = useState("us-east-1");
  const [saving, setSaving] = useState(false);
  const [webhookUrl, setWebhookUrl] = useState("");
  const [webhookSecret, setWebhookSecret] = useState("");
  usePageTitle(`Setup | ${STEPS[step]}`);

  // Auto-load webhook info whenever we reach step 3 (index 3 = "Your Webhook")
  useEffect(() => {
    if (step !== 3) return;
    if (webhookSecret) return;
    api.user.getWebhookSecret().then(res => {
      if (res.ok && res.data) {
        setWebhookUrl(res.data.webhookUrl);
        setWebhookSecret(res.data.token);
      }
    }).catch(() => {});
  }, [step, user?.id]);

  const next = () => setStep(s => Math.min(s + 1, STEPS.length - 1));
  const skip = () => navigate("/");

  const handleGiteaNext = async () => {
    setSaving(true);
    const res = await api.user.updateGitea({ giteaInstanceUrl: giteaUrl, giteaUsername, giteaPAT });
    setSaving(false);
    if (res.ok) {
      toast.success("Gitea connected!");
      refresh();
      next();
    } else {
      toast.error(res.message || "Failed to connect Gitea");
    }
  };

  const handleAwsNext = async () => {
    setSaving(true);
    const res = await api.user.updateAws({ awsAccessKeyId: awsKeyId, awsSecretAccessKey: awsSecret, awsRegion });
    setSaving(false);
    if (res.ok) {
      toast.success("AWS connected!");
      refresh();
      const secretRes = await api.user.getWebhookSecret();
      if (secretRes.ok && secretRes.data) {
        setWebhookUrl(secretRes.data.webhookUrl);
        setWebhookSecret(secretRes.data.token);
      }
      next();
    } else {
      toast.error(res.message || "Failed to connect AWS");
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-slate-900 px-4">
      <div className="bg-white dark:bg-slate-800 shadow-xl rounded-2xl p-8 w-full max-w-lg">
        {/* Progress */}
        <div className="mb-8">
          <div className="flex items-center gap-1">
            {STEPS.map((s, i) => (
              <React.Fragment key={i}>
                <div className={`h-1.5 flex-1 rounded-full transition-colors ${i <= step ? "bg-blue-600" : "bg-gray-200 dark:bg-slate-600"}`} />
              </React.Fragment>
            ))}
          </div>
          <p className="text-xs text-gray-500 dark:text-slate-400 mt-2">Step {step + 1} of {STEPS.length}: {STEPS[step]}</p>
        </div>

        <AnimatePresence mode="wait">
          <motion.div
            key={step}
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.2 }}
          >
            {step === 0 && (
              <div className="text-center space-y-4">
                <Rocket size={48} className="mx-auto text-blue-600 dark:text-blue-400" />
                <h2 className="text-2xl font-bold">Welcome to PR Previews</h2>
                <p className="text-gray-600 dark:text-slate-300 text-sm">
                  PP automatically provisions EC2 instances, builds your code, and posts live preview URLs on every pull request.
                </p>
                <p className="text-sm text-gray-500 dark:text-slate-400">Let's get you set up in a few steps.</p>
                <div className="flex gap-3 justify-center mt-4">
                  <button onClick={next} className="inline-flex items-center gap-1 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                    Get Started <ArrowRight size={16} />
                  </button>
                  <button onClick={skip} className="px-4 py-2.5 text-sm text-gray-500 dark:text-slate-400 hover:underline">
                    Skip wizard
                  </button>
                </div>
              </div>
            )}

            {step === 1 && (
              <div className="space-y-4">
                <h2 className="text-xl font-bold">Gitea Connection</h2>
                <p className="text-sm text-gray-600 dark:text-slate-300">Connect to your Gitea instance so PP can register webhooks and post comments.</p>
                <input type="url" value={giteaUrl} onChange={e => setGiteaUrl(e.target.value)}
                  className={inputCls} placeholder="https://gitea.example.com" />
                <input type="text" value={giteaUsername} onChange={e => setGiteaUsername(e.target.value)}
                  className={inputCls} placeholder="Gitea username" />
                <input type="password" value={giteaPAT} onChange={e => setGiteaPAT(e.target.value)}
                  className={inputCls} placeholder="Personal Access Token" />
                <p className="text-xs text-gray-400 dark:text-slate-500">
                  Required PAT scopes (Read <strong>and Write</strong>): <code>repository</code>, <code>issue</code>, <code>admin:repo_hook</code>
                </p>
                <div className="flex gap-3">
                  <button onClick={handleGiteaNext} disabled={saving || !giteaUrl || !giteaUsername || !giteaPAT}
                    className="flex-1 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50">
                    {saving ? "Validating..." : <span className="inline-flex items-center gap-1">Connect & Next <ArrowRight size={16} /></span>}
                  </button>
                  <button onClick={next} className="text-sm text-gray-500 dark:text-slate-400 hover:underline px-2">Skip</button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="space-y-4">
                <h2 className="text-xl font-bold">AWS Setup</h2>
                <p className="text-sm text-gray-600 dark:text-slate-300">PP will launch EC2 instances in your AWS account to host previews.</p>
                <input type="text" value={awsKeyId} onChange={e => setAwsKeyId(e.target.value)}
                  className={inputCls} placeholder="AWS Access Key ID" />
                <input type="password" value={awsSecret} onChange={e => setAwsSecret(e.target.value)}
                  className={inputCls} placeholder="AWS Secret Access Key" />
                <select value={awsRegion} onChange={e => setAwsRegion(e.target.value)} className={inputCls}>
                  {AWS_REGIONS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
                <details className="text-xs">
                  <summary className="cursor-pointer text-blue-600 dark:text-blue-400">View required IAM permissions</summary>
                  <pre className="mt-2 bg-gray-50 dark:bg-slate-700 rounded p-3 overflow-auto text-gray-700 dark:text-slate-300">
{`{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ec2:RunInstances","ec2:TerminateInstances",
      "ec2:DescribeInstances","ec2:CreateSecurityGroup",
      "ec2:DeleteSecurityGroup","ec2:AuthorizeSecurityGroupIngress",
      "ec2:DescribeSecurityGroups","ec2:CreateKeyPair",
      "ec2:DeleteKeyPair","ec2:CreateTags","sts:GetCallerIdentity"],
    "Resource": "*"
  }]
}`}
                  </pre>
                </details>
                <div className="flex gap-3">
                  <button onClick={handleAwsNext} disabled={saving || !awsKeyId || !awsSecret}
                    className="flex-1 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50">
                    {saving ? "Validating..." : <span className="inline-flex items-center gap-1">Connect & Next <ArrowRight size={16} /></span>}
                  </button>
                  <button onClick={next} className="text-sm text-gray-500 dark:text-slate-400 hover:underline px-2">Skip</button>
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="space-y-4">
                <h2 className="text-xl font-bold">Your Webhook</h2>
                <p className="text-sm text-gray-600 dark:text-slate-300">
                  PP auto-registers webhooks when you enable a repo. These are for reference:
                </p>
                <div className="space-y-2">
                  <div>
                    <label className="text-xs text-gray-500 block mb-1">Webhook URL (Target URL in Gitea)</label>
                    <input type="text" readOnly value={webhookUrl || "(loading...)"}
                      className={`${inputCls} font-mono text-xs bg-gray-50 dark:bg-slate-700/50`} />
                  </div>
                  <div>
                    <label className="text-xs text-gray-500 block mb-1">Webhook Secret</label>
                    <input type="text" readOnly value={webhookSecret || "(loading...)"}
                      className={`${inputCls} font-mono text-xs bg-gray-50 dark:bg-slate-700/50`} />
                  </div>
                </div>
                <button onClick={next} className="w-full inline-flex items-center justify-center gap-1 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                  Next <ArrowRight size={16} />
                </button>
              </div>
            )}

            {step === 4 && (
              <div className="space-y-4">
                <h2 className="text-xl font-bold">Enable Your First Repo</h2>
                <p className="text-sm text-gray-600 dark:text-slate-300">
                  Go to the Repos page to enable previews for a repository. PP will automatically register the webhook.
                </p>
                <div className="flex gap-3">
                  <a href="/repos"
                    className="flex-1 inline-flex items-center justify-center gap-1 py-2.5 text-center bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                    Go to Repos <ArrowRight size={16} />
                  </a>
                  <button onClick={next} className="text-sm text-gray-500 dark:text-slate-400 hover:underline px-2">Skip</button>
                </div>
              </div>
            )}

            {step === 5 && (
              <div className="text-center space-y-4">
                <PartyPopper size={48} className="mx-auto text-blue-600 dark:text-blue-400" />
                <h2 className="text-2xl font-bold">You're all set!</h2>
                <p className="text-gray-600 dark:text-slate-300 text-sm">
                  Open a pull request on an enabled repo and PP will provision a preview automatically.
                </p>
                <button onClick={() => navigate("/")} className="inline-flex items-center gap-1 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                  Go to Dashboard <ArrowRight size={16} />
                </button>
              </div>
            )}
          </motion.div>
        </AnimatePresence>
      </div>
    </div>
  );
}

const inputCls = "w-full px-3 py-2 text-sm border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500";
