'use client';

import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth/AuthContext';
import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  Mail,
  ArrowLeft,
  AlertCircle,
  Flag,
  Shield,
  CheckCircle2,
} from 'lucide-react';

import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';

interface FormErrors {
  email?: string;
  submit?: string;
}

interface SuccessState {
  message: string;
  magicLink?: string;
}

export default function ForgotPasswordPage() {
  const router = useRouter();
  const { session } = useAuth();
  
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});
  const [success, setSuccess] = useState<SuccessState | null>(null);
  const [formData, setFormData] = useState({
    email: '',
  });

  // Check if user is already authenticated
  useEffect(() => {
    if (session) {
      router.replace('/dashboard');
    }
  }, [session, router]);

  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Invalid email format';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (loading) return;

    if (!validateForm()) return;

    setLoading(true);
    setErrors({});
    setSuccess(null);

    try {
      const { ServiceFactory } = await import('@/lib/services/ServiceFactory');
      const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001');
      const authService = serviceFactory.createAuthService();
      const result = await authService.forgotPassword({ email: formData.email });

      setSuccess({
        message: result.message,
        magicLink: result.magicLink,
      });
    } catch (error) {
      setErrors({
        submit: error instanceof Error ? error.message : 'Failed to send reset link. Please try again.',
      });
      setLoading(false);
    }
  };

  return (
    <main className="min-h-screen bg-deep-graphite flex items-center justify-center px-4 py-12">
      {/* Background Pattern */}
      <div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
      <div className="absolute inset-0 opacity-5">
        <div className="absolute inset-0" style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        }} />
      </div>

      <div className="relative w-full max-w-md">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
            <Flag className="w-8 h-8 text-primary-blue" />
          </div>
          <Heading level={1} className="mb-2">Reset Password</Heading>
          <p className="text-gray-400">
            Enter your email and we'll send you a reset link
          </p>
        </div>

        <Card className="relative overflow-hidden">
          {/* Background accent */}
          <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />

          {!success ? (
            <form onSubmit={handleSubmit} className="relative space-y-5">
              {/* Email */}
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
                  Email Address
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, email: e.target.value })}
                    error={!!errors.email}
                    errorMessage={errors.email}
                    placeholder="you@example.com"
                    disabled={loading}
                    className="pl-10"
                    autoComplete="email"
                  />
                </div>
              </div>

              {/* Error Message */}
              {errors.submit && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30"
                >
                  <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
                  <p className="text-sm text-red-400">{errors.submit}</p>
                </motion.div>
              )}

              {/* Submit Button */}
              <Button
                type="submit"
                variant="primary"
                disabled={loading}
                className="w-full flex items-center justify-center gap-2"
              >
                {loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Shield className="w-4 h-4" />
                    Send Reset Link
                  </>
                )}
              </Button>

              {/* Back to Login */}
              <div className="text-center">
                <Link
                  href="/auth/login"
                  className="text-sm text-primary-blue hover:underline flex items-center justify-center gap-1"
                >
                  <ArrowLeft className="w-4 h-4" />
                  Back to Login
                </Link>
              </div>
            </form>
          ) : (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className="relative space-y-4"
            >
              <div className="flex items-start gap-3 p-4 rounded-lg bg-performance-green/10 border border-performance-green/30">
                <CheckCircle2 className="w-6 h-6 text-performance-green flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm text-performance-green font-medium">{success.message}</p>
                  {success.magicLink && (
                    <div className="mt-2">
                      <p className="text-xs text-gray-400 mb-1">Development Mode - Magic Link:</p>
                      <div className="bg-iron-gray p-2 rounded border border-charcoal-outline">
                        <code className="text-xs text-primary-blue break-all">
                          {success.magicLink}
                        </code>
                      </div>
                      <p className="text-[10px] text-gray-500 mt-1">
                        In production, this would be sent via email
                      </p>
                    </div>
                  )}
                </div>
              </div>

              <Button
                type="button"
                variant="secondary"
                onClick={() => router.push('/auth/login')}
                className="w-full"
              >
                Return to Login
              </Button>
            </motion.div>
          )}
        </Card>

        {/* Trust Indicators */}
        <div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500">
          <div className="flex items-center gap-2">
            <Shield className="w-4 h-4" />
            <span>Secure reset process</span>
          </div>
          <div className="flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4" />
            <span>15 minute expiration</span>
          </div>
        </div>

        {/* Footer */}
        <p className="mt-6 text-center text-xs text-gray-500">
          Need help?{' '}
          <Link href="/support" className="text-gray-400 hover:underline">
            Contact support
          </Link>
        </p>
      </div>
    </main>
  );
}