/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { toast } from "sonner";
import { registerSchema } from "@/zod/auth.validation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { DISTRICTS } from "@/context/CartContext";

export default function RegisterForm() {
  const emailRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);
  const nameRef = useRef<HTMLInputElement>(null);
  const mobileRef = useRef<HTMLInputElement>(null);
  const addressRef = useRef<HTMLInputElement>(null);
  const areaRef = useRef<HTMLInputElement>(null);
  const [city, setCity] = useState("dhaka");
  const imageRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  const [loading, setLoading] = useState(false);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setImagePreview(URL.createObjectURL(file));
    } else {
      setImagePreview(null);
    }
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    const email = emailRef.current?.value || "";
    const password = passwordRef.current?.value || "";
    const name = nameRef.current?.value || "";
    const mobile_number = mobileRef.current?.value || "";
    const address = addressRef.current?.value || "";
    const area = areaRef.current?.value || "";
    const file = imageRef.current?.files?.[0];

    const result = registerSchema.safeParse({
      email,
      password,
      name,
      mobile_number,
      address,
      area,
      city,
    });
    if (!result.success) {
      const fieldErrors = result.error.flatten().fieldErrors;
      const parsedErrors: Record<string, string> = {};
      Object.keys(fieldErrors).forEach((key) => {
        parsedErrors[key] = (fieldErrors as any)[key]?.[0] || "";
      });
      setErrors(parsedErrors);
      return;
    }

    const formData = new FormData();
    formData.append("email", result.data.email || "");
    formData.append("password", result.data.password);
    formData.append("name", result.data.name);
    formData.append("mobile_number", result.data.mobile_number);
    formData.append("address", result.data.address);
    formData.append("area", result.data.area);
    formData.append("city", result.data.city);
    if (file) {
      formData.append("image", file);
    }

    setLoading(true);
    const toastId = toast.loading("Creating your account...");
    try {
      const response = await fetch("/api/client/auth/register", {
        method: "POST",
        body: formData,
      });
      const apiResult = await response.json().catch(() => null);
      toast.dismiss(toastId);
      if (!response.ok || !apiResult?.success) {
        toast.error(apiResult?.message || "Registration failed. Mobile number might already be taken.");
        return;
      }
      toast.success("Account created successfully!");
      router.push("/");
      router.refresh();
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="border border-zinc-200/80 bg-white/70 shadow-xl backdrop-blur-md dark:border-zinc-800/80 dark:bg-zinc-900/70 rounded-md w-full max-w-2xl mx-auto">
      <CardHeader className="space-y-1 text-center py-4">
        <CardTitle className="text-xl lg:text-2xl font-black text-zinc-900 dark:text-white uppercase tracking-wider">
          Create Account
        </CardTitle>
        <CardDescription className="text-zinc-500 dark:text-zinc-400 text-xs">
          Register to shop your favorite pickles
        </CardDescription>
      </CardHeader>
      <CardContent className="pb-6">
        <form onSubmit={handleRegister} noValidate className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="name" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Full Name</Label>
              <Input
                id="name"
                ref={nameRef}
                placeholder="John Doe"
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
              />
              {errors.name && (
                <p className="text-red-500 text-xs mt-1">{errors.name}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="mobile_number" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Mobile Number</Label>
              <Input
                id="mobile_number"
                ref={mobileRef}
                placeholder="01712345678"
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
              />
              {errors.mobile_number && (
                <p className="text-red-500 text-xs mt-1">{errors.mobile_number}</p>
              )}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="email" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Email Address (Optional)</Label>
              <Input
                id="email"
                ref={emailRef}
                type="email"
                placeholder="you@example.com"
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
              />
              {errors.email && (
                <p className="text-red-500 text-xs mt-1">{errors.email}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="password" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Password</Label>
              <Input
                id="password"
                ref={passwordRef}
                type="password"
                placeholder="••••••••"
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
              />
              {errors.password && (
                <p className="text-red-500 text-xs mt-1">{errors.password}</p>
              )}
            </div>
          </div>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="address" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Street Address</Label>
              <Input
                id="address"
                ref={addressRef}
                placeholder="123 Main St, Apartment 4B"
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
              />
              {errors.address && (
                <p className="text-red-500 text-xs mt-1">{errors.address}</p>
              )}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="area" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Area</Label>
                <Input
                  id="area"
                  ref={areaRef}
                  placeholder="Gulshan"
                  className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
                />
                {errors.area && (
                  <p className="text-red-500 text-xs mt-1">{errors.area}</p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="city" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">City</Label>
                <div className="relative">
                  <select
                    id="city"
                    value={city}
                    onChange={(e) => setCity(e.target.value)}
                    className="w-full h-10 px-3.5 rounded-md border bg-zinc-50/50 dark:bg-zinc-950/50 border-zinc-200/80 dark:border-zinc-800 text-zinc-900 dark:text-white text-xs font-bold focus:outline-none cursor-pointer appearance-none"
                  >
                    {DISTRICTS.map((d) => (
                      <option key={d.value} value={d.value} className="bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white">
                        {d.name}
                      </option>
                    ))}
                  </select>
                  <div className="absolute inset-y-0 right-0 flex items-center pr-3.5 pointer-events-none">
                    <svg
                      className="w-3.5 h-3.5 text-zinc-500 dark:text-zinc-400"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2.5"
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                    </svg>
                  </div>
                </div>
                {errors.city && (
                  <p className="text-red-500 text-xs mt-1">{errors.city}</p>
                )}
              </div>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="image" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Profile Image (Optional)</Label>
            <div className="flex items-center gap-4">
              {imagePreview ? (
                <Image
                  src={imagePreview}
                  alt="Preview"
                  width={40}
                  height={40}
                  unoptimized
                  className="w-10 h-10 rounded-full object-cover border-2 border-brand-accent shadow-md shrink-0"
                />
              ) : (
                <div className="w-10 h-10 rounded-full bg-zinc-100 dark:bg-zinc-800 border border-dashed border-zinc-300 dark:border-zinc-700 flex items-center justify-center text-zinc-400 text-[10px] text-center shrink-0">
                  No Image
                </div>
              )}
              <Input
                id="image"
                type="file"
                ref={imageRef}
                accept="image/*"
                onChange={handleImageChange}
                className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent cursor-pointer flex-1 rounded-md"
              />
            </div>
          </div>

          <Button
            type="submit"
            disabled={loading}
            className="w-full rounded-md bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black text-xs uppercase tracking-wider h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)] border-none mt-2"
          >
            {loading ? "Registering..." : "Create Account"}
          </Button>

          <div className="flex items-center my-3">
            <div className="flex-1 border-t border-zinc-200 dark:border-zinc-800"></div>
            <span className="px-3 text-[10px] text-zinc-500 dark:text-zinc-400 uppercase tracking-wider font-bold">Or</span>
            <div className="flex-1 border-t border-zinc-200 dark:border-zinc-800"></div>
          </div>

          <Button
            type="button"
            onClick={() => {
              const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:3001/api/v1";
              window.location.href = `${backendUrl}/client/auth/google`;
            }}
            variant="outline"
            className="w-full rounded-md border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-950 text-zinc-700 dark:text-zinc-300 font-bold text-xs uppercase tracking-wider h-9 hover:bg-zinc-50 dark:hover:bg-zinc-900 transition-all duration-300 flex items-center justify-center gap-2"
          >
            <svg className="h-4 w-4 text-red-500" aria-hidden="true" focusable="false" data-prefix="fab" data-icon="google" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 512">
              <path fill="currentColor" d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"></path>
            </svg>
            Continue with Google Signup
          </Button>

          <div className="text-center text-sm text-zinc-500 dark:text-zinc-400">
            Already have an account?{" "}
            <Link
              href="/login"
              onClick={(e) => {
                e.preventDefault();
                router.push("/login");
              }}
              className="font-bold text-brand-accent hover:text-brand-accent-hover transition-colors uppercase tracking-wider text-[10px]"
            >
              Sign In
            </Link>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
