"use client";

import { signup } from "@/app/actions/auth";
import Link from "next/link";
import { useState } from "react";
import { createSupabaseBrowserClient, isSocialLoginEnabled } from "@/lib/supabase-client";
import { Eye, EyeOff, Loader2, ArrowRight, Briefcase, User } from "lucide-react";

function PasswordStrength({ password }: { password: string }) {
  const checks = [
    { label: "8+ characters", pass: password.length >= 8 },
    { label: "Uppercase", pass: /[A-Z]/.test(password) },
    { label: "Number", pass: /[0-9]/.test(password) },
    { label: "Symbol", pass: /[^A-Za-z0-9]/.test(password) },
  ];
  const score = checks.filter((c) => c.pass).length;
  const colors = ["bg-red-500", "bg-orange-400", "bg-yellow-400", "bg-emerald-400", "bg-emerald-500"];
  const labels = ["", "Weak", "Fair", "Good", "Strong"];

  if (!password) return null;

  return (
    <div className="mt-2 space-y-2">
      <div className="flex gap-1">
        {[0, 1, 2, 3].map((i) => (
          <div
            key={i}
            className={`h-1 flex-1 rounded-full transition-all duration-300 ${i < score ? colors[score] : "bg-white/10"}`}
          />
        ))}
      </div>
      <div className="flex items-center justify-between">
        <div className="flex gap-2 flex-wrap">
          {checks.map((c) => (
            <span key={c.label} className={`text-xs ${c.pass ? "text-emerald-400" : "text-slate-600"} transition-colors`}>
              {c.pass ? "✓" : "○"} {c.label}
            </span>
          ))}
        </div>
        {score > 0 && (
          <span className={`text-xs font-medium ${colors[score].replace("bg-", "text-")}`}>
            {labels[score]}
          </span>
        )}
      </div>
    </div>
  );
}

