'use client';

import { FormEvent, useState, useEffect } from 'react';
import api from '../../../lib/api-client';
import {
  AlertCircle,
  Eye,
  EyeOff,
  Fingerprint,
  LockKeyhole,
  LogIn,
  Mail,
  Loader2,
} from 'lucide-react';
import { useBiometrics } from '../../../hooks/use-biometrics';
import { useQuery } from '@tanstack/react-query';
import { MaintenanceScreen } from '../../../components/maintenance-screen';

export default function LoginPage() {
  const [email, setEmail] = useState('field@example.com');
  const [password, setPassword] = useState('password');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const { loginBiometric, loading: bioLoading, isSupported: bioSupported } = useBiometrics();
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsVisible(true);
    setIsClient(true);
  }, []);

  const { data: publicFlags } = useQuery({
    queryKey: ['public-flags'],
    queryFn: async () => {
      const response = await api.get('/app/public-flags');
      return response.data;
    },
    retry: false,
  });

  if (publicFlags?.maintenance_mode) {
    return (
      <div className="min-h-screen bg-slate-50 p-8">
        <MaintenanceScreen />
      </div>
    );
  }

  const handleBiometricLogin = async () => {
    if (!email) {
      setError('Please enter your email first to use biometric login');
      return;
    }
    
    // Suppress biometric errors for now if they fail
    try {
        const data = await loginBiometric(email);
        if (data && data.success) {
        // Save to localStorage
        localStorage.setItem('gcx_fshs_token', data.token);
        localStorage.setItem('gcx_fshs_user', JSON.stringify(data.user));
        
        // Use window.location for full page reload to ensure token is available
        if (data.user.role === 'SUPER_ADMIN') {
            window.location.href = '/super-admin';
        } else if (data.user.role === 'FIELD_STAFF') {
            window.location.href = '/field-staff/new-delivery';
        } else {
            window.location.href = '/field-staff';
        }
        }
    } catch (e) {
        console.error("Biometric login failed silently:", e);
    }
  };

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const { data } = await api.post(
        '/auth/login',
        { email, password },
        {
          timeout: 20_000,
          timeoutErrorMessage: 'Network is slow - still trying to log you in...',
        },
      );

      // Save to localStorage
      localStorage.setItem('gcx_fshs_token', data.token);
      localStorage.setItem('gcx_fshs_user', JSON.stringify(data.user));
      
      // Use window.location for full page reload to ensure token is available
      if (data.user.role === 'SUPER_ADMIN') {
        window.location.href = '/super-admin';
      } else if (data.user.role === 'FIELD_STAFF') {
        window.location.href = '/field-staff/new-delivery';
      } else {
        window.location.href = '/field-staff';
      }
    } catch (err: any) {
      console.error('Login error:', err);
      if (err.code === 'ECONNABORTED') {
        setError('The server took too long to respond. Please check your connection and try again.');
      } else {
        setError(err.response?.data?.error || 'Invalid credentials');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="min-h-[100svh] bg-[#edf2ef] text-slate-950 sm:p-6 dark:bg-slate-950">
      <div className="mx-auto grid min-h-[100svh] max-w-6xl overflow-hidden bg-white shadow-[0_24px_70px_rgba(15,23,42,0.14)] sm:min-h-[calc(100svh-3rem)] sm:rounded-2xl lg:grid-cols-[0.9fr_1.1fr] dark:bg-slate-900">
        <section
          className={`relative flex min-h-[200px] flex-col items-center justify-center overflow-hidden bg-[#075e4b] px-6 py-8 text-center text-white transition-all duration-700 motion-reduce:transform-none motion-reduce:transition-none sm:min-h-[240px] sm:px-8 lg:min-h-full lg:p-10 ${
            isVisible ? 'translate-y-0 opacity-100' : '-translate-y-3 opacity-0'
          }`}
          aria-label="GCX Free SHS field operations"
        >
          <div className="absolute inset-x-0 top-0 grid h-1 grid-cols-3" aria-hidden="true">
            <span className="bg-red-600" />
            <span className="bg-yellow-400" />
            <span className="bg-green-500" />
          </div>

          <div className="flex flex-col items-center">
            <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-white shadow-xl shadow-emerald-950/25 sm:h-24 sm:w-24">
              <img src="/icon-192.png" alt="GCX" className="h-16 w-16 object-contain sm:h-20 sm:w-20" />
            </div>
            <p className="mt-5 max-w-xs text-xs font-medium leading-5 text-emerald-100 sm:text-sm sm:leading-6">
              Connecting Markets, Connecting People, Creating Opportunities.
            </p>
          </div>
        </section>

        <section className="flex items-center justify-center px-5 py-7 sm:px-10 sm:py-10 lg:px-16">
          <div
            className={`w-full max-w-md transition-all delay-150 duration-700 motion-reduce:transform-none motion-reduce:transition-none ${
              isVisible ? 'translate-y-0 opacity-100' : 'translate-y-4 opacity-0'
            }`}
          >
            <div className="mb-7">
              <h1 className="text-3xl font-bold text-slate-950 dark:text-white">Welcome back</h1>
              <p className="mt-2 text-sm leading-6 text-slate-500 dark:text-slate-400">
                Sign in to continue to delivery operations.
              </p>
            </div>

            {error && (
              <div className="mb-5 flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 p-3.5 text-red-800" role="alert">
                <AlertCircle className="mt-0.5 h-5 w-5 shrink-0" />
                <p className="text-sm font-medium leading-5">{error}</p>
              </div>
            )}

            <form onSubmit={submit} className="space-y-5">
              <div>
                <label htmlFor="login-email" className="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">
                  Email address
                </label>
                <div className="relative">
                  <Mail className="pointer-events-none absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                  <input
                    id="login-email"
                    type="email"
                    autoComplete="email"
                    required
                    placeholder="name@example.com"
                    className="h-14 w-full rounded-xl border border-slate-200 bg-slate-50 pl-12 pr-4 text-base text-slate-950 outline-none transition placeholder:text-slate-400 focus:border-emerald-600 focus:bg-white focus:ring-4 focus:ring-emerald-600/10 dark:border-slate-700 dark:bg-slate-800 dark:text-white dark:focus:border-emerald-400 dark:focus:bg-slate-900"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="login-password" className="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">
                  Password
                </label>
                <div className="relative">
                  <LockKeyhole className="pointer-events-none absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                  <input
                    type={showPassword ? 'text' : 'password'}
                    id="login-password"
                    autoComplete="current-password"
                    required
                    placeholder="Enter your password"
                    className="h-14 w-full rounded-xl border border-slate-200 bg-slate-50 pl-12 pr-14 text-base text-slate-950 outline-none transition placeholder:text-slate-400 focus:border-emerald-600 focus:bg-white focus:ring-4 focus:ring-emerald-600/10 dark:border-slate-700 dark:bg-slate-800 dark:text-white dark:focus:border-emerald-400 dark:focus:bg-slate-900"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-1.5 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-lg text-slate-400 transition hover:bg-white hover:text-slate-700 active:scale-95 dark:hover:bg-slate-700 dark:hover:text-white"
                    aria-label={showPassword ? 'Hide password' : 'Show password'}
                    title={showPassword ? 'Hide password' : 'Show password'}
                  >
                    {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                aria-busy={loading}
                className="flex h-14 w-full items-center justify-center gap-2 rounded-xl bg-emerald-700 px-4 font-bold text-white shadow-[0_10px_24px_rgba(4,120,87,0.24)] transition hover:bg-emerald-800 hover:shadow-[0_12px_28px_rgba(4,120,87,0.3)] active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-60 disabled:shadow-none"
              >
                {loading ? (
                  <>
                    <Loader2 className="h-5 w-5 animate-spin" />
                    <span>Signing in...</span>
                  </>
                ) : (
                  <>
                    <LogIn className="h-5 w-5" />
                    <span>Sign in</span>
                  </>
                )}
              </button>

              {isClient && bioSupported && (
                <>
                  <div className="flex items-center gap-3" aria-hidden="true">
                    <span className="h-px flex-1 bg-slate-200 dark:bg-slate-700" />
                    <span className="text-xs font-medium text-slate-400">or</span>
                    <span className="h-px flex-1 bg-slate-200 dark:bg-slate-700" />
                  </div>
                  <button
                    type="button"
                    onClick={handleBiometricLogin}
                    disabled={bioLoading || loading}
                    className="flex h-14 w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-4 font-bold text-slate-700 transition hover:border-emerald-200 hover:bg-emerald-50 hover:text-emerald-800 active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"
                  >
                    {bioLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Fingerprint className="h-5 w-5" />}
                    <span>{bioLoading ? 'Verifying...' : 'Use biometrics'}</span>
                  </button>
                </>
              )}
            </form>

            {isClient && !bioSupported && (
              <div className="mt-5 flex items-center gap-2 text-xs text-slate-400">
                <Fingerprint className="h-4 w-4 shrink-0" />
                <span>Biometric sign-in is unavailable on this device.</span>
              </div>
            )}

            <div className="mt-7 border-t border-slate-100 pt-5 dark:border-slate-800">
              <p className="text-center text-xs font-medium text-slate-400">
                Government of Ghana | Free SHS Programme
              </p>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
