import React, { useState } from 'react';
import { X, Truck, Loader2, CheckCircle2 } from 'lucide-react';
import { useAuth, ROLES, Role } from '@/contexts/AuthContext';

interface Props {
  open: boolean;
  close: () => void;
}

const AuthModal: React.FC<Props> = ({ open, close }) => {
  const { signIn, signUp } = useAuth();
  const [mode, setMode] = useState<'login' | 'signup'>('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [fullName, setFullName] = useState('');
  const [role, setRole] = useState<Role>('Dispatcher');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [signedUp, setSignedUp] = useState(false);

  if (!open) return null;

  const reset = () => {
    setError('');
    setPassword('');
    setSignedUp(false);
  };

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!email || !password) {
      setError('Email and password are required.');
      return;
    }
    setLoading(true);
    if (mode === 'login') {
      const { error } = await signIn(email, password);
      setLoading(false);
      if (error) {
        setError(error);
        return;
      }
      close();
    } else {
      const { error } = await signUp(email, password, fullName, role);
      setLoading(false);
      if (error) {
        setError(error);
        return;
      }
      setSignedUp(true);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={close}>
      <div className="bg-white rounded-2xl w-full max-w-md overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2">
            <div className="w-9 h-9 rounded-lg bg-[#0B3D91] flex items-center justify-center">
              <Truck className="w-5 h-5 text-white" />
            </div>
            <h2 className="font-semibold text-slate-900">
              {mode === 'login' ? 'Sign in to FleetFlow' : 'Create your account'}
            </h2>
          </div>
          <button onClick={close} className="text-slate-400 hover:text-slate-600">
            <X className="w-5 h-5" />
          </button>
        </div>

        {signedUp ? (
          <div className="p-8 text-center">
            <CheckCircle2 className="w-12 h-12 text-[#00C853] mx-auto mb-3" />
            <h3 className="font-semibold text-slate-900">Account created!</h3>
            <p className="text-sm text-slate-500 mt-1">
              You can now sign in with your email and password.
            </p>
            <button
              onClick={() => { setMode('login'); reset(); }}
              className="mt-5 w-full py-2.5 rounded-lg bg-[#0B3D91] text-white text-sm font-semibold"
            >
              Go to Sign In
            </button>
          </div>
        ) : (
          <>
            <div className="flex border-b border-slate-100">
              <button
                onClick={() => { setMode('login'); reset(); }}
                className={`flex-1 py-3 text-sm font-medium ${mode === 'login' ? 'text-[#0B3D91] border-b-2 border-[#0B3D91]' : 'text-slate-500'}`}
              >
                Sign In
              </button>
              <button
                onClick={() => { setMode('signup'); reset(); }}
                className={`flex-1 py-3 text-sm font-medium ${mode === 'signup' ? 'text-[#0B3D91] border-b-2 border-[#0B3D91]' : 'text-slate-500'}`}
              >
                Sign Up
              </button>
            </div>

            <form onSubmit={submit} className="p-6 space-y-4">
              {mode === 'signup' && (
                <div>
                  <label className="text-xs font-medium text-slate-600">Full Name</label>
                  <input
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]"
                  />
                </div>
              )}
              <div>
                <label className="text-xs font-medium text-slate-600">Email</label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]"
                />
              </div>
              <div>
                <label className="text-xs font-medium text-slate-600">Password</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]"
                />
              </div>
              {mode === 'signup' && (
                <div>
                  <label className="text-xs font-medium text-slate-600">Role</label>
                  <select
                    value={role}
                    onChange={(e) => setRole(e.target.value as Role)}
                    className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]"
                  >
                    {ROLES.map((r) => (
                      <option key={r} value={r}>{r}</option>
                    ))}
                  </select>
                  <p className="text-[11px] text-slate-400 mt-1">
                    Your role controls which dispatch tools you can access.
                  </p>
                </div>
              )}
              {error && <p className="text-xs text-[#D32F2F]">{error}</p>}
              <button
                type="submit"
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 py-2.5 rounded-lg bg-[#0B3D91] hover:bg-[#0a3580] disabled:opacity-60 text-white text-sm font-semibold"
              >
                {loading && <Loader2 className="w-4 h-4 animate-spin" />}
                {mode === 'login' ? 'Sign In' : 'Create Account'}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

export default AuthModal;