export default function SignupPage() {
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [socialLoading, setSocialLoading] = useState<"google" | "linkedin" | null>(null);
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [role, setRole] = useState<"candidate" | "employer">("candidate");

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);
    const formData = new FormData(e.currentTarget);
    try {
      const result = await signup(formData);
      if (result?.error) {
        setError(result.error);
        setIsLoading(false);
      }
    } catch (e) {
      setIsLoading(false);
      throw e;
    }
  };

  const handleSocialLogin = async (provider: "google" | "linkedin_oidc") => {
    if (!isSocialLoginEnabled) {
      setError("Social login is not configured yet. Please use email & password.");
      return;
    }
    const key = provider === "google" ? "google" : "linkedin";
    setSocialLoading(key);
    try {
      const supabase = createSupabaseBrowserClient();
      const { error } = await supabase.auth.signInWithOAuth({
        provider,
        options: {
          redirectTo: `${window.location.origin}/api/auth/callback`,
          queryParams: provider === "google" ? { access_type: "offline", prompt: "consent" } : {},
        },
      });
      if (error) {
        setError(error.message);
        setSocialLoading(null);
      }
    } catch {
      setError("Something went wrong. Please try again.");
      setSocialLoading(null);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center relative overflow-hidden bg-[#0a0f1e] p-4 py-10">
      {/* Background blobs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-[600px] h-[600px] rounded-full bg-[#0070f3]/20 blur-[120px] animate-pulse" />
        <div className="absolute -bottom-40 -left-40 w-[600px] h-[600px] rounded-full bg-purple-600/15 blur-[120px] animate-pulse delay-1000" />
      </div>
      <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.02)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.02)_1px,transparent_1px)] bg-[size:64px_64px] pointer-events-none" />

      <div className="relative w-full max-w-md z-10">
        {/* Logo */}
        <div className="text-center mb-8">
          <Link href="/" className="inline-flex items-center gap-2 group">
            <div className="w-10 h-10 rounded-xl bg-[#0070f3] flex items-center justify-center shadow-lg shadow-[#0070f3]/30">
              <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
            <span className="text-2xl font-extrabold text-white tracking-tight">
              Proten<span className="text-[#0070f3]">Connect</span>
            </span>
          </Link>
          <p className="mt-3 text-slate-400 text-sm">Create your free account and get started</p>
        </div>

        <div className="bg-white/5 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl shadow-black/40 p-8">
          {/* Error */}
          {error && (
            <div className="mb-6 flex items-start gap-3 p-4 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
              <span className="mt-0.5 flex-shrink-0">⚠</span>
              {error}
            </div>
          )}

          {/* Role selector */}
          <div className="mb-6">
            <p className="text-sm font-medium text-slate-300 mb-3">I am joining as a…</p>
            <div className="grid grid-cols-2 gap-3">
              <button
                type="button"
                onClick={() => setRole("candidate")}
                className={`flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all duration-200 ${
                  role === "candidate"
                    ? "border-[#0070f3] bg-[#0070f3]/10 text-white"
                    : "border-white/10 bg-white/5 text-slate-400 hover:border-white/20 hover:text-slate-300"
                }`}
              >
                <User className={`w-6 h-6 ${role === "candidate" ? "text-[#0070f3]" : ""}`} />
                <span className="text-sm font-semibold">Candidate</span>
                <span className="text-xs text-slate-500 text-center leading-tight">Find your next role</span>
              </button>
              <button
                type="button"
                onClick={() => setRole("employer")}
                className={`flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all duration-200 ${
                  role === "employer"
                    ? "border-purple-500 bg-purple-500/10 text-white"
                    : "border-white/10 bg-white/5 text-slate-400 hover:border-white/20 hover:text-slate-300"
                }`}
              >
                <Briefcase className={`w-6 h-6 ${role === "employer" ? "text-purple-400" : ""}`} />
                <span className="text-sm font-semibold">Employer</span>
                <span className="text-xs text-slate-500 text-center leading-tight">Hire top talent</span>
              </button>
            </div>
          </div>

          {/* Social Buttons */}
          <div className="space-y-3 mb-6">
            <button
              type="button"
              onClick={() => handleSocialLogin("google")}
              disabled={!!socialLoading || isLoading}
              className="w-full flex items-center justify-center gap-3 px-4 py-3 rounded-xl bg-white/8 border border-white/15 text-white text-sm font-medium hover:bg-white/12 hover:border-white/25 transition-all duration-200 disabled:opacity-50"
            >
              {socialLoading === "google" ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <svg className="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24">
                  <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                  <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                  <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                  <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                </svg>
              )}
              Sign up with Google
            </button>
            <button
              type="button"
              onClick={() => handleSocialLogin("linkedin_oidc")}
              disabled={!!socialLoading || isLoading}
              className="w-full flex items-center justify-center gap-3 px-4 py-3 rounded-xl bg-white/8 border border-white/15 text-white text-sm font-medium hover:bg-white/12 hover:border-white/25 transition-all duration-200 disabled:opacity-50"
            >
              {socialLoading === "linkedin" ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <svg className="w-5 h-5 flex-shrink-0" fill="#0A66C2" viewBox="0 0 24 24">
                  <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
                </svg>
              )}
              Sign up with LinkedIn
            </button>
          </div>

          {/* Divider */}
          <div className="relative mb-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-white/10" />
            </div>
            <div className="relative flex justify-center">
              <span className="px-3 bg-transparent text-slate-500 text-xs uppercase tracking-widest">or with email</span>
            </div>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            <input type="hidden" name="role" value={role} />

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">First Name</label>
                <input
                  name="first_name"
                  type="text"
                  required
                  autoComplete="given-name"
                  className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                  placeholder="John"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">Last Name</label>
                <input
                  name="last_name"
                  type="text"
                  required
                  autoComplete="family-name"
                  className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                  placeholder="Doe"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1.5">Email Address</label>
              <input
                name="email"
                type="email"
                required
                autoComplete="email"
                className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                placeholder="john@example.com"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1.5">Password</label>
              <div className="relative">
                <input
                  name="password"
                  type={showPassword ? "text" : "password"}
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="new-password"
                  className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 pr-12 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                  placeholder="Create a strong password"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors"
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              <PasswordStrength password={password} />
            </div>

            <button
              type="submit"
              disabled={isLoading || !!socialLoading}
              className="w-full flex items-center justify-center gap-2 rounded-xl bg-[#0070f3] px-4 py-3 font-semibold text-white shadow-lg shadow-[#0070f3]/30 hover:bg-[#0060d3] hover:shadow-[#0070f3]/40 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed group text-sm mt-2"
            >
              {isLoading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <>
                  Create Account
                  <ArrowRight className="w-4 h-4 group-hover:translate-x-0.5 transition-transform" />
                </>
              )}
            </button>
          </form>

          <p className="mt-6 text-center text-sm text-slate-500">
            Already have an account?{" "}
            <Link href="/login" className="font-medium text-[#0070f3] hover:text-[#0070f3]/80 transition-colors">
              Sign in
            </Link>
          </p>
        </div>

        <p className="mt-6 text-center text-xs text-slate-600">
          By creating an account, you agree to our{" "}
          <Link href="/terms" className="text-slate-500 hover:text-slate-400 underline">Terms</Link>
          {" & "}
          <Link href="/privacy" className="text-slate-500 hover:text-slate-400 underline">Privacy Policy</Link>
        </p>
      </div>
    </div>
  );
}
