'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { loginSchema } from '@/lib/schemas/authSchema';
import { FormField } from '@/components/common/FormField';
import { login } from '@/lib/api/auth';
import { useAuthStore, AuthStore } from '@/lib/stores/authStore';
import { toast } from '@/lib/stores/notificationStore';
import { Eye, EyeOff, Loader2, KeyRound, User, Info, ArrowRight } from 'lucide-react';
import Link from 'next/link';
import { cn } from '@/lib/utils';

type LoginFormValues = {
  username: string;
  password: string;
  rememberMe?: boolean;
};

export function LoginForm() {
  const router = useRouter();
  const setUser = useAuthStore((state: AuthStore) => state.setUser);
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      username: '',
      password: '',
      rememberMe: false,
    },
  });

  const onSubmit = async (values: LoginFormValues) => {
    setIsLoading(true);
    try {
      const response = await login(values);
      if (response.success && response.data) {
        setUser(response.data);
        toast.success(response.message);

        // Redirect to user dashboard based on role
        const targetDashboard =
          response.data.role === 'mahasiswa'
            ? '/dashboard/mahasiswa'
            : response.data.role === 'operator_pt'
              ? '/dashboard/operator'
              : '/dashboard/admin';

        router.push(targetDashboard);
        router.refresh();
      } else {
        toast.error(response.message || 'Email atau password salah');
      }
    } catch (error) {
      toast.error('Terjadi kesalahan sistem. Silakan coba beberapa saat lagi.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="w-full flex flex-col">
      <div className="space-y-3 mb-8 text-center">
        <h2 className="text-3xl font-black text-slate-900 tracking-tight">
          Selamat Datang
        </h2>
        <p className="text-sm text-slate-500 font-medium leading-relaxed">
          Masuk ke akun SIMKATMAWA untuk melanjutkan akses layanan.
        </p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-5 flex-grow flex flex-col">
        <FormField label="Username" error={errors.username?.message}>
          <div className="relative group">
            <span className="absolute inset-y-0 left-0 pl-4 flex items-center text-slate-400 group-focus-within:text-primary transition-colors">
              <User className="h-5 w-5" />
            </span>
            <input
              type="text"
              disabled={isLoading}
              placeholder="Masukkan username Anda"
              {...register('username')}
              className={cn(
                "w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-100 rounded-2xl text-sm placeholder:text-slate-400 text-slate-900 font-medium transition-all disabled:opacity-50",
                "focus:outline-none focus:border-primary/30 focus:ring-4 focus:ring-primary/10 hover:border-slate-200"
              )}
            />
          </div>
        </FormField>

        <FormField label="Password" error={errors.password?.message}>
          <div className="relative group">
            <span className="absolute inset-y-0 left-0 pl-4 flex items-center text-slate-400 group-focus-within:text-primary transition-colors">
              <KeyRound className="h-5 w-5" />
            </span>
            <input
              type={showPassword ? 'text' : 'password'}
              disabled={isLoading}
              placeholder="••••••••"
              {...register('password')}
              className={cn(
                "w-full pl-12 pr-12 py-3.5 bg-white border-2 border-slate-100 rounded-2xl text-sm placeholder:text-slate-400 text-slate-900 font-medium transition-all disabled:opacity-50",
                "focus:outline-none focus:border-primary/30 focus:ring-4 focus:ring-primary/10 hover:border-slate-200"
              )}
            />
            <button
              type="button"
              disabled={isLoading}
              onClick={() => setShowPassword(!showPassword)}
              className="absolute inset-y-0 right-0 pr-4 flex items-center text-slate-400 hover:text-slate-600 transition-colors"
            >
              {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
            </button>
          </div>
        </FormField>

        <div className="flex items-center justify-between pb-2 select-none">
          <label className="flex items-center gap-2 cursor-pointer group">
            <input
              type="checkbox"
              {...register('rememberMe')}
              className="peer sr-only"
            />
            <div className="h-5 w-5 rounded-lg border-2 border-slate-100 bg-slate-50 transition-all peer-checked:bg-primary peer-checked:border-primary flex items-center justify-center group-hover:border-slate-200 peer-focus-visible:ring-4 peer-focus-visible:ring-primary/10 [&_svg]:scale-0 peer-checked:[&_svg]:scale-100">
              <svg
                className="h-3 w-3 text-white transition-transform"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth="3.5"
              >
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <span className="text-xs font-bold text-slate-500 group-hover:text-slate-700 transition-colors">
              Ingat Saya
            </span>
          </label>
        </div>

        <button
          type="submit"
          disabled={isLoading}
          className="group w-full flex items-center justify-center gap-2 py-4 bg-gradient-to-r from-primary to-primary-dark text-white font-bold rounded-2xl text-sm shadow-[0_8px_20px_rgb(37,99,235,0.25)] hover:shadow-[0_8px_25px_rgb(37,99,235,0.35)] hover:-translate-y-0.5 transition-all duration-200 disabled:opacity-50 disabled:hover:translate-y-0"
        >
          <span className="flex items-center gap-2">
            {isLoading ? (
              <>
                <Loader2 className="h-5 w-5 animate-spin" />
                Memproses...
              </>
            ) : (
              <>
                Login
                <ArrowRight className="h-4 w-4 group-hover:translate-x-1 transition-transform" />
              </>
            )}
          </span>
        </button>
      </form>
    </div>
  );
}
