import { useState } from 'react';
import { motion } from 'framer-motion';
import { useLanguage } from '../../contexts/LanguageContext';
import { ArrowLeft, Send, CheckCircle, AlertCircle } from 'lucide-react';
import { Link } from 'react-router-dom';
import axios from 'axios';

const Support = () => {
    const { t, language } = useLanguage();
    const [formData, setFormData] = useState({
        nom: '',
        prenom: '',
        account_email: '',
        contact_email: '',
        useSameEmail: false,
        message: ''
    });
    const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle');
    const [errorMessage, setErrorMessage] = useState('');

    const handleSameEmailChange = (checked: boolean) => {
        setFormData(prev => ({
            ...prev,
            useSameEmail: checked,
            contact_email: checked ? prev.account_email : prev.contact_email
        }));
    };

    const handleAccountEmailChange = (value: string) => {
        setFormData(prev => ({
            ...prev,
            account_email: value,
            contact_email: prev.useSameEmail ? value : prev.contact_email
        }));
    };

    const [showConfirmModal, setShowConfirmModal] = useState(false);

    const handleInitialSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setShowConfirmModal(true);
    };

    const handleFinalSubmit = async () => {
        setShowConfirmModal(false);
        setStatus('submitting');
        setErrorMessage('');

        try {
            await axios.post('/api/support', {
                nom: formData.nom,
                prenom: formData.prenom,
                account_email: formData.account_email,
                contact_email: formData.contact_email,
                message: formData.message
            });
            setStatus('success');
            setFormData({
                nom: '',
                prenom: '',
                account_email: '',
                contact_email: '',
                useSameEmail: false,
                message: ''
            });
        } catch (error: any) {
            console.error('Submission error', error);
            setStatus('error');
            setErrorMessage(error.response?.data?.message || t('support.error.generic'));
        }
    };

    const containerVariants = {
        hidden: { opacity: 0, y: 20 },
        visible: { opacity: 1, y: 0 }
    };

    return (
        <div className="support-page" style={{ paddingTop: '100px', minHeight: '100vh', paddingBottom: '50px', position: 'relative' }}>
            <div className="container" style={{ maxWidth: '800px', margin: '0 auto', padding: '0 20px' }}>
                <Link
                    to={`/${language}/travelmate`}
                    style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '8px',
                        marginBottom: '2rem',
                        textDecoration: 'none',
                        color: 'var(--text-color)',
                        opacity: 0.8
                    }}
                >
                    <ArrowLeft size={18} />
                    {t('policies.back')}
                </Link>

                <motion.div
                    initial="hidden"
                    animate="visible"
                    variants={containerVariants}
                    style={{
                        background: 'var(--card-bg, rgba(255, 255, 255, 0.05))',
                        padding: '2.5rem',
                        borderRadius: '1.5rem',
                        border: '1px solid var(--border-color, rgba(255, 255, 255, 0.1))',
                    }}
                >
                    <h1 style={{ marginBottom: '1.5rem', fontSize: '2rem' }}>{t('support.title')}</h1>
                    <p style={{ marginBottom: '2rem', opacity: 0.8, lineHeight: '1.6' }}>
                        {t('support.description')}
                    </p>

                    {status === 'success' ? (
                        <div style={{
                            padding: '2rem',
                            background: 'rgba(16, 185, 129, 0.1)',
                            borderRadius: '1rem',
                            border: '1px solid rgba(16, 185, 129, 0.2)',
                            textAlign: 'center',
                            color: '#10B981'
                        }}>
                            <CheckCircle size={48} style={{ marginBottom: '1rem' }} />
                            <h3>{t('support.success.title')}</h3>
                            <p>{t('support.success.message')}</p>
                        </div>
                    ) : (
                        <form onSubmit={handleInitialSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1.5rem' }}>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: '500' }}>{t('support.form.lastname')}</label>
                                    <input
                                        type="text"
                                        required
                                        value={formData.nom}
                                        onChange={e => setFormData({ ...formData, nom: e.target.value })}
                                        className="form-input"
                                        style={{ width: '100%', padding: '0.8rem', borderRadius: '0.5rem', border: '1px solid var(--border-color)', background: 'rgba(0,0,0,0.2)', color: 'inherit' }}
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: '500' }}>{t('support.form.firstname')}</label>
                                    <input
                                        type="text"
                                        required
                                        value={formData.prenom}
                                        onChange={e => setFormData({ ...formData, prenom: e.target.value })}
                                        className="form-input"
                                        style={{ width: '100%', padding: '0.8rem', borderRadius: '0.5rem', border: '1px solid var(--border-color)', background: 'rgba(0,0,0,0.2)', color: 'inherit' }}
                                    />
                                </div>
                            </div>

                            <div>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: '500' }}>{t('support.form.accountemail')}</label>
                                <input
                                    type="email"
                                    required
                                    value={formData.account_email}
                                    onChange={e => handleAccountEmailChange(e.target.value)}
                                    className="form-input"
                                    style={{ width: '100%', padding: '0.8rem', borderRadius: '0.5rem', border: '1px solid var(--border-color)', background: 'rgba(0,0,0,0.2)', color: 'inherit' }}
                                />
                            </div>

                            <div style={{ marginBottom: '-0.5rem' }}>
                                <label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', opacity: 0.9 }}>
                                    <input
                                        type="checkbox"
                                        checked={formData.useSameEmail}
                                        onChange={e => handleSameEmailChange(e.target.checked)}
                                        style={{ width: '18px', height: '18px' }}
                                    />
                                    <span style={{ fontSize: '0.9rem' }}>
                                        {t('support.form.sameemail')}
                                    </span>
                                </label>
                            </div>

                            <div>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: '500' }}>{t('support.form.contactemail')}</label>
                                <input
                                    type="email"
                                    required
                                    value={formData.contact_email}
                                    onChange={e => setFormData({ ...formData, contact_email: e.target.value })}
                                    disabled={formData.useSameEmail} // Optional: disable if same
                                    className="form-input"
                                    style={{
                                        width: '100%',
                                        padding: '0.8rem',
                                        borderRadius: '0.5rem',
                                        border: '1px solid var(--border-color)',
                                        background: formData.useSameEmail ? 'rgba(0,0,0,0.1)' : 'rgba(0,0,0,0.2)',
                                        color: 'inherit',
                                        opacity: formData.useSameEmail ? 0.7 : 1
                                    }}
                                />
                            </div>

                            <div>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: '500' }}>{t('support.form.message')}</label>
                                <textarea
                                    required
                                    rows={5}
                                    value={formData.message}
                                    onChange={e => setFormData({ ...formData, message: e.target.value })}
                                    className="form-input"
                                    style={{ width: '100%', padding: '0.8rem', borderRadius: '0.5rem', border: '1px solid var(--border-color)', background: 'rgba(0,0,0,0.2)', color: 'inherit' }}
                                />
                            </div>

                            {status === 'error' && (
                                <div style={{ color: '#EF4444', display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.95rem' }}>
                                    <AlertCircle size={16} />
                                    {errorMessage}
                                </div>
                            )}

                            <button
                                type="submit"
                                disabled={status === 'submitting'}
                                className="btn btn-primary"
                                style={{
                                    marginTop: '1rem',
                                    padding: '1rem',
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    gap: '10px',
                                    opacity: status === 'submitting' ? 0.7 : 1,
                                    cursor: status === 'submitting' ? 'wait' : 'pointer'
                                }}
                            >
                                {status === 'submitting' ? t('support.form.submitting') : (
                                    <>
                                        <Send size={18} />
                                        {t('support.form.submit')}
                                    </>
                                )}
                            </button>
                        </form>
                    )}
                </motion.div>
            </div>

            {/* Confirmation Modal */}
            {showConfirmModal && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0, 0, 0, 0.7)',
                    backdropFilter: 'blur(5px)',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    zIndex: 1000,
                    padding: '20px'
                }}>
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        style={{
                            background: '#1a1a1a',
                            backgroundColor: 'var(--card-bg, #1a1a1a)',
                            padding: '2rem',
                            borderRadius: '1rem',
                            border: '1px solid var(--border-color, rgba(255,255,255,0.1))',
                            maxWidth: '500px',
                            width: '100%',
                            boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.5)'
                        }}
                    >
                        <h2 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
                            <AlertCircle size={24} color="var(--primary-color)" />
                            {t('modal.confirm.title')}
                        </h2>
                        <p style={{ marginBottom: '1.5rem', opacity: 0.8 }}>
                            {t('modal.confirm.message')}
                        </p>

                        <div style={{ background: 'rgba(255,255,255,0.05)', padding: '1rem', borderRadius: '0.5rem', marginBottom: '2rem', fontSize: '0.95rem' }}>
                            <p style={{ marginBottom: '0.5rem' }}><strong>{t('support.form.lastname')}:</strong> {formData.nom}</p>
                            <p style={{ marginBottom: '0.5rem' }}><strong>{t('support.form.firstname')}:</strong> {formData.prenom}</p>
                            <p style={{ marginBottom: '0.5rem' }}><strong>{t('support.form.accountemail')}:</strong> {formData.account_email}</p>
                            <p style={{ marginBottom: '0.5rem' }}><strong>{t('support.form.contactemail')}:</strong> {formData.contact_email}</p>
                            {formData.message && <p><strong>{t('support.form.message')}:</strong> <span style={{ opacity: 0.8, display: 'block', marginTop: '4px', fontStyle: 'italic' }}>"{formData.message}"</span></p>}
                        </div>

                        <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
                            <button
                                onClick={() => setShowConfirmModal(false)}
                                style={{
                                    padding: '0.8rem 1.5rem',
                                    borderRadius: '0.5rem',
                                    background: 'transparent',
                                    border: '1px solid var(--border-color)',
                                    color: 'inherit',
                                    cursor: 'pointer'
                                }}
                            >
                                {t('modal.btn.cancel')}
                            </button>
                            <button
                                onClick={handleFinalSubmit}
                                className="btn btn-primary"
                                style={{
                                    padding: '0.8rem 1.5rem',
                                    cursor: 'pointer'
                                }}
                            >
                                {t('modal.btn.confirm')}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}
        </div>
    );
};

export default Support;
