import React, { useState } from 'react';
import { useNavigate, NavLink } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShieldCheck,
  Lock,
  User,
  ArrowRight,
  Cpu,
  Activity,
  KeyRound,
  ShieldAlert,
  Eye,
  EyeOff,
  Building,
  HeartPulse,
  Stethoscope,
  Monitor,
  Wifi,
  CheckCircle2,
  AlertCircle
} from 'lucide-react';
import { hospitalApi } from '../api/hospital';
import './HospitalLogin.css';

export const HospitalLogin: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [mfaCode, setMfaCode] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showError, setShowError] = useState('');
  const [mfaSessionToken, setMfaSessionToken] = useState('');
  const [tempUser, setTempUser] = useState<any>(null);
  const [loginStep, setLoginStep] = useState<'login' | 'mfa'>('login');
  const [showPassword, setShowPassword] = useState(false);
  const [loginSuccess, setLoginSuccess] = useState(false);

  const navigate = useNavigate();

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

    try {
      const response = await hospitalApi.login(username, password);

      if (response.status === 201 || response.status === 200) {
        if (response.data?.mfa_required) {
          setMfaSessionToken(response.data.mfa_session_token || '');
          setTempUser(response.data.user || null);
          setLoginStep('mfa');
        } else {
          // Verify hospital role
          const user = response.data?.user;
          const roles = Array.isArray(user?.roles)
            ? user.roles.map((r: string) => r.toUpperCase())
            : [];

          const hasHospitalAccess = roles.some((r: string) =>
            ['HOSPITAL_ADMIN', 'HOSPITAL ADMIN', 'ED_DOCTOR', 'COORDINATOR', 'EMT', 'CURESELECT_ADMIN', 'ADMIN'].includes(r)
          );

          if (!hasHospitalAccess) {
            setShowError('This account does not have hospital access privileges');
            setIsLoading(false);
            return;
          }

          // Success animation then redirect
          setLoginSuccess(true);
          localStorage.setItem('teleems_auth', 'true');
          localStorage.setItem('teleems_token', response.data.access_token || '');
          localStorage.setItem('teleems_user', JSON.stringify(user || {}));

          setTimeout(() => navigate('/'), 800);
        }
      } else {
        let apiError = 'Invalid credentials. Please try again.';
        const resAny = response as any;
        if (resAny.error && typeof resAny.error === 'object') {
          if (Array.isArray(resAny.error.details) && resAny.error.details.length > 0) {
            apiError = resAny.error.details.join('; ');
          } else {
            apiError = resAny.error.message || apiError;
          }
        } else if (typeof resAny.error === 'string') {
          apiError = resAny.error;
        } else if (resAny.message) {
          apiError = resAny.message;
        } else if (resAny.detail) {
          apiError = resAny.detail;
        } else if (resAny.data) {
          apiError = resAny.data.message || resAny.data.detail || resAny.data.error || apiError;
        }
        setShowError(apiError);
      }
    } catch (err) {
      setShowError('Unable to reach hospital authentication server');
    } finally {
      if (!loginSuccess) setIsLoading(false);
    }
  };

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

    try {
      const response = await hospitalApi.verifyMfa(mfaSessionToken, mfaCode);

      if (response.status === 201 || response.status === 200) {
        const userToStore = response.data?.user || tempUser || {};
        userToStore.mfa_enabled = true;

        setLoginSuccess(true);
        localStorage.setItem('teleems_auth', 'true');
        localStorage.setItem('teleems_token', response.data.access_token || '');
        localStorage.setItem('teleems_user', JSON.stringify(userToStore));

        setTimeout(() => navigate('/'), 800);
      } else {
        let apiError = 'Invalid verification code';
        const resAny = response as any;
        if (resAny.error && typeof resAny.error === 'object') {
          if (Array.isArray(resAny.error.details) && resAny.error.details.length > 0) {
            apiError = resAny.error.details.join('; ');
          } else {
            apiError = resAny.error.message || apiError;
          }
        } else if (typeof resAny.error === 'string') {
          apiError = resAny.error;
        } else if (resAny.message) {
          apiError = resAny.message;
        } else if (resAny.detail) {
          apiError = resAny.detail;
        } else if (resAny.data) {
          apiError = resAny.data.message || resAny.data.detail || resAny.data.error || apiError;
        }
        setShowError(apiError);
      }
    } catch (err) {
      setShowError('MFA verification failed. Please try again.');
    } finally {
      if (!loginSuccess) setIsLoading(false);
    }
  };

  return (
    <div className="hosp-login-page">
      {/* Background effects */}
      <div className="hosp-bg-grid" />
      <div className="hosp-bg-orb orb-1" />
      <div className="hosp-bg-orb orb-2" />
      <div className="hosp-bg-orb orb-3" />
      <div className="hosp-scan-line" />

      {/* Floating medical icons */}
      <div className="hosp-floating-icons">
        <motion.div
          className="float-icon fi-1"
          animate={{ y: [-10, 10, -10], rotate: [0, 5, -5, 0] }}
          transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut' }}
        >
          <HeartPulse size={20} />
        </motion.div>
        <motion.div
          className="float-icon fi-2"
          animate={{ y: [10, -10, 10], rotate: [0, -5, 5, 0] }}
          transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
        >
          <Stethoscope size={18} />
        </motion.div>
        <motion.div
          className="float-icon fi-3"
          animate={{ y: [-8, 12, -8] }}
          transition={{ duration: 7, repeat: Infinity, ease: 'easeInOut' }}
        >
          <Activity size={16} />
        </motion.div>
      </div>

      {/* Login card */}
      <AnimatePresence mode="wait">
        <motion.div
          key={loginStep + (loginSuccess ? '-success' : '')}
          initial={{ opacity: 0, y: 30, scale: 0.96 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: -20, scale: 0.96 }}
          transition={{ duration: 0.5, ease: [0.16, 1, 0.3, 1] }}
          className={`hosp-login-card ${loginSuccess ? 'success-glow' : ''}`}
        >
          {/* Card top accent */}
          <div className="hosp-card-accent" />

          {/* Header */}
          <div className="hosp-login-header">
            <motion.div
              className="hosp-logo-container"
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ delay: 0.2, duration: 0.6, type: 'spring', stiffness: 200 }}
            >
              <div className="hosp-logo-ring" />
              <div className="hosp-logo-inner">
                <Building size={26} strokeWidth={2} />
              </div>
              <div className="hosp-logo-pulse" />
            </motion.div>

            <motion.h1
              className="hosp-title"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              {loginStep === 'login' ? 'Hospital Console' : 'Verify Identity'}
            </motion.h1>
            <motion.p
              className="hosp-subtitle"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
            >
              {loginStep === 'login'
                ? 'Secure Clinical Operations Portal'
                : 'Enter your authenticator code'}
            </motion.p>
          </div>

          {/* Login form */}
          {loginStep === 'login' ? (
            <form onSubmit={handleLogin} className="hosp-form">
              <motion.div
                className="hosp-input-group"
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.35 }}
              >
                <label className="hosp-label">Hospital ID</label>
                <div className="hosp-input-wrap">
                  <User className="hosp-input-icon" size={18} />
                  <input
                    id="hospital-username"
                    type="text"
                    className="hosp-input"
                    placeholder="Enter username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    required
                    autoComplete="username"
                  />
                  <div className="hosp-input-focus-line" />
                </div>
              </motion.div>

              <motion.div
                className="hosp-input-group"
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.45 }}
              >
                <label className="hosp-label">Access Key</label>
                <div className="hosp-input-wrap">
                  <Lock className="hosp-input-icon" size={18} />
                  <input
                    id="hospital-password"
                    type={showPassword ? 'text' : 'password'}
                    className="hosp-input"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    className="hosp-eye-btn"
                    onClick={() => setShowPassword(!showPassword)}
                    aria-label={showPassword ? 'Hide password' : 'Show password'}
                  >
                    {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                  </button>
                  <div className="hosp-input-focus-line" />
                </div>
              </motion.div>

              <motion.div
                className="hosp-extras"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.5 }}
              >
                <label className="hosp-remember">
                  <input type="checkbox" />
                  <span className="hosp-check-mark" />
                  Keep session active
                </label>
                <a href="#" className="hosp-forgot">Reset credentials?</a>
              </motion.div>

              <motion.button
                type="submit"
                className="hosp-submit-btn"
                disabled={isLoading || loginSuccess}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.55 }}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                {loginSuccess ? (
                  <motion.div
                    className="hosp-success-check"
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    transition={{ type: 'spring', stiffness: 300 }}
                  >
                    <CheckCircle2 size={22} />
                    <span>ACCESS GRANTED</span>
                  </motion.div>
                ) : isLoading ? (
                  <div className="hosp-loader">
                    <motion.div
                      animate={{ rotate: 360 }}
                      transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
                    >
                      <Cpu size={20} />
                    </motion.div>
                    <span>AUTHENTICATING...</span>
                  </div>
                ) : (
                  <>
                    <span>SECURE LOGIN</span>
                    <ArrowRight size={18} />
                  </>
                )}
              </motion.button>
            </form>
          ) : (
            /* MFA Form */
            <form onSubmit={handleMfaVerify} className="hosp-form">
              <motion.div
                className="hosp-input-group"
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.2 }}
              >
                <label className="hosp-label">TOTP Security Code</label>
                <div className="hosp-input-wrap">
                  <KeyRound className="hosp-input-icon" size={18} />
                  <input
                    id="hospital-mfa-code"
                    type="text"
                    className="hosp-input mono"
                    placeholder="000 000"
                    maxLength={6}
                    value={mfaCode}
                    onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ''))}
                    required
                    autoFocus
                  />
                  <div className="hosp-input-focus-line" />
                </div>
              </motion.div>

              <p className="hosp-mfa-hint">
                <AlertCircle size={14} />
                Enter the 6-digit code from your authenticator app
              </p>

              <motion.button
                type="submit"
                className="hosp-submit-btn"
                disabled={isLoading || loginSuccess}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                {loginSuccess ? (
                  <motion.div
                    className="hosp-success-check"
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                  >
                    <CheckCircle2 size={22} />
                    <span>VERIFIED</span>
                  </motion.div>
                ) : isLoading ? (
                  <div className="hosp-loader">
                    <motion.div
                      animate={{ rotate: 360 }}
                      transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
                    >
                      <Cpu size={20} />
                    </motion.div>
                    <span>VERIFYING...</span>
                  </div>
                ) : (
                  <>
                    <ShieldCheck size={18} />
                    <span>VERIFY IDENTITY</span>
                  </>
                )}
              </motion.button>

              <button
                type="button"
                className="hosp-back-btn"
                onClick={() => { setLoginStep('login'); setShowError(''); setMfaCode(''); }}
              >
                ← Back to Login
              </button>
            </form>
          )}

          {/* Error display */}
          <AnimatePresence>
            {showError && (
              <motion.div
                className="hosp-error-badge"
                initial={{ opacity: 0, height: 0, marginTop: 0 }}
                animate={{ opacity: 1, height: 'auto', marginTop: 16 }}
                exit={{ opacity: 0, height: 0, marginTop: 0 }}
              >
                <ShieldAlert size={14} />
                <span>{showError}</span>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Security badge */}
          {!showError && (
            <motion.div
              className="hosp-security-badge"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.6 }}
            >
              <ShieldCheck size={14} />
              <span>HIPAA-COMPLIANT SECURE CONNECTION</span>
            </motion.div>
          )}

          {/* Footer */}
          <div className="hosp-footer">
            <NavLink to="/launcher" className="hosp-portal-link">
              <Monitor size={14} />
              VIEW ALL PORTALS
            </NavLink>
          </div>
        </motion.div>
      </AnimatePresence>

      {/* Status indicators */}
      <div className="hosp-status-bar">
        <div className="hosp-status-item">
          <Wifi size={12} />
          <span>UPLINK ACTIVE</span>
        </div>
        <div className="hosp-status-dot" />
        <div className="hosp-status-item">
          <Activity size={12} />
          <span>NODE ONLINE</span>
        </div>
      </div>
    </div>
  );
};

export default HospitalLogin;
