'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { uploadImage } from '@/lib/upload';
import { updateOrganigramDpm } from '@/lib/admin-actions';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

export default function ParlemenOrganigramForm({ profilId, initialUrl }: { profilId: string; initialUrl: string | null }) {
    const [file, setFile] = useState<File | null>(null);
    const [currentUrl, setCurrentUrl] = useState(initialUrl);
    const [isSaving, setIsSaving] = useState(false);

    const handleSave = async () => {
        if (!file) {
            toast.error("Pilih file terlebih dahulu");
            return;
        }
        setIsSaving(true);
        try {
            const url = await uploadImage(file);
            const res = await updateOrganigramDpm(profilId, url);
            if (res.success) {
                toast.success(res.message);
                setCurrentUrl(url);
                setFile(null);
            } else {
                toast.error(res.message);
            }
        } catch(e: any) {
            toast.error(e.message);
        } finally {
            setIsSaving(false);
        }
    };

    const previewUrl = file ? URL.createObjectURL(file) : currentUrl;

    return (
        <div className="bg-white border border-slate-200 rounded-3xl p-8 relative overflow-hidden flex flex-col md:flex-row gap-6 shadow-sm">
            <div className="flex-1 space-y-4">
                <div>
                    <h2 className="text-xl font-bold text-slate-800">Organigram DPM</h2>
                    <p className="text-slate-500 text-sm mt-1">Unggah bagan struktur organisasi Dewan Perwakilan Mahasiswa.</p>
                </div>
                <div className="space-y-2">
                    <Input type="file" accept="image/*" onChange={e => setFile(e.target.files?.[0] || null)} />
                </div>
                <Button onClick={handleSave} disabled={!file || isSaving}>
                    {isSaving ? 'Menyimpan...' : 'Simpan Organigram'}
                </Button>
            </div>
            <div className="w-full md:w-1/3 aspect-video bg-slate-50 border-2 border-dashed border-slate-200 rounded-xl flex items-center justify-center overflow-hidden">
                {previewUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={previewUrl} alt="Organigram" className="w-full h-full object-contain" />
                ) : (
                    <span className="text-slate-400 text-sm font-medium">Belum ada bagan</span>
                )}
            </div>
        </div>
    );
}
