'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Eye, EyeOff, LogIn, Building2, AlertCircle } from 'lucide-react';
import dealerApi from '@/lib/dealer-axios';
import { useDealerAuthStore } from '@/store/dealer-auth';
import MathCaptcha from '@/components/MathCaptcha';

export default function DealerLoginPage() {
  const router = useRouter();
  const { setAuth } = useDealerAuthStore();
  const [form, setForm] = useState({ customer_code_bmu: '', password: '' });
  const [loading, setLoading] = useState(false);
  const [showPw, setShowPw] = useState(false);
  const [error, setError] = useState('');
  const [errorCode, setErrorCode] = useState('');
  const [captchaOk, setCaptchaOk] = useState(false);
  const [captchaKey, setCaptchaKey] = useState(0);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setErrorCode('');
    
    if (!captchaOk) { 
      setError('Selesaikan verifikasi CAPTCHA terlebih dahulu.'); 
      return; 
    }
    
    setLoading(true);
    
    try {
      const res = await dealerApi.post('/dealer/login', form);
      setAuth(res.data.data, res.data.token);
      router.push('/dealer/dashboard');
    } catch (err: any) {
      const code = err.response?.data?.code;
      const message = err.response?.data?.message;
      const errors = err.response?.data?.errors;
      
      setErrorCode(code || '');
      
      // Handle specific error codes
      if (code === 'INACTIVE') {
        setError('Akun Anda tidak aktif. Silakan hubungi administrator.');
      } else if (code === 'BLOCKED') {
        setError(message || 'Akun Anda diblokir. Silakan hubungi administrator.');
      } else if (errors?.customer_code_bmu) {
        setError(errors.customer_code_bmu[0]);
      } else {
        setError(message || 'Customer Code BMU atau password salah.');
      }
      
      setCaptchaOk(false);
      setCaptchaKey(k => k + 1);
    } finally {
      setLoading(false);
    }
  };

  const inputCls = "w-full h-11 bg-gray-50 border border-gray-200 rounded-xl px-4 text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-400 transition";

  return (
    <div className="min-h-screen w-full bg-gradient-to-br from-blue-500 via-blue-600 to-indigo-700 flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-white/20 backdrop-blur-sm rounded-2xl mb-4 shadow-lg">
            <Building2 className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl font-extrabold text-white">Login Dealer</h1>
          <p className="text-white/80 text-sm mt-1">Gunakan kredensial BMU Portal Anda</p>
        </div>

        <div className="bg-white rounded-3xl p-7 shadow-2xl">
          {error && (
            <div className={`border text-sm rounded-xl px-4 py-3 mb-4 flex items-start gap-2 ${
              errorCode === 'INACTIVE' || errorCode === 'BLOCKED' 
                ? 'bg-red-50 border-red-200 text-red-700' 
                : 'bg-red-50 border-red-200 text-red-700'
            }`}>
              <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
              <p>{error}</p>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="text-xs font-medium text-gray-600 mb-1.5 block">Customer Code BMU</label>
              <input 
                value={form.customer_code_bmu} 
                onChange={e => setForm(f => ({ ...f, customer_code_bmu: e.target.value }))}
                className={inputCls} 
                placeholder="Contoh: C200100000073" 
                required 
                autoComplete="username" 
              />
              <p className="text-xs text-gray-500 mt-1.5">
                Gunakan Customer Code BMU yang sama dengan BMU Portal
              </p>
            </div>

            <div>
              <label className="text-xs font-medium text-gray-600 mb-1.5 block">Password</label>
              <div className="relative">
                <input 
                  type={showPw ? 'text' : 'password'} 
                  value={form.password}
                  onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
                  className={inputCls + ' pr-11'} 
                  placeholder="Password BMU Portal Anda" 
                  required 
                  autoComplete="current-password"
                />
                <button 
                  type="button" 
                  onClick={() => setShowPw(!showPw)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              <p className="text-xs text-gray-500 mt-1.5">
                Gunakan password yang sama dengan BMU Portal
              </p>
            </div>

            <MathCaptcha key={captchaKey} onVerified={setCaptchaOk} />

            <button 
              type="submit" 
              disabled={loading || !captchaOk}
              className="w-full h-11 bg-blue-500 text-white font-bold rounded-xl shadow-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                  <span>Memverifikasi...</span>
                </>
              ) : (
                <>
                  <LogIn className="h-4 w-4" />
                  <span>Login</span>
                </>
              )}
            </button>
          </form>

          <div className="mt-6 pt-6 border-t border-gray-100">
            <div className="bg-blue-50 border border-blue-100 rounded-xl px-4 py-3">
              <p className="text-xs text-blue-800 font-medium mb-1">ℹ️ Informasi</p>
              <p className="text-xs text-blue-700">
                Gunakan Akun BMU Portal Anda untuk login.
              </p>
            </div>
          </div>
        </div>

        <p className="text-center text-white/80 text-xs mt-5">
          <Link href="/" className="hover:text-white transition">← Kembali ke beranda</Link>
        </p>
      </div>
    </div>
  );
}
