import React, { useState, useRef, useEffect } from 'react';
import { useUser } from '../contexts/UserContext';
import ArticleTable from "../components/ArticleTable";
import api from '../utils/api';
import { Article } from '../types/article';
import Avatar from '@mui/material/Avatar';

export default function UserProfile() {
    const { user, updateUserPP, updateBio } = useUser();
    const [isEditing, setIsEditing] = useState(false);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [editedUserData, setEditedUserData] = useState({
        username: user?.username || '',
        email: user?.email || '',
        bio: user?.bio || '',
        profilePicture: user?.profilePicture || null
    });
    const [previewImage, setPreviewImage] = useState<string | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [articles, setArticles] = useState<Article[]>([]);

    const handleInputChange = (field: string, value: string) => {
        setEditedUserData(prev => ({ ...prev, [field]: value }));
    };

    console.log(user);

    const triggerFileInput = () => {
        fileInputRef.current?.click();
    };

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setSelectedFile(file);

            const reader = new FileReader();
            reader.onloadend = () => {
                setPreviewImage(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    useEffect(() => {
        const fetchArticles = async () => {
            api.get(`/articles/self`)
                .then(res => {
                    setArticles(res.data.articles);
                });

        };

        if (user) {
            fetchArticles();
        }

    }, [user]);


    const handleSave = async () => {
        setIsEditing(false);
        
        updateBio(editedUserData.bio); // TODO: Update bio in backend

        
        if (selectedFile) {
            const fileData = new FormData();
            fileData.append('file', selectedFile);

            try {
                await api.post('/profile/uploadprofileimage', fileData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });

                // Assume backend responds with: { image: "newfilename.jpg" }
                const imageFileName = user?.id + '.jpg';
                const newImageUrl = import.meta.env.VITE_PROFILE_PICTURES_URL + imageFileName;

                // Update global context
                updateUserPP(newImageUrl);

                // Update local state
                setEditedUserData(prev => ({
                    ...prev,
                    profilePicture: newImageUrl,
                }));

                setPreviewImage(null);
                setSelectedFile(null);
            } catch (error) {
                console.error('Error uploading profile picture:', error);
            }
        }
    };



    if (!user) return <div className="p-8 text-center">Uživatel není přihlášen.</div>;

    return (
        <div className="container mx-auto my-8 px-4">

            <div className="flex flex-col md:flex-row gap-6 mb-8">
                {/* Profile Image */}
                <div className="flex flex-col items-center">
                    {previewImage || (editedUserData.profilePicture && editedUserData.profilePicture.trim() !== import.meta.env.VITE_PROFILE_PICTURES_URL) ? (
                        <div className="w-32 h-32 overflow-hidden rounded-full border-4 border-green-950 shadow-lg">
                            <img
                                src={previewImage || editedUserData.profilePicture || undefined}
                                alt="Profilový obrázek"
                                className="w-full h-full object-cover"
                            />
                        </div>)
                        : <Avatar sx={{ height: '8rem', width: '8rem', fontSize: '4rem' }}>{user?.username.charAt(0)}</Avatar>
                    }
                    {isEditing && (
                        <button
                            onClick={triggerFileInput}
                            className="mt-3 px-3 py-1 bg-green-700 text-white rounded hover:bg-green-800"
                        >
                            Změnit foto
                        </button>
                    )}
                    <input
                        type="file"
                        ref={fileInputRef}
                        className="hidden"
                        accept="image/*"
                        onChange={handleImageChange}
                    />
                </div>

                {/* Profile Form */}
                <div className="flex-1">
                    {isEditing ? (
                        <>
                            <div className="mb-4">
                                <label className="block mb-1 font-semibold">Uživatelské jméno</label>
                                <input
                                    type="text"
                                    value={editedUserData.username}
                                    className="w-full border rounded px-3 py-2 bg-gray-100 cursor-not-allowed"
                                    disabled
                                />
                            </div>

                            <div className="mb-4">
                                <label className="block mb-1 font-semibold">Email</label>
                                <input
                                    type="email"
                                    value={editedUserData.email}
                                    className="w-full border rounded px-3 py-2 bg-gray-100 cursor-not-allowed"
                                    disabled
                                />
                            </div>


                            <div className="mb-4">
                                <label className="block mb-1 font-semibold">Bio</label>
                                <textarea
                                    value={editedUserData.bio}
                                    onChange={(e) => handleInputChange('bio', e.target.value)}
                                    className="w-full border rounded px-3 py-2 h-24"
                                />
                            </div>
                        </>
                    ) : (
                        <>
                            <h2 className="text-xl font-semibold mb-2">{user.username}</h2>
                            <div className="mb-2"><strong>Email:</strong> {user.email}</div>
                            <div className="mb-2"><strong>Bio:</strong> {user.bio || ''}</div>
                        </>
                    )}

                    <div className="mt-6 space-x-4">
                        {isEditing ? (
                            <>
                                <button
                                    onClick={handleSave}
                                    className="bg-green-950 hover:bg-green-800 text-white font-medium py-2 px-4 rounded"
                                >
                                    Uložit změny
                                </button>
                                <button
                                    onClick={() => setIsEditing(false)}
                                    className="bg-gray-400 hover:bg-gray-500 text-white font-medium py-2 px-4 rounded"
                                >
                                    Zrušit
                                </button>
                            </>
                        ) : (
                            <button
                                onClick={() => setIsEditing(true)}
                                className="bg-green-950 hover:bg-green-800 text-white font-medium py-2 px-4 rounded"
                            >
                                Upravit profil
                            </button>
                        )}
                        {/*
                        <button className="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded">
                            Změnit heslo
                        </button>
                        */
                        }
                    </div>
                </div>
            </div>

            <ArticleTable articles={articles} />
        </div>
    );
}
