'use client';

import { useState, Suspense } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { Ghost, Lock, Mail, AlertCircle, Eye, EyeOff, Loader2, FlaskConical } from 'lucide-react';
import Link from 'next/link';
import { BRAND, VOCAB } from '@/lib/white-label/constants';

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/ghost-control';
  const error = searchParams.get('error');

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isTestLoading, setIsTestLoading] = useState(false);
  const [loginError, setLoginError] = useState(error || '');

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

    try {
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
        callbackUrl,
      });

      if (result?.error) {
        setLoginError(result.error);
        setIsLoading(false);
      } else if (result?.ok) {
        router.push(callbackUrl);
        router.refresh();
      }
    } catch (err) {
      setLoginError('An unexpected error occurred');
      setIsLoading(false);
    }
  };

  const handleTestLogin = async () => {
    setIsTestLoading(true);
    setLoginError('');

    try {
      const result = await signIn('credentials', {
        email: 'admin@ghostfoundry.ai',
        password: 'Syndicate2026!',
        redirect: false,
        callbackUrl,
      });

      if (result?.error) {
        setLoginError(result.error);
        setIsTestLoading(false);
      } else if (result?.ok) {
        router.push(callbackUrl);
        router.refresh();
      }
    } catch (err) {
      setLoginError('Test login failed');
      setIsTestLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-brand-bg flex items-center justify-center p-4">
      {/* Background effects */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-brand-deep/10 rounded-full blur-3xl" />
        <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-brand-secondary/10 rounded-full blur-3xl" />
      </div>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative w-full max-w-md"
      >
        {/* Logo */}
        <div className="text-center mb-8">
          <Link href="/" className="inline-flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-brand-deep to-brand-secondary-deep flex items-center justify-center">
              <Ghost className="w-7 h-7 text-white" />
            </div>
            <div className="text-left">
              <span className="text-xl font-bold text-white">{BRAND.primaryName}</span>
              <span className="text-xl font-light text-brand">Familiars</span>
            </div>
          </Link>
          <p className="text-gray-400 mt-4">Sign in to access your dashboard</p>
        </div>

        {/* Login Card */}
        <div className="glass-card p-8 rounded-2xl border border-white/10">
          <h1 className="text-2xl font-bold text-white text-center mb-6">
            Welcome Back
          </h1>

          {loginError && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="mb-6 p-4 rounded-lg bg-red-500/10 border border-red-500/20 flex items-center gap-3"
            >
              <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
              <p className="text-red-400 text-sm">{loginError}</p>
            </motion.div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Email */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Email Address
              </label>
              <div className="relative">
                <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@company.com"
                  required
                  className="w-full pl-12 pr-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50 focus:border-brand-deep/50 transition-all"
                />
              </div>
            </div>

            {/* Password */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Password
              </label>
              <div className="relative">
                <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter your password"
                  required
                  className="w-full pl-12 pr-12 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50 focus:border-brand-deep/50 transition-all"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-300"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            {/* Submit */}
            <button
              type="submit"
              disabled={isLoading || isTestLoading}
              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 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Signing in...
                </>
              ) : (
                'Sign In'
              )}
            </button>
          </form>

          {/* Testing Login Button */}
          <div className="mt-4 pt-4 border-t border-white/10">
            <button
              type="button"
              onClick={handleTestLogin}
              disabled={isLoading || isTestLoading}
              className="w-full py-3 bg-amber-500/20 border border-amber-500/30 text-amber-400 font-medium rounded-lg hover:bg-amber-500/30 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
            >
              {isTestLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Testing...
                </>
              ) : (
                <>
                  <FlaskConical className="w-5 h-5" />
                  Testing Login (Demo Access)
                </>
              )}
            </button>
            <p className="text-center text-gray-500 text-xs mt-2">
              Auto-fills demo credentials
            </p>
          </div>

          {/* Help text */}
          <p className="text-center text-gray-500 text-sm mt-6">
            Need access?{' '}
            <Link href="/#design-partner" className="text-brand hover:text-brand-light">
              Contact your admin
            </Link>
          </p>
        </div>

        {/* Security badge */}
        <div className="text-center mt-6">
          <p className="text-gray-500 text-xs flex items-center justify-center gap-2">
            <Lock className="w-3 h-3" />
            Protected by {BRAND.companyName} Sentinel
          </p>
        </div>
      </motion.div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-brand-bg flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-brand-deep animate-spin" />
      </div>
    }>
      <LoginForm />
    </Suspense>
  );
}
