'use client';

import { useState, useEffect } from 'react';
import { Qrcode } from '@/types/medical';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { getImageUrl } from '@/lib/config';

export interface QrcodeFormData {
    qrcode: string;
}

interface QrcodeModalProps {
    qrcode?: Qrcode | null;
    onClose: () => void;
    onSubmit: (data: QrcodeFormData) => Promise<void>;
    title: string;
}

export default function QrcodeModal({
    qrcode,
    onClose,
    onSubmit,
    title,
}: QrcodeModalProps) {
    const { token } = useAuth();
    const [formData, setFormData] = useState<QrcodeFormData>({
        qrcode: '',
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [uploadingImage, setUploadingImage] = useState(false);
    const [imagePreview, setImagePreview] = useState<string>('');

    useEffect(() => {
        if (qrcode) {
            setFormData({
                qrcode: qrcode.qrcode || '',
            });
            // Utiliser getImageUrl pour l'aperçu
            setImagePreview(qrcode.qrcode ? getImageUrl(qrcode.qrcode) : '');
        } else {
            setFormData({
                qrcode: '',
            });
            setImagePreview('');
        }
    }, [qrcode]);

    const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file || !token) return;

        // Validation du fichier
        if (!file.type.startsWith('image/')) {
            setError('Veuillez sélectionner une image');
            return;
        }

        if (file.size > 5000000) {
            setError('L\'image est trop volumineuse (max 5MB)');
            return;
        }

        setUploadingImage(true);
        setError(null);

        try {
            // Upload l'image
            const result = await api.uploadQrcodeImage(token, file);

            // Mettre à jour le formulaire avec le chemin de l'image
            setFormData({ ...formData, qrcode: result.fileName });

            // Créer l'URL complète pour l'aperçu
            setImagePreview(getImageUrl(result.fileName));
        } catch (err: any) {
            setError(err.message || 'Erreur lors de l\'upload de l\'image');
        } finally {
            setUploadingImage(false);
        }
    };

    // Bloquer le scroll du body
    useEffect(() => {
        document.body.classList.add('modal-open');
        return () => {
            document.body.classList.remove('modal-open');
        };
    }, []);

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

        try {
            await onSubmit(formData);
            onClose();
        } catch (err: any) {
            setError(err.message || 'Une erreur est survenue');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div
            onClick={onClose}
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 9999,
            }}
        >
            <div
                onClick={(e) => e.stopPropagation()}
                style={{
                    backgroundColor: 'white',
                    borderRadius: '12px',
                    boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1)',
                    maxWidth: '500px',
                    width: '100%',
                    margin: '0 16px',
                    maxHeight: '90vh',
                    overflow: 'auto',
                }}
            >
                {/* Header */}
                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        padding: '24px',
                        borderBottom: '1px solid #E5E7EB',
                    }}
                >
                    <h2
                        style={{
                            fontSize: '20px',
                            fontWeight: '600',
                            color: '#111827',
                            margin: 0,
                        }}
                    >
                        {title}
                    </h2>
                    <button
                        onClick={onClose}
                        style={{
                            color: '#9CA3AF',
                            cursor: 'pointer',
                            background: 'none',
                            border: 'none',
                            padding: '8px',
                        }}
                    >
                        <svg
                            style={{ width: '24px', height: '24px' }}
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M6 18L18 6M6 6l12 12"
                            />
                        </svg>
                    </button>
                </div>

                {/* Form */}
                <form onSubmit={handleSubmit} style={{ padding: '24px' }}>
                    {error && (
                        <div
                            style={{
                                marginBottom: '16px',
                                padding: '12px',
                                backgroundColor: '#FEE2E2',
                                border: '1px solid #FCA5A5',
                                borderRadius: '6px',
                                color: '#991B1B',
                                fontSize: '14px',
                            }}
                        >
                            {error}
                        </div>
                    )}

                    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                        {/* Image du QR Code */}
                        <div>
                            <label
                                htmlFor="qrcode"
                                style={{
                                    display: 'block',
                                    fontSize: '14px',
                                    fontWeight: '500',
                                    color: '#374151',
                                    marginBottom: '6px',
                                }}
                            >
                                Image du QR Code *
                            </label>

                            {/* Aperçu de l'image */}
                            {imagePreview && (
                                <div
                                    style={{
                                        marginBottom: '12px',
                                        border: '2px solid #E5E7EB',
                                        borderRadius: '8px',
                                        overflow: 'hidden',
                                        width: '200px',
                                        height: '200px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        backgroundColor: '#F9FAFB',
                                    }}
                                >
                                    <img
                                        src={imagePreview}
                                        alt="Aperçu du QR Code"
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            objectFit: 'contain',
                                        }}
                                    />
                                </div>
                            )}

                            {/* Bouton d'upload */}
                            <label
                                htmlFor="imageUpload"
                                style={{
                                    display: 'inline-block',
                                    padding: '10px 16px',
                                    backgroundColor: uploadingImage ? '#9CA3AF' : '#10B981',
                                    color: 'white',
                                    borderRadius: '6px',
                                    cursor: uploadingImage ? 'not-allowed' : 'pointer',
                                    fontSize: '14px',
                                    fontWeight: '500',
                                    marginBottom: '8px',
                                }}
                            >
                                {uploadingImage ? 'Upload en cours...' : '📷 Choisir une image'}
                            </label>
                            <input
                                type="file"
                                id="imageUpload"
                                accept="image/*"
                                onChange={handleImageChange}
                                disabled={uploadingImage}
                                style={{ display: 'none' }}
                            />

                            {/* Ou saisir une URL */}
                            <div style={{ marginTop: '12px' }}>
                                <label
                                    style={{
                                        display: 'block',
                                        fontSize: '12px',
                                        color: '#6B7280',
                                        marginBottom: '4px',
                                    }}
                                >
                                    Ou saisir une URL :
                                </label>
                                <input
                                    type="text"
                                    placeholder="https://example.com/qrcode.jpg"
                                    value={formData.qrcode}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setFormData({ ...formData, qrcode: value });
                                        // Utiliser getImageUrl si ce n'est pas déjà une URL complète
                                        setImagePreview(value.startsWith('http') ? value : getImageUrl(value));
                                    }}
                                    style={{
                                        width: '100%',
                                        padding: '10px 12px',
                                        border: '1px solid #D1D5DB',
                                        borderRadius: '6px',
                                        fontSize: '14px',
                                        boxSizing: 'border-box',
                                    }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Actions */}
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'flex-end',
                            gap: '12px',
                            marginTop: '24px',
                        }}
                    >
                        <button
                            type="button"
                            onClick={onClose}
                            disabled={loading}
                            style={{
                                padding: '10px 16px',
                                backgroundColor: 'white',
                                color: '#374151',
                                border: '1px solid #D1D5DB',
                                borderRadius: '6px',
                                fontSize: '14px',
                                fontWeight: '500',
                                cursor: loading ? 'not-allowed' : 'pointer',
                                opacity: loading ? 0.6 : 1,
                            }}
                        >
                            Annuler
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            style={{
                                padding: '10px 16px',
                                backgroundColor: loading ? '#9CA3AF' : '#10B981',
                                color: 'white',
                                border: 'none',
                                borderRadius: '6px',
                                fontSize: '14px',
                                fontWeight: '500',
                                cursor: loading ? 'not-allowed' : 'pointer',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px',
                            }}
                        >
                            {loading && (
                                <svg
                                    style={{
                                        animation: 'spin 1s linear infinite',
                                        width: '16px',
                                        height: '16px',
                                    }}
                                    fill="none"
                                    viewBox="0 0 24 24"
                                >
                                    <circle
                                        style={{ opacity: 0.25 }}
                                        cx="12"
                                        cy="12"
                                        r="10"
                                        stroke="currentColor"
                                        strokeWidth="4"
                                    />
                                    <path
                                        style={{ opacity: 0.75 }}
                                        fill="currentColor"
                                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                    />
                                </svg>
                            )}
                            {loading ? 'Enregistrement...' : qrcode ? 'Modifier' : 'Créer'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}