import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Progress } from "@/components/ui/progress";
import { GraduationCap, Eye, EyeOff, Loader2 } from "lucide-react";
import { useRegister, useCheckEmail } from "@/hooks/queries/useSignup";
import { ApiError } from "@/lib/api-client";
import type { RegisterRequest } from "@/types";
import { cn } from "@/lib/utils";

const passwordStrength = (pwd: string): number => {
  let s = 0;
  if (pwd.length >= 8) s += 1;
  if (pwd.length >= 12) s += 1;
  if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) s += 1;
  if (/\d/.test(pwd)) s += 1;
  if (/[^A-Za-z0-9]/.test(pwd)) s += 1;
  return Math.min(100, s * 25);
};

const schema = z
  .object({
    name: z.string().min(2, "Enter your full name"),
    email: z.string().email("Enter a valid email"),
    password: z
      .string()
      .min(8, "At least 8 characters")
      .regex(/[A-Za-z]/, "Include letters")
      .regex(/\d/, "Include a number"),
    confirm: z.string(),
    role: z.enum(["academic_student", "self_learner", "teacher"]),
  })
  .refine((d) => d.password === d.confirm, { message: "Passwords do not match", path: ["confirm"] });

type FormValues = z.infer<typeof schema>;

export default function Register() {
  const navigate = useNavigate();
  const register = useRegister();
  const checkEmail = useCheckEmail();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: "",
      email: "",
      password: "",
      confirm: "",
      role: "self_learner",
    },
    mode: "onBlur",
  });

  const pwd = form.watch("password");
  const strength = passwordStrength(pwd || "");

  const onSubmit = async (values: FormValues) => {
    const payload: RegisterRequest = {
      name: values.name.trim(),
      email: values.email.trim(),
      password: values.password,
      role: values.role,
      captcha_token: "demo-placeholder",
    };
    try {
      await register.mutateAsync(payload);
      navigate(`/verify-email?email=${encodeURIComponent(values.email.trim())}`);
    } catch (e) {
      form.setError("root", {
        message: e instanceof ApiError ? e.message : "Registration failed",
      });
    }
  };

  const verifyEmailBlur = async () => {
    const ok = await form.trigger("email");
    if (!ok) return;
    const email = form.getValues("email").trim();
    if (!email) return;
    try {
      const res = await checkEmail.mutateAsync(email);
      if (res.exists) {
        form.setError("email", { message: "This email is already registered" });
      } else {
        form.clearErrors("email");
      }
    } catch {
      form.setError("email", { message: "Could not verify email" });
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-muted/40 to-background p-4">
      <div className="w-full max-w-md">
        <div className="flex items-center justify-center gap-2 mb-8">
          <div className="h-10 w-10 rounded-xl bg-primary flex items-center justify-center shadow-sm">
            <GraduationCap className="h-6 w-6 text-primary-foreground" />
          </div>
          <h1 className="text-2xl font-bold tracking-tight">EnCoach</h1>
        </div>

        <Card className="shadow-lg border-0 bg-card/90 backdrop-blur-sm">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-xl">Create an account</CardTitle>
            <CardDescription>Start your IELTS preparation journey</CardDescription>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form className="space-y-5" onSubmit={form.handleSubmit(onSubmit)}>
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Full name</FormLabel>
                      <FormControl>
                        <Input placeholder="Jane Doe" autoComplete="name" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Email</FormLabel>
                      <FormControl>
                        <Input
                          type="email"
                          placeholder="you@example.com"
                          autoComplete="email"
                          {...field}
                          onBlur={(e) => {
                            field.onBlur();
                            void verifyEmailBlur();
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Password</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showPassword ? "text" : "password"}
                            placeholder="••••••••"
                            autoComplete="new-password"
                            className="pr-10"
                            {...field}
                          />
                          <button
                            type="button"
                            className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                            onClick={() => setShowPassword((v) => !v)}
                            aria-label={showPassword ? "Hide password" : "Show password"}
                          >
                            {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                          </button>
                        </div>
                      </FormControl>
                      <div className="space-y-1 pt-1">
                        <Progress value={strength} className="h-1.5" />
                        <p className="text-xs text-muted-foreground">Strength: {strength}%</p>
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="confirm"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Confirm password</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showConfirm ? "text" : "password"}
                            placeholder="••••••••"
                            autoComplete="new-password"
                            className="pr-10"
                            {...field}
                          />
                          <button
                            type="button"
                            className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                            onClick={() => setShowConfirm((v) => !v)}
                            aria-label={showConfirm ? "Hide password" : "Show password"}
                          >
                            {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                          </button>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="role"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Role</FormLabel>
                      <FormControl>
                        <RadioGroup onValueChange={field.onChange} value={field.value} className="grid gap-2">
                          {(
                            [
                              ["academic_student", "Academic student"],
                              ["self_learner", "Self learner"],
                              ["teacher", "Teacher"],
                            ] as const
                          ).map(([value, label]) => (
                            <label
                              key={value}
                              className={cn(
                                "flex items-center gap-3 rounded-lg border p-3 cursor-pointer transition-colors",
                                field.value === value && "border-primary bg-primary/5",
                              )}
                            >
                              <RadioGroupItem value={value} id={`role-${value}`} />
                              <span className="text-sm font-medium">{label}</span>
                            </label>
                          ))}
                        </RadioGroup>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="rounded-lg border border-dashed bg-muted/30 p-4 space-y-2">
                  <p className="text-sm font-medium">CAPTCHA</p>
                  <div className="h-16 rounded-md bg-muted flex items-center justify-center text-xs text-muted-foreground">
                    Verification widget placeholder
                  </div>
                </div>

                {form.formState.errors.root && (
                  <p className="text-sm text-destructive text-center bg-destructive/10 rounded-md py-2 px-3">
                    {form.formState.errors.root.message}
                  </p>
                )}

                <Button type="submit" className="w-full" size="lg" disabled={register.isPending}>
                  {register.isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Creating account
                    </>
                  ) : (
                    "Create account"
                  )}
                </Button>
              </form>
            </Form>
            <p className="text-center text-sm text-muted-foreground mt-6">
              Already have an account?{" "}
              <Link to="/login" className="text-primary font-medium hover:underline">
                Sign in
              </Link>
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
