'use client';

import { useState, useEffect, ReactNode } from 'react';
import { motion } from 'framer-motion';
import { Lock, KeyRound, AlertTriangle } from 'lucide-react';

const GATE_COOKIE = 'gfs_internal_access';
const GATE_PASSWORD = 'majestic121947';
const COOKIE_MAX_AGE = 60 * 60 * 24 * 30; // 30 days

function getCookie(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : null;
}

function setCookie(name: string, value: string, maxAge: number) {
  document.cookie = `${name}=${encodeURIComponent(value)};path=/;max-age=${maxAge};SameSite=Lax`;
}

export function InternalGate({ children }: { children: ReactNode }) {
  const [authorized, setAuthorized] = useState(false);
  const [password, setPassword] = useState('');
  const [error, setError] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const token = getCookie(GATE_COOKIE);
    if (token === 'granted') {
      setAuthorized(true);
    }
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (password === GATE_PASSWORD) {
      setCookie(GATE_COOKIE, 'granted', COOKIE_MAX_AGE);
      setAuthorized(true);
      setError(false);
    } else {
      setError(true);
      setPassword('');
    }
  };

  if (!mounted) {
    return (
      <div className="min-h-screen bg-[#0C1222] flex items-center justify-center">
        <div className="w-6 h-6 border-2 border-brand border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (authorized) {
    return <>{children}</>;
  }

  return (
    <div className="min-h-screen bg-[#0C1222] flex items-center justify-center px-4">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="w-full max-w-md"
      >
        <div className="glass-card p-8 border border-brand-deep/30 text-center">
          <div className="w-16 h-16 mx-auto mb-6 rounded-full bg-brand-deep/20 flex items-center justify-center">
            <Lock className="w-8 h-8 text-brand" />
          </div>
          <h1 className="text-2xl font-bold text-white mb-2">Restricted Access</h1>
          <p className="text-gray-400 text-sm mb-6">
            This section is for internal use only. Enter the access code to continue.
          </p>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="relative">
              <KeyRound className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
              <input
                type="password"
                value={password}
                onChange={(e) => { setPassword(e.target.value); setError(false); }}
                placeholder="Access code"
                autoFocus
                className="w-full pl-10 pr-4 py-3 bg-slate-800/60 border border-slate-700/50 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50 focus:border-brand-deep/50"
              />
            </div>

            {error && (
              <motion.div
                initial={{ opacity: 0, y: -5 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 text-red-400 text-sm"
              >
                <AlertTriangle className="w-4 h-4" />
                <span>Invalid access code. Try again.</span>
              </motion.div>
            )}

            <button
              type="submit"
              className="w-full py-3 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white font-semibold rounded-lg hover:opacity-90 transition-opacity"
            >
              Enter
            </button>
          </form>

          <p className="text-gray-600 text-xs mt-6">
            If you believe you should have access, contact your administrator.
          </p>
        </div>
      </motion.div>
    </div>
  );
}
