import React, { useState } from 'react';
import { Shield, Key, Eye, EyeOff, Loader2, ArrowRight, CheckCircle2 } from 'lucide-react';

interface LoginScreenProps {
  onLoginSuccess: (user: any) => void;
}

export default function LoginScreen({ onLoginSuccess }: LoginScreenProps) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  
  // Forgot Password state
  const [isForgotPassword, setIsForgotPassword] = useState(false);
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotSuccess, setForgotSuccess] = useState('');
  const [isForgotLoading, setIsForgotLoading] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
      });

      const data = await res.json();
      if (res.ok && data.success) {
        onLoginSuccess(data.user);
      } else {
        setError(data.message || 'Invalid username or password.');
      }
    } catch (err) {
      setError('Connection to Intranet Server failed. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setForgotSuccess('');
    setIsForgotLoading(true);

    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: forgotEmail })
      });

      const data = await res.json();
      if (res.ok && data.success) {
        setForgotSuccess(data.message);
        setForgotEmail('');
      } else {
        setError(data.message || 'Error processing password reset request.');
      }
    } catch (err) {
      setError('Connection failed. Please check server status.');
    } finally {
      setIsForgotLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col justify-between" id="login-container">
      {/* Top Header Accent */}
      <div className="bg-slate-900 text-white py-4 px-6 border-b border-slate-800 flex items-center justify-between shadow-sm">
        <div className="flex items-center gap-3">
          <div className="bg-amber-500 text-slate-950 p-2 rounded-lg font-bold text-xs tracking-wider">MYUSAKO</div>
          <div>
            <h1 className="font-sans font-semibold text-sm tracking-tight text-white leading-none">Intranet Portal</h1>
            <span className="font-mono text-[10px] text-slate-400">Secure Internal Gateway</span>
          </div>
        </div>
        <div className="flex items-center gap-2 text-xs text-slate-400 font-mono">
          <Shield className="w-3.5 h-3.5 text-amber-500" />
          <span>SSL ENCRYPTED</span>
        </div>
      </div>

      {/* Main Login Card */}
      <div className="flex-1 flex items-center justify-center p-6">
        <div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-xl overflow-hidden">
          <div className="bg-slate-900 p-6 text-white text-center border-b border-slate-800 relative">
            <div className="absolute top-3 left-3 bg-slate-800 text-slate-400 font-mono text-[9px] px-2 py-0.5 rounded border border-slate-700">
              IP: 136.0.111.105
            </div>
            <div className="w-12 h-12 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-center justify-center mx-auto mb-3">
              <Shield className="w-6 h-6 text-amber-500" />
            </div>
            <h2 className="font-sans text-xl font-bold tracking-tight">
              {isForgotPassword ? 'Reset Employee Password' : 'Employee Secure Login'}
            </h2>
            <p className="font-sans text-xs text-slate-400 mt-1">
              {isForgotPassword 
                ? 'Submit request to administrative helpdesk' 
                : 'Enter your myusako.org credentials to access tools'}
            </p>
          </div>

          <div className="p-6">
            {error && (
              <div className="bg-red-50 text-red-700 border border-red-200 p-3.5 rounded-xl text-xs mb-4 flex items-start gap-2">
                <div className="bg-red-100 p-1 rounded-md text-red-700 font-bold text-[10px]">ERR</div>
                <div className="flex-1 font-medium">{error}</div>
              </div>
            )}

            {forgotSuccess && (
              <div className="bg-emerald-50 text-emerald-800 border border-emerald-200 p-3.5 rounded-xl text-xs mb-4 flex items-start gap-2">
                <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0 mt-0.5" />
                <div className="flex-1 font-medium">{forgotSuccess}</div>
              </div>
            )}

            {!isForgotPassword ? (
              <form onSubmit={handleLogin} className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1.5">
                    Company Email Address
                  </label>
                  <div className="relative">
                    <input
                      type="email"
                      required
                      placeholder="Firstname.Lastname@myusako.org"
                      className="w-full bg-slate-50 border border-slate-200 focus:border-amber-500 focus:bg-white text-sm px-3.5 py-2.5 rounded-xl transition-all focus:outline-none placeholder-slate-400"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </div>
                </div>

                <div>
                  <div className="flex justify-between items-center mb-1.5">
                    <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider">
                      Security Password
                    </label>
                    <button
                      type="button"
                      onClick={() => setIsForgotPassword(true)}
                      className="text-xs text-slate-500 hover:text-amber-600 font-medium cursor-pointer"
                    >
                      Forgot Password?
                    </button>
                  </div>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      required
                      placeholder="••••••••••••"
                      className="w-full bg-slate-50 border border-slate-200 focus:border-amber-500 focus:bg-white text-sm px-3.5 py-2.5 rounded-xl pr-10 transition-all focus:outline-none placeholder-slate-400"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3.5 top-3 text-slate-400 hover:text-slate-600"
                    >
                      {showPassword ? <EyeOff className="w-4.5 h-4.5" /> : <Eye className="w-4.5 h-4.5" />}
                    </button>
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={isLoading}
                  className="w-full bg-slate-900 hover:bg-slate-800 text-white font-medium text-sm py-3 rounded-xl flex items-center justify-center gap-2 cursor-pointer transition-all disabled:opacity-50 mt-2 hover:shadow-lg shadow-slate-900/10"
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="w-4.5 h-4.5 animate-spin" />
                      <span>Authenticating Credentials...</span>
                    </>
                  ) : (
                    <>
                      <span>Sign in to Intranet Dashboard</span>
                      <ArrowRight className="w-4.5 h-4.5" />
                    </>
                  )}
                </button>
              </form>
            ) : (
              <form onSubmit={handleForgotPassword} className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1.5">
                    Your Registered Email Address
                  </label>
                  <input
                    type="email"
                    required
                    placeholder="Firstname.Lastname@myusako.org"
                    className="w-full bg-slate-50 border border-slate-200 focus:border-amber-500 focus:bg-white text-sm px-3.5 py-2.5 rounded-xl transition-all focus:outline-none placeholder-slate-400"
                    value={forgotEmail}
                    onChange={(e) => setForgotEmail(e.target.value)}
                  />
                  <p className="text-[11px] text-slate-400 mt-2 leading-normal">
                    This will send a priority reset alert to the System Administrator. Once approved, your password will be reset to match your default username (email).
                  </p>
                </div>

                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => {
                      setIsForgotPassword(false);
                      setError('');
                      setForgotSuccess('');
                    }}
                    className="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium text-xs py-2.5 rounded-xl cursor-pointer text-center transition-all"
                  >
                    Back to Login
                  </button>
                  <button
                    type="submit"
                    disabled={isForgotLoading}
                    className="flex-1 bg-slate-900 hover:bg-slate-800 text-white font-medium text-xs py-2.5 rounded-xl flex items-center justify-center gap-1.5 cursor-pointer transition-all disabled:opacity-50"
                  >
                    {isForgotLoading ? (
                      <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    ) : (
                      <span>Request Reset</span>
                    )}
                  </button>
                </div>
              </form>
            )}

            {/* Quick Helper Credentials Panel */}
            <div className="mt-6 pt-5 border-t border-slate-100">
              <div className="bg-amber-50/70 border border-amber-200/50 p-4 rounded-xl">
                <h4 className="text-[11px] font-bold text-amber-800 uppercase tracking-wider flex items-center gap-1.5 mb-1.5">
                  <Key className="w-3.5 h-3.5" />
                  System Test Credentials
                </h4>
                <div className="space-y-1.5 font-mono text-[10px] text-slate-600">
                  <div className="flex justify-between border-b border-amber-100/30 pb-1">
                    <span className="text-slate-500">Admin Email:</span>
                    <span className="font-semibold text-slate-800">admin@myusako.org</span>
                  </div>
                  <div className="flex justify-between border-b border-amber-100/30 pb-1">
                    <span className="text-slate-500">Admin Pass:</span>
                    <span className="font-semibold text-slate-800">Dave&Doc2315</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">Staff Email:</span>
                    <span className="font-semibold text-slate-800">John.Doe@myusako.org</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">Staff Pass:</span>
                    <span className="font-semibold text-slate-800">John.Doe@myusako.org</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="bg-slate-900 text-slate-400 py-4 px-6 border-t border-slate-800 text-center text-xs font-mono">
        <div>Domain: <span className="text-white">myusako.org</span> | IP Address: <span className="text-white">136.0.111.105</span></div>
        <div className="text-[10px] text-slate-500 mt-1">© 2026 MyUsako. All security and administrative actions are logged.</div>
      </div>
    </div>
  );
}
