'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 { registrasiSchema } from '@/lib/schemas/authSchema';
import { FormField } from '@/components/common/FormField';
import { registrasi } from '@/lib/api/auth';
import { useAuthStore, AuthStore } from '@/lib/stores/authStore';
import { toast } from '@/lib/stores/notificationStore';
import { Eye, EyeOff, Loader2, User, Mail, GraduationCap, Building2, KeyRound } from 'lucide-react';
import Link from 'next/link';

type RegistrasiFormValues = {
  name: string;
  email: string;
  nimOrNidn: string;
  perguruanTinggiName: string;
  role: 'mahasiswa' | 'operator_pt';
  password: string;
  confirmPassword: string;
};

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

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<RegistrasiFormValues>({
    resolver: zodResolver(registrasiSchema),
    defaultValues: {
      name: '',
      email: '',
      nimOrNidn: '',
      perguruanTinggiName: '',
      role: 'mahasiswa',
      password: '',
      confirmPassword: '',
    },
  });

  const selectedRole = watch('role');

  const onSubmit = async (values: RegistrasiFormValues) => {
    setIsLoading(true);
    try {
      const response = await registrasi(values);
      if (response.success && response.data) {
        setUser(response.data);
        toast.success(response.message);
        
        // Redirect to respective dashboard
        const targetDashboard =
          response.data.role === 'mahasiswa'
            ? '/dashboard/mahasiswa'
            : '/dashboard/operator';
        
        router.push(targetDashboard);
        router.refresh();
      } else {
        toast.error(response.message || 'Pendaftaran gagal');
      }
    } catch (error) {
      toast.error('Terjadi kesalahan sistem. Silakan coba beberapa saat lagi.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6 w-full">
      <div className="space-y-2 text-center">
        <h2 className="text-2xl sm:text-3xl font-extrabold text-text-primary tracking-tight">
          Registrasi Akun Baru
        </h2>
        <p className="text-sm text-text-muted font-medium">
          Daftarkan diri Anda untuk mulai melaporkan prestasi dan kinerja
        </p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        {/* Role Toggle Select */}
        <div className="grid grid-cols-2 gap-3 bg-surface p-1.5 rounded-2xl border border-text-muted/10">
          <label className="cursor-pointer">
            <input
              type="radio"
              value="mahasiswa"
              {...register('role')}
              className="peer sr-only"
            />
            <div className="text-center py-2.5 rounded-xl text-xs font-bold transition-all peer-checked:bg-white peer-checked:text-primary peer-checked:shadow-sm text-text-muted">
              Mahasiswa
            </div>
          </label>
          <label className="cursor-pointer">
            <input
              type="radio"
              value="operator_pt"
              {...register('role')}
              className="peer sr-only"
            />
            <div className="text-center py-2.5 rounded-xl text-xs font-bold transition-all peer-checked:bg-white peer-checked:text-primary peer-checked:shadow-sm text-text-muted">
              Operator PT
            </div>
          </label>
        </div>
        {errors.role && (
          <p className="text-xs text-danger font-semibold text-center">{errors.role.message}</p>
        )}

        <FormField label="Nama Lengkap" error={errors.name?.message}>
          <div className="relative">
            <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted">
              <User className="h-4 w-4" />
            </span>
            <input
              type="text"
              disabled={isLoading}
              placeholder="Nama Lengkap Anda"
              {...register('name')}
              className="w-full pl-10 pr-4 py-3 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all disabled:opacity-50"
            />
          </div>
        </FormField>

        <FormField label="Email" error={errors.email?.message}>
          <div className="relative">
            <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted">
              <Mail className="h-4 w-4" />
            </span>
            <input
              type="email"
              disabled={isLoading}
              placeholder="nama@email.com"
              {...register('email')}
              className="w-full pl-10 pr-4 py-3 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all disabled:opacity-50"
            />
          </div>
        </FormField>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <FormField
            label={selectedRole === 'mahasiswa' ? 'NIM' : 'NIDN'}
            error={errors.nimOrNidn?.message}
          >
            <div className="relative">
              <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted">
                <GraduationCap className="h-4 w-4" />
              </span>
              <input
                type="text"
                disabled={isLoading}
                placeholder={selectedRole === 'mahasiswa' ? 'Contoh: 12022030' : 'Contoh: 00120869'}
                {...register('nimOrNidn')}
                className="w-full pl-10 pr-4 py-3 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all disabled:opacity-50"
              />
            </div>
          </FormField>

          <FormField label="Perguruan Tinggi" error={errors.perguruanTinggiName?.message}>
            <div className="relative">
              <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted">
                <Building2 className="h-4 w-4" />
              </span>
              <input
                type="text"
                disabled={isLoading}
                placeholder="Nama Kampus Anda"
                {...register('perguruanTinggiName')}
                className="w-full pl-10 pr-4 py-3 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all disabled:opacity-50"
              />
            </div>
          </FormField>
        </div>

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

        <FormField label="Konfirmasi Password" error={errors.confirmPassword?.message}>
          <div className="relative">
            <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted">
              <KeyRound className="h-4 w-4" />
            </span>
            <input
              type={showConfirmPassword ? 'text' : 'password'}
              disabled={isLoading}
              placeholder="••••••••"
              {...register('confirmPassword')}
              className="w-full pl-10 pr-12 py-3 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all disabled:opacity-50"
            />
            <button
              type="button"
              disabled={isLoading}
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-text-muted hover:text-text-primary transition-colors"
            >
              {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </FormField>

        <button
          type="submit"
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 py-3 bg-primary hover:bg-primary-dark text-white font-semibold rounded-xl text-sm shadow-md shadow-primary/20 hover:shadow-lg transition-all duration-200 disabled:opacity-50"
        >
          {isLoading ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              Memproses...
            </>
          ) : (
            'Daftar Sekarang'
          )}
        </button>
      </form>

      <div className="text-center text-xs text-text-muted font-medium">
        Sudah memiliki akun?{' '}
        <Link href="/login" className="text-primary font-bold hover:underline">
          Masuk Sekarang
        </Link>
      </div>
    </div>
  );
}
