"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Eye, EyeOff, Loader2, Check, AlertTriangle, MailCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { authApi } from "@/lib/api";
import { tokenStore } from "@/lib/auth-store";
import { GoogleLoginButton } from "@/components/auth/google-login-button";

const plans = [
  {
    id: "free",
    name: "Free",
    price: "₹0/mo",
    perks: ["1 video/day", "15 min max", "Watermarked"],
  },
  {
    id: "pro",
    name: "Pro",
    price: "₹799/mo",
    perks: ["5 videos/day", "20 min max", "No watermark"],
    popular: true,
  },
];

export default function SignupPage() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState("free");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [otp, setOtp] = useState("");
  const [verificationEmail, setVerificationEmail] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setMessage("");
    setLoading(true);
    try {
      const response = await authApi.signup(name, email, password);
      setVerificationEmail(response.email);
      setMessage(response.message);
      setOtp("");
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Signup failed");
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setMessage("");
    setLoading(true);
    try {
      const tokens = await authApi.verifyEmail(verificationEmail, otp);
      tokenStore.set(tokens.access_token, tokens.refresh_token);
      router.push("/dashboard");
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Verification failed");
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    setError("");
    setMessage("");
    setLoading(true);
    try {
      const response = await authApi.resendVerification(verificationEmail);
      setMessage(response.message);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Could not resend code");
    } finally {
      setLoading(false);
    }
  };

  if (verificationEmail) {
    return (
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-violet-500/10 text-violet-300">
            <MailCheck className="h-6 w-6" />
          </div>
          <h1 className="text-2xl font-black text-white mb-2">Verify your email</h1>
          <p className="text-zinc-500 text-sm">Enter the 6-digit code sent to {verificationEmail}</p>
        </div>

        <div className="glass-card p-6">
          <form onSubmit={handleVerify} className="space-y-4">
            {message && (
              <div className="flex items-center gap-2 text-xs text-emerald-400 p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/20">
                <Check className="w-3.5 h-3.5 flex-shrink-0" />
                {message}
              </div>
            )}
            {error && (
              <div className="flex items-center gap-2 text-xs text-red-400 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                <AlertTriangle className="w-3.5 h-3.5 flex-shrink-0" />
                {error}
              </div>
            )}

            <div className="space-y-1.5">
              <Label className="text-xs text-zinc-400">Verification code</Label>
              <Input
                inputMode="numeric"
                pattern="[0-9]{6}"
                maxLength={6}
                placeholder="000000"
                required
                value={otp}
                onChange={(e) => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
                className="bg-white/5 border-white/10 text-white placeholder:text-zinc-700 focus:border-violet-500/50 h-11 text-center tracking-[0.4em] text-lg"
              />
            </div>

            <Button
              type="submit"
              disabled={loading || otp.length !== 6}
              className="w-full bg-gradient-to-r from-violet-600 to-violet-500 hover:from-violet-500 hover:to-violet-400 text-white border-0 shadow-lg shadow-violet-900/30 h-11"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Verify Email"}
            </Button>
          </form>

          <div className="mt-4 flex items-center justify-between text-xs">
            <button
              type="button"
              onClick={() => setVerificationEmail("")}
              className="text-zinc-500 hover:text-zinc-300"
            >
              Edit signup details
            </button>
            <button
              type="button"
              onClick={handleResend}
              disabled={loading}
              className="text-violet-400 hover:text-violet-300 disabled:opacity-50"
            >
              Resend code
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full max-w-sm">
      <div className="text-center mb-8">
        <h1 className="text-2xl font-black text-white mb-2">Create your account</h1>
        <p className="text-zinc-500 text-sm">Start finding viral clips today</p>
      </div>

      <div className="glass-card p-6 space-y-5">
        <GoogleLoginButton
          text="signup_with"
          onSuccess={() => router.push("/dashboard")}
          onError={setError}
        />

        <div className="flex items-center gap-3">
          <Separator className="flex-1 bg-white/8" />
          <span className="text-xs text-zinc-600">or email</span>
          <Separator className="flex-1 bg-white/8" />
        </div>

        {/* Plan selector */}
        <div>
          <Label className="text-xs text-zinc-400 mb-2 block">Choose a plan</Label>
          <div className="grid grid-cols-2 gap-2">
            {plans.map((plan) => (
              <button
                key={plan.id}
                type="button"
                onClick={() => setSelectedPlan(plan.id)}
                className={cn(
                  "relative p-3 rounded-xl border text-left transition-all",
                  selectedPlan === plan.id
                    ? "border-violet-500/50 bg-violet-500/10"
                    : "border-white/8 bg-white/3 hover:border-white/15"
                )}
              >
                {plan.popular && (
                  <span className="absolute -top-2 left-1/2 -translate-x-1/2 text-[9px] bg-violet-600 text-white px-1.5 py-0.5 rounded-full">
                    Popular
                  </span>
                )}
                {selectedPlan === plan.id && (
                  <Check className="absolute top-2 right-2 w-3 h-3 text-violet-400" />
                )}
                <div className="text-sm font-semibold text-white">{plan.name}</div>
                <div className="text-xs text-violet-400 mb-1.5">{plan.price}</div>
                {plan.perks.map((p) => (
                  <div key={p} className="text-[10px] text-zinc-500">{p}</div>
                ))}
              </button>
            ))}
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-3">
          {error && (
            <div className="flex items-center gap-2 text-xs text-red-400 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
              <AlertTriangle className="w-3.5 h-3.5 flex-shrink-0" />
              {error}
            </div>
          )}

          <div className="space-y-1.5">
            <Label className="text-xs text-zinc-400">Full Name</Label>
            <Input
              placeholder="Your name"
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="bg-white/5 border-white/10 text-white placeholder:text-zinc-700 focus:border-violet-500/50 h-10"
            />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs text-zinc-400">Email</Label>
            <Input
              type="email"
              placeholder="you@example.com"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="bg-white/5 border-white/10 text-white placeholder:text-zinc-700 focus:border-violet-500/50 h-10"
            />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs text-zinc-400">Password</Label>
            <div className="relative">
              <Input
                type={showPassword ? "text" : "password"}
                placeholder="Min 8 characters"
                required
                minLength={8}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="bg-white/5 border-white/10 text-white placeholder:text-zinc-700 focus:border-violet-500/50 h-10 pr-10"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300"
              >
                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
          </div>

          <Button
            type="submit"
            disabled={loading}
            className="w-full bg-gradient-to-r from-violet-600 to-violet-500 hover:from-violet-500 hover:to-violet-400 text-white border-0 shadow-lg shadow-violet-900/30 h-11 mt-1"
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Create Account"}
          </Button>
        </form>

        <p className="text-[11px] text-zinc-600 text-center">
          By signing up, you agree to our{" "}
          <Link href="/terms" className="text-zinc-400 hover:text-white">Terms</Link>
          {" "}and{" "}
          <Link href="/privacy" className="text-zinc-400 hover:text-white">Privacy Policy</Link>
        </p>
      </div>

      <p className="text-center text-sm text-zinc-500 mt-6">
        Already have an account?{" "}
        <Link href="/login" className="text-violet-400 hover:text-violet-300 transition-colors font-medium">
          Sign in
        </Link>
      </p>
    </div>
  );
}
