import Popup from "@/components/PopUp";
import Button from "@/components/Button";
import loginStyles from "@/styles/login.module.css";
import { useState } from "react";
import { useSession } from "next-auth/react";

interface Props {
    open: boolean;
    onClose: () => void;
}

export default function ProfilePicturePopup({ open, onClose }: Props) {
    const { update } = useSession();

    const [imageFile, setImageFile] = useState<File | null>(null);
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState("");

    async function handleUpload(e: React.FormEvent) {
        e.preventDefault();
        setLoading(true);
        setMessage("");

        try {
            if (!imageFile) {
                setMessage("Bitte eine Datei auswählen.");
                return;
            }

            const formData = new FormData();
            formData.append("file", imageFile);

            const res = await fetch("/api/user/update-profile-picture", {
                method: "POST",
                body: formData,
            });

            const data = await res.json();
            if (!res.ok) throw new Error(data.error || "Fehler beim Upload.");

            await update({ image: data.path });

            setMessage("Profilbild erfolgreich geändert.");
            setTimeout(onClose, 1000);
        } catch (err: unknown) {
            setMessage(err instanceof Error ? err.message : "Unbekannter Fehler");
        } finally {
            setLoading(false);
        }
    }

    return (
        <Popup isOpen={open} onClose={onClose}>
            <h2>Profilbild ändern</h2>

            <form onSubmit={handleUpload}>
                <div className={loginStyles.formGroup}>
                        <input
                            type="file"
                            accept="image/png, image/jpeg, image/jpg, image/webp"
                            onChange={(e) => setImageFile(e.target.files?.[0] || null)}
                        />
                </div>

                <Button type="submit" disabled={loading}>
                    {loading ? "Hochladen..." : "Speichern"}
                </Button>

                {message && <p style={{ color: "var(--color-contrast)" }}>{message}</p>}
            </form>
        </Popup>
    );
}
