import React, { useEffect, useState } from 'react';
import GuestLayout from '../../Layouts/GuestLayout';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { Alert, Button, Card, Col, Container, Form, Row, InputGroup } from 'react-bootstrap';
import logoLight from '../../../images/logo-light.png';
import { Eye, EyeOff, Check, X } from 'lucide-react';
import Swal from 'sweetalert2';

export default function ResetPassword({ token, email }: any) {
    const { appName } = usePage<any>().props;
    const { data, setData, post, processing, errors, reset } = useForm({
        token: token,
        email: email,
        password: '',
        password_confirmation: '',
    });

    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);

    useEffect(() => {
        return () => {
            reset('password', 'password_confirmation');
        };
    }, []);

    // Función para validar fuerza de contraseña
    const checkStrength = (pass: string) => {
        return {
            length: pass.length >= 8,
            uppercase: /[A-Z]/.test(pass),
            number: /[0-9]/.test(pass),
            special: /[!@#$%^&*(),.?":{}|<>]/.test(pass),
        };
    };

    const strength = checkStrength(data.password);
    const isStrengthValid = Object.values(strength).every(Boolean);

    const submit = (e: any) => {
        e.preventDefault();

        if (data.password !== data.password_confirmation) {
            Swal.fire({
                title: 'Error',
                text: 'Las contraseñas no coinciden.',
                icon: 'error'
            });
            return;
        }

        if (!isStrengthValid) {
            Swal.fire({
                title: 'Contraseña Débil',
                text: 'La contraseña debe cumplir con todos los requisitos de seguridad.',
                icon: 'warning'
            });
            return;
        }

        post(route('password.store'));
    };

    return (
        <React.Fragment>
            <GuestLayout>
                <Head title={`Restablecer Contraseña | ${appName}`} />
                <div className="auth-page-content mt-lg-5">
                    <Container>
                        <Row>
                            <Col lg={12}>
                                <div className="text-center mt-sm-5 mb-4 text-white-50">
                                    <div>
                                        <Link href="/#" className="d-inline-block auth-logo">
                                            <img src={logoLight} alt="" height="20" />
                                        </Link>
                                    </div>
                                    <p className="mt-3 fs-15 fw-semibold">Sistema de Gestión {appName}</p>
                                </div>
                            </Col>
                        </Row>

                        <Row className="justify-content-center">
                            <Col md={8} lg={6} xl={5}>
                                <Card className="mt-4 card-bg-fill">
                                    <Card.Body className="p-4">
                                        <div className="text-center mt-2">
                                            <h5 className="text-primary">Crear Nueva Contraseña</h5>
                                            <p className="text-muted">Tu nueva contraseña debe ser diferente a la anterior.</p>
                                        </div>

                                        <div className="p-2">
                                            <form onSubmit={submit}>
                                                <div className="mb-3">
                                                    <Form.Label htmlFor="email" className="form-label">Correo Electrónico</Form.Label>
                                                    <Form.Control
                                                        id="email"
                                                        type="email"
                                                        name="email"
                                                        value={data.email}
                                                        className={"form-control" + (errors.email ? ' is-invalid' : '')}
                                                        onChange={(e: any) => setData('email', e.target.value)}
                                                        readOnly
                                                    />
                                                    <Form.Control.Feedback type="invalid" className='d-block'>{errors.email}</Form.Control.Feedback>
                                                </div>

                                                <div className="mb-3">
                                                    <Form.Label htmlFor="password" className="form-label">Nueva Contraseña</Form.Label>
                                                    <InputGroup>
                                                        <Form.Control
                                                            id="password"
                                                            type={showPassword ? "text" : "password"}
                                                            name="password"
                                                            placeholder="Ingresa tu nueva contraseña"
                                                            value={data.password}
                                                            className={"form-control" + (errors.password ? ' is-invalid' : '')}
                                                            autoComplete="new-password"
                                                            onChange={(e: any) => setData('password', e.target.value)}
                                                            required
                                                        />
                                                        <Button
                                                            variant="outline-secondary"
                                                            onClick={() => setShowPassword(!showPassword)}
                                                            type="button"
                                                        >
                                                            {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                                        </Button>
                                                    </InputGroup>

                                                    <Form.Control.Feedback type="invalid" className='d-block'>{errors.password}</Form.Control.Feedback>

                                                    {/* Medidor de Fuerza de Contraseña */}
                                                    {data.password && (
                                                        <div className="mt-2 p-2 bg-light rounded border">
                                                            <small className="d-block fw-bold mb-1">Requisitos de seguridad:</small>
                                                            <ul className="list-unstyled mb-0" style={{ fontSize: '0.85rem' }}>
                                                                <li className={strength.length ? "text-success" : "text-danger"}>
                                                                    {strength.length ? <Check size={14} className="me-1" /> : <X size={14} className="me-1" />}
                                                                    Mínimo 8 caracteres
                                                                </li>
                                                                <li className={strength.uppercase ? "text-success" : "text-danger"}>
                                                                    {strength.uppercase ? <Check size={14} className="me-1" /> : <X size={14} className="me-1" />}
                                                                    Al menos 1 mayúscula
                                                                </li>
                                                                <li className={strength.number ? "text-success" : "text-danger"}>
                                                                    {strength.number ? <Check size={14} className="me-1" /> : <X size={14} className="me-1" />}
                                                                    Al menos 1 número
                                                                </li>
                                                                <li className={strength.special ? "text-success" : "text-danger"}>
                                                                    {strength.special ? <Check size={14} className="me-1" /> : <X size={14} className="me-1" />}
                                                                    Al menos 1 carácter especial
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    )}
                                                </div>

                                                <div className="mb-3">
                                                    <Form.Label htmlFor="password_confirmation" className="form-label">Confirmar Contraseña</Form.Label>
                                                    <InputGroup>
                                                        <Form.Control
                                                            id="password_confirmation"
                                                            type={showConfirmPassword ? "text" : "password"}
                                                            name="password_confirmation"
                                                            placeholder="Confirma tu nueva contraseña"
                                                            value={data.password_confirmation}
                                                            className={"form-control" + (errors.password_confirmation ? ' is-invalid' : '')}
                                                            autoComplete="new-password"
                                                            onChange={(e: any) => setData('password_confirmation', e.target.value)}
                                                            required
                                                        />
                                                        <Button
                                                            variant="outline-secondary"
                                                            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                                            type="button"
                                                        >
                                                            {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                                        </Button>
                                                    </InputGroup>
                                                    <Form.Control.Feedback type="invalid" className='d-block'>{errors.password_confirmation}</Form.Control.Feedback>
                                                </div>

                                                <div className="mt-4">
                                                    <Button variant="success" className="w-100" type="submit" disabled={processing}>
                                                        Restablecer Contraseña
                                                    </Button>
                                                </div>
                                            </form>
                                        </div>
                                    </Card.Body>
                                </Card>
                                <div className="mt-4 text-center">
                                    <p className="mb-0">Espera, recuerdo mi contraseña... <Link href={route('login')} className="fw-semibold text-primary text-decoration-underline"> Click aquí </Link> </p>
                                </div>
                            </Col>
                        </Row>
                    </Container>
                </div>

            </GuestLayout>
        </React.Fragment>
    );
}
