"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Mail,
  Lock,
  Phone,
  User,
  KeyRound,
  ArrowLeft,
  ShieldCheck,
  Eye,
  EyeOff,
} from "lucide-react";
import Link from "next/link";
import { showToast } from "@/lib/toast";
import { useRegister, useVerifyOtp } from "@/modules/auth/hooks/auth.hooks";
import { useAppDispatch } from "@/lib/store";
import { setCurrentUser } from "@/modules/auth/slices/authSlice";
import { capitalizeFirstLetter } from "@/lib/capitalize";

type FieldErrors = Record<string, string>;

function getFieldErrors(error: any): FieldErrors {
  const fieldErrors = error?.response?.data?.details?.fieldErrors;
  if (!fieldErrors) return {};
  const flat: FieldErrors = {};
  Object.entries(fieldErrors).forEach(([key, val]) => {
    flat[key] = Array.isArray(val) ? val[0] : (val as string);
  });
  return flat;
}

function FieldError({ msg }: { msg?: string }) {
  if (!msg) return null;
  return <p className="text-xs text-destructive mt-1">{msg}</p>;
}

export default function Register() {
  const [step, setStep] = useState<"register" | "otp">("register");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [phone, setPhone] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [otp, setOtp] = useState("");
  const [otpError, setOtpError] = useState("");
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const router = useRouter();

  const { mutate: registerUser, isPending: isRegistering } = useRegister();
  const { mutate: verifyOtpMutate, isPending: isVerifying } = useVerifyOtp();
  const dispatch = useAppDispatch();

  // --- client-side register validation ---
  function validateRegister(): FieldErrors {
    const errs: FieldErrors = {};
    if (!name.trim() || name.trim().length < 2)
      errs.name = "Name must be at least 2 characters";
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
      errs.email = "Enter a valid email address";
    if (!phone.trim() || !/^[0-9]{10,15}$/.test(phone.replace(/\s+/g, "")))
      errs.phone = "Enter a valid phone number (10–15 digits)";
    if (!password) errs.password = "Password is required";
    else if (password.length < 8)
      errs.password = "Password must be at least 8 characters";
    else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password))
      errs.password = "Must contain uppercase, lowercase and a number";
    return errs;
  }

  const handleRegister = (e: React.FormEvent) => {
    e.preventDefault();
    const errs = validateRegister();
    if (Object.keys(errs).length > 0) {
      setFieldErrors(errs);
      return;
    }
    setFieldErrors({});
    registerUser(
      { name: name.trim(), email: email.trim(), password, phone: phone.trim() },
      {
        onSuccess: () => setStep("otp"),
        // onError: (error: any) => {
        //   const status = error?.response?.status;
        //   const message: string = error?.response?.data?.message || "";
        //   const serverErrs = getFieldErrors(error);

        //   if (Object.keys(serverErrs).length > 0) {
        //     // Backend returned fieldErrors (e.g. phone unique constraint via Prisma P2002)
        //     setFieldErrors(serverErrs);
        //   } else if (status === 409) {
        //     // ConflictError thrown directly in service (before DB)
        //     if (message.toLowerCase().includes("phone")) {
        //       setFieldErrors({ phone: "This phone number is already registered." });
        //     } else {
        //       setFieldErrors({ email: "This email is already registered. Please sign in instead." });
        //     }
        //   }
        // },

        onError: (error: any) => {
          const status = error?.response?.status;
          const message: string =
            error?.response?.data?.error ||
            error?.response?.data?.message ||
            "";
          const serverErrs = getFieldErrors(error);

          if (Object.keys(serverErrs).length > 0) {
            setFieldErrors(serverErrs);
            return;
          }

          const lower = message.toLowerCase();
          if (status === 409 || lower.includes("already registered")) {
            if (lower.includes("phone")) {
              setFieldErrors({
                phone: message || "This phone number is already registered.",
              });
            } else {
              setFieldErrors({
                email:
                  message ||
                  "This email is already registered. Please sign in instead.",
              });
            }
            return;
          }

          showToast.error(message || "Registration failed. Please try again.");
        },
      }
    );
  };

  const handleVerifyOtp = (e: React.FormEvent) => {
    e.preventDefault();
    if (!otp || otp.length < 6) {
      setOtpError("Please enter the 6-digit OTP code");
      return;
    }
    setOtpError("");
    verifyOtpMutate(
      { email, otp, purpose: "EMAIL_VERIFICATION" },
      {
        onSuccess: (data) => {
          showToast.success("Email verified! Welcome to TaxFend.");
          router.push("/onboarding/create-organization");
          setTimeout(() => {
            if (data?.user) dispatch(setCurrentUser(data.user));
          }, 100);
        },
        onError: (error: any) => {
          const msg =
            error?.response?.data?.message || "Invalid OTP. Please try again.";
          setOtpError(msg);
          setOtp("");
        },
      }
    );
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4 py-12 relative overflow-hidden">
      <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px] pointer-events-none" />

      <Card className="w-full max-w-md border-border bg-card shadow-xl relative overflow-hidden">
        <CardHeader className="space-y-1 text-center relative">
          <div className="mx-auto bg-primary/10 w-12 h-12 rounded-2xl flex items-center justify-center mb-2 border border-primary/20">
            {step === "register" ? (
              <ShieldCheck className="h-6 w-6 text-primary" />
            ) : (
              <KeyRound className="h-6 w-6 text-primary" />
            )}
          </div>
          <CardTitle className="text-2xl font-bold tracking-tight text-card-foreground">
            {step === "register"
              ? "Create your TaxFend account"
              : "Email Verification"}
          </CardTitle>
          <CardDescription className="text-muted-foreground">
            {step === "register"
              ? "Sign up to get started with TaxFend"
              : `Enter the 6-digit OTP code sent to ${email}`}
          </CardDescription>
        </CardHeader>

        <CardContent className="space-y-4 relative">
          {step === "register" ? (
            <form onSubmit={handleRegister} className="space-y-4" noValidate>
              {/* Name */}
              <div className="space-y-1">
                <Label
                  htmlFor="name"
                  className="text-foreground flex items-center gap-2"
                >
                  <User className="h-4 w-4 text-primary" /> Full Name
                </Label>
                <Input
                  id="name"
                  placeholder="John Doe"
                  value={name}
                  onChange={(e) => {
                    setName(capitalizeFirstLetter(e.target.value));
                    setFieldErrors((p) => ({ ...p, name: "" }));
                  }}
                  className={`bg-background border-input ${
                    fieldErrors.name
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                />
                <FieldError msg={fieldErrors.name} />
              </div>

              {/* Email */}
              <div className="space-y-1">
                <Label
                  htmlFor="email"
                  className="text-foreground flex items-center gap-2"
                >
                  <Mail className="h-4 w-4 text-primary" /> Email Address
                </Label>
                <Input
                  id="email"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    setFieldErrors((p) => ({ ...p, email: "" }));
                  }}
                  className={`bg-background border-input ${
                    fieldErrors.email
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                />
                <FieldError msg={fieldErrors.email} />
              </div>

              {/* Phone */}
              <div className="space-y-1">
                <Label
                  htmlFor="phone"
                  className="text-foreground flex items-center gap-2"
                >
                  <Phone className="h-4 w-4 text-primary" /> Phone Number
                </Label>
                <Input
                  id="phone"
                  type="tel"
                  placeholder="9876543210"
                  value={phone}
                  onChange={(e) => {
                    setPhone(e.target.value);
                    setFieldErrors((p) => ({ ...p, phone: "" }));
                  }}
                  className={`bg-background border-input ${
                    fieldErrors.phone
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                />
                <FieldError msg={fieldErrors.phone} />
              </div>

              {/* Password */}
              <div className="space-y-1">
                <Label
                  htmlFor="password"
                  className="text-foreground flex items-center gap-2"
                >
                  <Lock className="h-4 w-4 text-primary" /> Password
                </Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      setFieldErrors((p) => ({ ...p, password: "" }));
                    }}
                    className={`bg-background border-input pr-10 ${
                      fieldErrors.password
                        ? "border-destructive focus-visible:ring-destructive"
                        : ""
                    }`}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                    tabIndex={-1}
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </button>
                </div>
                <FieldError msg={fieldErrors.password} />
                {!fieldErrors.password && (
                  <p className="text-xs text-muted-foreground">
                    Min 8 chars · uppercase · lowercase · number
                  </p>
                )}
              </div>

              <Button
                type="submit"
                className="w-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium h-10 shadow-sm"
                disabled={isRegistering}
              >
                {isRegistering ? "Sending OTP..." : "Create Account"}
              </Button>
            </form>
          ) : (
            <form onSubmit={handleVerifyOtp} className="space-y-6" noValidate>
              <div className="space-y-2 text-center">
                <Label htmlFor="otp" className="text-foreground font-medium">
                  Enter 6-Digit Verification Code
                </Label>
                <Input
                  id="otp"
                  type="text"
                  inputMode="numeric"
                  maxLength={6}
                  placeholder="123456"
                  value={otp}
                  onChange={(e) => {
                    setOtp(e.target.value.replace(/\D/g, ""));
                    setOtpError("");
                  }}
                  className={`bg-background border-input text-center text-2xl tracking-[0.5em] font-mono h-14 ${
                    otpError
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                  autoFocus
                />
                {otpError && (
                  <p className="text-sm text-destructive font-medium">
                    {otpError}
                  </p>
                )}
              </div>

              <div className="grid grid-cols-2 gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    setStep("register");
                    setOtp("");
                    setOtpError("");
                  }}
                  className="h-10 border-border text-foreground hover:bg-secondary/20 gap-2"
                  disabled={isVerifying}
                >
                  <ArrowLeft className="h-4 w-4" /> Back
                </Button>
                <Button
                  type="submit"
                  className="h-10 bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm"
                  disabled={isVerifying || otp.length < 6}
                >
                  {isVerifying ? "Verifying..." : "Verify"}
                </Button>
              </div>
            </form>
          )}
        </CardContent>

        <CardFooter className="flex flex-col space-y-2 border-t border-border pt-4">
          <p className="text-xs text-muted-foreground text-center">
            Already have an account?{" "}
            <Link
              href="/login"
              className="text-primary hover:underline font-medium"
            >
              Sign In
            </Link>
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
