import { useEffect, useState } from "react";
import { router } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { ArrowRight, Mail, ShieldCheck, Loader2, BookOpen } from "lucide-react";
import { toast } from "sonner";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

type Step = "email" | "otp";

const Onboarding = () => {
  const searchParams = new URLSearchParams(window.location.search);
  const orderId = searchParams.get("order_id");

  const [step, setStep] = useState<Step>("email");
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [loading, setLoading] = useState(false);
  const [resendIn, setResendIn] = useState(0);

  // 60-second resend cooldown ticker
  useEffect(() => {
    if (resendIn <= 0) return;
    const t = setTimeout(() => setResendIn((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [resendIn]);

  const handleSendOtp = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!email.trim()) return;
    if (resendIn > 0) return;
    setLoading(true);
    try {
      const res = await fetch('/api/functions/send-delegate-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ email: email.trim(), order_id: orderId }),
      });
      if (res.status === 429) {
        toast.error('Too many attempts. Please wait a minute before trying again.');
        return;
      }
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data?.error) throw new Error(data?.error || 'Failed to send code');
      toast.success("Code sent! Check your email.");
      setStep("otp");
      setResendIn(60);
    } catch (err: any) {
      toast.error(err.message || "Failed to send code. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async () => {
    if (otp.length !== 6) return;
    setLoading(true);
    try {
      const res = await fetch('/api/functions/verify-delegate-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ email: email.trim(), code: otp }),
      });
      if (res.status === 429) {
        toast.error('Too many verification attempts. Please wait a minute and try again.');
        setOtp("");
        return;
      }
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data?.error) throw new Error(data?.error || 'Invalid code. Please try again.');

      const targetOrderId = data.order_id || orderId;
      router.visit(`/delegate-dashboard${targetOrderId ? `?order_id=${targetOrderId}` : ""}`);
    } catch (err: any) {
      toast.error(err.message || "Invalid code. Please try again.");
      setOtp("");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col" style={{ background: "#f8fafc", color: "#0f172a" }}>
      {/* Header */}
      <header style={{ background: "#ffffff", borderBottom: "1px solid #e2e8f0" }}>
        <div className="max-w-md mx-auto px-4 py-4 flex items-center gap-3">
          <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ background: "#f97316" }}>
            <BookOpen className="w-5 h-5" style={{ color: "#ffffff" }} />
          </div>
          <div>
            <p className="text-sm font-semibold" style={{ color: "#0f172a" }}>Locktel Academy</p>
            <p className="text-xs" style={{ color: "#64748b" }}>Delegate Onboarding</p>
          </div>
        </div>
      </header>

      {/* Content */}
      <div className="flex-1 flex items-center justify-center px-4 py-8">
        <div className="w-full max-w-md space-y-8">
          {step === "email" ? (
            <>
              <div className="text-center space-y-2">
                <div className="w-16 h-16 rounded-2xl flex items-center justify-center mx-auto" style={{ background: "#fff7ed" }}>
                  <Mail className="w-8 h-8" style={{ color: "#f97316" }} />
                </div>
                <h1 className="text-2xl font-bold" style={{ color: "#0f172a" }}>Welcome</h1>
                <p className="text-sm" style={{ color: "#64748b" }}>
                  Enter the email address you used when booking your course. We'll send you a one-time access code.
                </p>
              </div>

              <form onSubmit={handleSendOtp} className="space-y-4">
                <div className="space-y-1.5">
                  <Label htmlFor="email" style={{ color: "#374151" }}>Email Address</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="your@email.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    autoFocus
                    className="h-12 text-base"
                    style={{ background: "#ffffff", borderColor: "#d1d5db", color: "#0f172a" }}
                  />
                </div>
                <Button
                  type="submit"
                  className="w-full h-12 text-base font-semibold"
                  disabled={loading || !email.trim()}
                  style={{ background: "#f97316", color: "#ffffff", border: "none" }}
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  ) : (
                    <ArrowRight className="w-4 h-4 mr-2" />
                  )}
                  {loading ? "Sending code..." : "Send my access code"}
                </Button>
              </form>
            </>
          ) : (
            <>
              <div className="text-center space-y-2">
                <div className="w-16 h-16 rounded-2xl flex items-center justify-center mx-auto" style={{ background: "#f0fdf4" }}>
                  <ShieldCheck className="w-8 h-8" style={{ color: "#16a34a" }} />
                </div>
                <h1 className="text-2xl font-bold" style={{ color: "#0f172a" }}>Check your email</h1>
                <p className="text-sm" style={{ color: "#64748b" }}>
                  We sent a 6-digit code to <span className="font-medium" style={{ color: "#0f172a" }}>{email}</span>
                </p>
              </div>

              <div className="space-y-6">
                <div className="flex justify-center">
                  <InputOTP
                    maxLength={6}
                    value={otp}
                    onChange={setOtp}
                    onComplete={handleVerifyOtp}
                  >
                    <InputOTPGroup>
                      <InputOTPSlot index={0} />
                      <InputOTPSlot index={1} />
                      <InputOTPSlot index={2} />
                      <InputOTPSlot index={3} />
                      <InputOTPSlot index={4} />
                      <InputOTPSlot index={5} />
                    </InputOTPGroup>
                  </InputOTP>
                </div>

                <Button
                  className="w-full h-12 text-base font-semibold"
                  disabled={loading || otp.length !== 6}
                  onClick={handleVerifyOtp}
                  style={{ background: "#f97316", color: "#ffffff", border: "none" }}
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  ) : (
                    <ShieldCheck className="w-4 h-4 mr-2" />
                  )}
                  {loading ? "Verifying..." : "Verify & Continue"}
                </Button>

                <div className="text-center">
                  <button
                    type="button"
                    className="text-sm underline underline-offset-2"
                    style={{ color: "#64748b" }}
                    onClick={() => { setStep("email"); setOtp(""); }}
                  >
                    Use a different email
                  </button>
                  <span className="mx-3" style={{ color: "#cbd5e1" }}>·</span>
                  {resendIn > 0 ? (
                    <span className="text-sm" style={{ color: "#94a3b8" }}>
                      Resend available in {resendIn}s
                    </span>
                  ) : (
                    <button
                      type="button"
                      className="text-sm font-medium"
                      style={{ color: "#f97316" }}
                      onClick={() => handleSendOtp()}
                      disabled={loading}
                    >
                      Resend code
                    </button>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default Onboarding;
