import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import Container from '@/components/Layout/Container';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { KeyRound, ArrowLeft, Mail, CheckCircle } from 'lucide-react';

export default function ForgotPassword() {
    const [email, setEmail] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [isSuccess, setIsSuccess] = useState(false);
    const [error, setError] = useState('');

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

        try {
            const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
            const nonce = (window as any).woonoowCustomer?.nonce || '';

            const response = await fetch(`${apiRoot}/auth/forgot-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce,
                },
                credentials: 'include',
                body: JSON.stringify({ email }),
            });

            const data = await response.json();

            if (data.success) {
                setIsSuccess(true);
                toast.success('Password reset email sent!');
            } else {
                setError(data.message || 'Failed to send reset email');
            }
        } catch (err: any) {
            setError(err.message || 'An error occurred. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    // Success state
    if (isSuccess) {
        return (
            <Container>
                <div className="min-h-[60vh] flex items-center justify-center py-12">
                    <div className="w-full max-w-md">
                        <div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
                            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <CheckCircle className="w-8 h-8 text-green-600" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900 mb-2">Check Your Email</h1>
                            <p className="text-gray-600 mb-6">
                                We've sent a password reset link to <strong>{email}</strong>.
                                Please check your inbox and click the link to reset your password.
                            </p>
                            <div className="space-y-3">
                                <Link to="/login">
                                    <Button className="w-full">
                                        Return to Login
                                    </Button>
                                </Link>
                                <button
                                    onClick={() => {
                                        setIsSuccess(false);
                                        setEmail('');
                                    }}
                                    className="text-sm text-gray-600 hover:text-primary"
                                >
                                    Try a different email
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </Container>
        );
    }

    return (
        <Container>
            <div className="min-h-[60vh] flex items-center justify-center py-12">
                <div className="w-full max-w-md">
                    {/* Back link */}
                    <Link
                        to="/login"
                        className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-6 no-underline"
                    >
                        <ArrowLeft className="w-4 h-4" />
                        Back to login
                    </Link>

                    <div className="bg-white rounded-2xl shadow-xl p-8 border">
                        {/* Header */}
                        <div className="text-center mb-8">
                            <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                                <KeyRound className="w-8 h-8 text-primary" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900">Forgot Password?</h1>
                            <p className="text-gray-600 mt-2">
                                Enter your email and we'll send you a link to reset your password.
                            </p>
                        </div>

                        {/* Error message */}
                        {error && (
                            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                                {error}
                            </div>
                        )}

                        {/* Form */}
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="space-y-2">
                                <Label htmlFor="email">Email Address</Label>
                                <div className="relative">
                                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                                    <Input
                                        id="email"
                                        type="email"
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                        placeholder="Enter your email"
                                        required
                                        autoComplete="email"
                                        disabled={isLoading}
                                        className="pl-10"
                                    />
                                </div>
                            </div>

                            <Button
                                type="submit"
                                className="w-full"
                                disabled={isLoading}
                            >
                                {isLoading ? 'Sending...' : 'Send Reset Link'}
                            </Button>
                        </form>

                        {/* Footer */}
                        <div className="mt-6 text-center text-sm text-gray-600">
                            Remember your password?{' '}
                            <Link to="/login" className="text-primary hover:underline">
                                Sign in
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </Container>
    );
}
