'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Card, Input, Button } from '@zen/core/shared/components';
import { useToast } from '@zen/core/toast';

const ProfilePage = ({ user: initialUser }) => {
    const toast = useToast();
    const [user, setUser] = useState(initialUser);
    const [loading, setLoading] = useState(false);
    const [uploadingImage, setUploadingImage] = useState(false);
    const [imagePreview, setImagePreview] = useState(null);
    const fileInputRef = useRef(null);
    const [formData, setFormData] = useState({
        name: initialUser?.name || ''
    });

    // Helper function to get image URL from storage key
    const getImageUrl = (imageKey) => {
        if (!imageKey) return null;
        return `/zen/api/storage/${imageKey}`;
    };

    useEffect(() => {
        if (initialUser) {
            setFormData({
                name: initialUser.name || ''
            });
            setImagePreview(getImageUrl(initialUser.image));
        }
    }, [initialUser]);

    const handleChange = (value) => {
        setFormData(prev => ({
            ...prev,
            name: value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (!formData.name.trim()) {
            toast.error('Le nom est requis');
            return;
        }

        setLoading(true);

        try {
            const response = await fetch('/zen/api/users/profile', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
                body: JSON.stringify({
                    name: formData.name.trim()
                })
            });

            const data = await response.json();

            if (!response.ok || !data.success) {
                throw new Error(data.error || 'Échec de la mise à jour du profil');
            }

            setUser(data.user);
            toast.success('Profil mis à jour avec succès');
            
            // Refresh the page to update the user data in the header
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } catch (error) {
            console.error('Error updating profile:', error);
            toast.error(error.message || 'Échec de la mise à jour du profil');
        } finally {
            setLoading(false);
        }
    };

    const handleReset = () => {
        setFormData({
            name: user?.name || ''
        });
    };

    const handleImageSelect = async (e) => {
        const file = e.target.files?.[0];
        if (!file) return;

        // Validate file type
        if (!file.type.startsWith('image/')) {
            toast.error('Veuillez sélectionner un fichier image');
            return;
        }

        // Validate file size (5MB)
        if (file.size > 5 * 1024 * 1024) {
            toast.error("L'image doit faire moins de 5MB");
            return;
        }

        // Show preview
        const reader = new FileReader();
        reader.onloadend = () => {
            setImagePreview(reader.result);
        };
        reader.readAsDataURL(file);

        // Upload image
        setUploadingImage(true);
        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await fetch('/zen/api/users/profile/picture', {
                method: 'POST',
                credentials: 'include',
                body: formData
            });

            const data = await response.json();

            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Échec du téléchargement de l\'image');
            }

            setUser(data.user);
            setImagePreview(getImageUrl(data.user.image));
            toast.success('Photo de profil mise à jour avec succès');
        } catch (error) {
            console.error('Error uploading image:', error);
            toast.error(error.message || 'Échec du téléchargement de l\'image');
            // Revert preview on error
            setImagePreview(getImageUrl(user?.image));
        } finally {
            setUploadingImage(false);
        }
    };

    const handleRemoveImage = async () => {
        if (!user?.image) return;

        setUploadingImage(true);
        try {
            const response = await fetch('/zen/api/users/profile/picture', {
                method: 'DELETE',
                credentials: 'include'
            });

            const data = await response.json();

            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Échec de la suppression de l\'image');
            }

            setUser(data.user);
            setImagePreview(null);
            toast.success('Photo de profil supprimée avec succès');
        } catch (error) {
            console.error('Error removing image:', error);
            toast.error(error.message || 'Échec de la suppression de l\'image');
        } finally {
            setUploadingImage(false);
        }
    };

    const getUserInitials = (name) => {
        if (!name) return 'U';
        return name
            .split(' ')
            .map(n => n[0])
            .join('')
            .toUpperCase()
            .slice(0, 2);
    };

    const hasChanges = formData.name !== user?.name;

    return (
        <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">
                        Mon profil
                    </h1>
                    <p className="mt-1 text-xs text-neutral-400">
                        Gérez les informations de votre compte
                    </p>
                </div>
            </div>

            {/* Content */}
            <div className="flex flex-col gap-6">
            <Card>
                <div className="space-y-4">
                    <h2 className="text-lg font-semibold text-neutral-900 dark:text-white">
                        Photo de profil
                    </h2>
                    <div className="flex items-center gap-6">
                        <div className="relative">
                            {imagePreview ? (
                                <img
                                    src={imagePreview}
                                    alt="Profile"
                                    className="w-24 h-24 rounded-full object-cover border-2 border-neutral-300 dark:border-neutral-700"
                                />
                            ) : (
                                <div className="w-24 h-24 bg-gradient-to-br from-neutral-200 to-neutral-300 dark:from-neutral-800 dark:to-neutral-700 rounded-full flex items-center justify-center border-2 border-neutral-300 dark:border-neutral-700">
                                    <span className="text-neutral-700 dark:text-white font-semibold text-2xl">
                                        {getUserInitials(user?.name)}
                                    </span>
                                </div>
                            )}
                            {uploadingImage && (
                                <div className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center">
                                    <div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                </div>
                            )}
                        </div>
                        <div className="flex flex-col gap-2">
                            <p className="text-sm text-neutral-400">
                                Téléchargez une nouvelle photo de profil. Taille max 5MB.
                            </p>
                            <div className="flex gap-2">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/*"
                                    onChange={handleImageSelect}
                                    className="hidden"
                                />
                                <Button
                                    type="button"
                                    variant="secondary"
                                    onClick={() => fileInputRef.current?.click()}
                                    disabled={uploadingImage}
                                >
                                    {uploadingImage ? 'Téléchargement...' : 'Télécharger une image'}
                                </Button>
                                {imagePreview && (
                                    <Button
                                        type="button"
                                        variant="secondary"
                                        onClick={handleRemoveImage}
                                        disabled={uploadingImage}
                                    >
                                        Supprimer
                                    </Button>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </Card>

            <Card>
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="space-y-4">
                        <h2 className="text-lg font-semibold text-neutral-900 dark:text-white">
                            Informations personnelles
                        </h2>
                        
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <Input
                                label="Nom complet"
                                type="text"
                                value={formData.name}
                                onChange={handleChange}
                                placeholder="Entrez votre nom complet"
                                required
                                disabled={loading}
                            />

                            <Input
                                label="Courriel"
                                name="email"
                                type="email"
                                value={user?.email || ''}
                                disabled
                                readOnly
                                description="L'email ne peut pas être modifié"
                            />
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <Input
                                label="Compte créé"
                                name="createdAt"
                                type="text"
                                value={user?.created_at ? new Date(user.created_at).toLocaleDateString('fr-FR', {
                                    year: 'numeric',
                                    month: 'long',
                                    day: 'numeric'
                                }) : 'N/D'}
                                disabled
                                readOnly
                            />
                        </div>
                    </div>

                    {/* Action Buttons */}
                    <div className="flex items-center justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700/50">
                        <Button
                            type="button"
                            variant="secondary"
                            onClick={handleReset}
                            disabled={loading || !hasChanges}
                        >
                            Réinitialiser
                        </Button>
                        <Button
                            type="submit"
                            variant="primary"
                            disabled={loading || !hasChanges}
                            loading={loading}
                        >
                            {loading ? 'Enregistrement...' : 'Enregistrer les modifications'}
                        </Button>
                    </div>
                </form>
            </Card>
            </div>
        </div>
    );
};

export default ProfilePage;
