import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { loginUser } from "../services/auth-api";
import { useAuthStore } from "../hooks/use-auth";
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import { Hexagon, Lock, Mail, ArrowRight, Eye, EyeOff } from "lucide-react";
import { motion } from "framer-motion";
import { useToast } from "../hooks/use-toast";

const loginSchema = z.object({
  email: z.string().email({ message: "Invalid email address" }),
  password: z
    .string()
    .min(6, { message: "Password must be at least 6 characters" }),
});

type LoginFormValues = z.infer<typeof loginSchema>;

export const LoginPage = () => {
  const { success, error: toastError } = useToast();
  const [error, setError] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const setAuth = useAuthStore((state) => state.setAuth);
  const navigate = useNavigate();

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
  });

  const onSubmit = async (data: LoginFormValues) => {
    try {
      setError(null);
      const response = await loginUser({
        email: data.email,
        password: data.password,
      });
      setAuth(response);
      success("Successfully signed in", `Welcome back, ${response.user.email}!`);
      if (response.user.role === "ADMIN") {
        navigate("/admin");
      } else {
        navigate("/client");
      }
    } catch (err: any) {
      const errMsg = err.response?.data?.error || "Authentication failed. Verify credentials.";
      setError(errMsg);
      toastError("Authentication failed", errMsg);
    }
  };

  return (
    <div className="min-h-screen bg-ink-50 flex flex-col justify-between items-center p-6 md:p-12 relative overflow-hidden font-sans transition-colors duration-500">
      {/* Monochromatic Soft Background Blurs */}
      <div className="absolute top-1/4 left-1/4 w-[600px] h-[600px] bg-ink-900/5 rounded-full blur-[150px] pointer-events-none" />
      <div className="absolute bottom-1/4 right-1/4 w-[700px] h-[700px] bg-ink-900/5 rounded-full blur-[150px] pointer-events-none" />

      {/* Spacer to push content down slightly on desktop for better centering */}
      <div className="hidden md:block h-6" />

      <motion.div
        initial={{ opacity: 0, y: 30 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 1, ease: [0.16, 1, 0.3, 1] }}
        className="w-full max-w-5xl relative z-10 grid grid-cols-1 md:grid-cols-12 gap-12 md:gap-16 items-center my-auto"
      >
        {/* Left Column - Partner Explanation */}
        <div className="md:col-span-6 lg:col-span-7 flex flex-col justify-center text-left">
          <h1 className="text-3xl lg:text-4xl font-extrabold text-ink-900 tracking-tight leading-tight">
            <span className="gradient-text">Tech4Biz Channel Partner</span>
          </h1>
          <p className="text-ink-500 text-sm mt-5 font-medium leading-relaxed max-w-lg">
            Expand your business by partnering with Tech4Biz and unlock new
            opportunities for growth through our innovative technology
            solutions. Join our partner network to access exclusive resources,
            dedicated support, and a platform designed to help you succeed.
          </p>
        </div>

        {/* Right Column - Login Component */}
        <div className="md:col-span-6 lg:col-span-5 w-full max-w-sm justify-self-center md:justify-self-end">
          <div className="bg-ink-0 border border-ink-200 rounded-2xl shadow-xl p-8 md:p-10 relative overflow-hidden">
            <div className="absolute top-0 inset-x-0 h-px bg-gradient-to-r from-transparent via-ink-300 to-transparent" />

            <div className="flex flex-col items-center mb-8 text-center">
              <div className="relative flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-tr from-ink-900 to-ink-800 shadow-md mb-6">
                <Hexagon className="text-ink-0 w-8 h-8 absolute" />
              </div>
              <h2 className="text-2xl font-bold text-ink-900 tracking-tight">
                Channel Portal
              </h2>
              <p className="text-ink-500 text-[10px] mt-1.5 font-bold uppercase tracking-wider">
                Authorized Access Only
              </p>
            </div>

            {error && (
              <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-red-500/10 border border-red-500/20 text-red-600 dark:text-red-400 p-3 rounded-lg text-xs mb-6 flex items-center gap-2.5 font-medium shadow-sm font-sans"
              >
                <div className="w-1.5 h-1.5 rounded-full bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.5)] shrink-0" />
                {error}
              </motion.div>
            )}

            <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
              <div className="space-y-1.5">
                <label className="block text-[10px] font-bold text-ink-500 uppercase tracking-wider">
                  Work Email
                </label>
                <div className="relative group">
                  <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                    <Mail
                      className={`w-4 h-4 transition-colors ${errors.email ? "text-red-400" : "text-ink-400 group-focus-within:text-ink-900"}`}
                    />
                  </div>
                  <input
                    type="email"
                    {...register("email")}
                    className={`w-full bg-ink-50 border ${errors.email ? "border-red-500/50 focus:border-red-500" : "border-ink-200 focus:border-ink-900/50"} rounded-xl py-2.5 pl-11 pr-4 text-xs font-medium text-ink-900 placeholder-ink-400 outline-none transition-all focus:bg-ink-0 focus:ring-4 ring-ink-900/10 font-sans`}
                    placeholder="admin@tech4biz.com"
                  />
                </div>
                {errors.email && (
                  <p className="text-red-500 dark:text-red-400 text-[10px] mt-1 font-bold font-sans">
                    {errors.email.message}
                  </p>
                )}
              </div>

              <div className="space-y-1.5">
                <div className="flex justify-between items-center">
                  <label className="block text-[10px] font-bold text-ink-500 uppercase tracking-wider">
                    Password
                  </label>
                  <a
                    href="#"
                    className="text-[10px] font-bold text-ink-500 hover:text-ink-900 transition-colors tracking-wider"
                  >
                    RECOVERY?
                  </a>
                </div>
                <div className="relative group">
                  <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                    <Lock
                      className={`w-4 h-4 transition-colors ${errors.password ? "text-red-400" : "text-ink-400 group-focus-within:text-ink-900"}`}
                    />
                  </div>
                  <input
                    type={showPassword ? "text" : "password"}
                    {...register("password")}
                    className={`w-full bg-ink-50 border ${errors.password ? "border-red-500/50 focus:border-red-500" : "border-ink-200 focus:border-ink-900/50"} rounded-xl py-2.5 pl-11 pr-11 text-xs font-medium text-ink-900 placeholder-ink-400 outline-none transition-all focus:bg-ink-0 focus:ring-4 ring-ink-900/10 font-sans`}
                    placeholder="••••••••"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3.5 flex items-center text-ink-400 hover:text-ink-950 focus:outline-none transition-colors"
                  >
                    {showPassword ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                </div>
                {errors.password && (
                  <p className="text-red-500 dark:text-red-400 text-[10px] mt-1 font-bold font-sans">
                    {errors.password.message}
                  </p>
                )}
              </div>

              <button
                type="submit"
                disabled={isSubmitting}
                className="group relative w-full bg-ink-900 text-ink-0 font-bold text-xs uppercase tracking-wider py-2.5 px-4 rounded-xl hover:bg-ink-800 transition-all duration-300 disabled:opacity-70 disabled:cursor-not-allowed mt-4 overflow-hidden flex items-center justify-center gap-2 shadow-md font-sans cursor-pointer"
              >
                {isSubmitting ? "AUTHENTICATING..." : "SECURE SIGN IN"}
                {!isSubmitting && (
                  <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                )}
              </button>
            </form>
          </div>
        </div>
      </motion.div>

      <p className="text-center text-ink-400 text-[10px] font-bold tracking-wider uppercase mt-8 relative z-10">
        © 2026 Tech4Biz Solutions.
      </p>
    </div>
  );
};
export default LoginPage;
