'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { createAcaraTab, updateAcaraTab, deleteAcaraTab } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Pencil, Trash2, Plus, X, Layers } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';

type AcaraTab = {
    id: string;
    judul: string;
    deskripsi: string;
    gambarUrl: string | null;
    gambarPosisi: string;
    acaraId: string;
};

type AcaraData = {
    id: string;
    slug: string;
    nama: string;
    tabs: AcaraTab[];
};

export default function AcaraClientPage({ initialAcara }: { initialAcara: AcaraData }) {
    const [acara, setAcara] = useState<AcaraData>(initialAcara);

    return (
        <div className="space-y-6">
            <TabsSection acara={acara} setAcara={setAcara} />
        </div>
    );
}

function TabsSection({
    acara,
    setAcara,
}: {
    acara: AcaraData;
    setAcara: React.Dispatch<React.SetStateAction<AcaraData>>;
}) {
    const [showAddForm, setShowAddForm] = useState(false);
    const [addJudul, setAddJudul] = useState('');
    const [addDeskripsi, setAddDeskripsi] = useState('');
    const [addGambarPosisi, setAddGambarPosisi] = useState('atas');
    const [addGambarFile, setAddGambarFile] = useState<File | null>(null);
    const [addGambarUrl, setAddGambarUrl] = useState('');
    const [isAdding, setIsAdding] = useState(false);

    const [editItem, setEditItem] = useState<AcaraTab | null>(null);
    const [editJudul, setEditJudul] = useState('');
    const [editDeskripsi, setEditDeskripsi] = useState('');
    const [editGambarPosisi, setEditGambarPosisi] = useState('atas');
    const [editGambarFile, setEditGambarFile] = useState<File | null>(null);
    const [editGambarUrl, setEditGambarUrl] = useState('');
    const [isEditing, setIsEditing] = useState(false);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    const handleAdd = async () => {
        if (!addJudul.trim() || !addDeskripsi.trim()) {
            toast.error('Judul dan Deskripsi wajib diisi');
            return;
        }
        setIsAdding(true);
        try {
            let finalGambarUrl = addGambarUrl.trim() || undefined;
            if (addGambarFile) {
                finalGambarUrl = await uploadImage(addGambarFile);
            }
            const result = await createAcaraTab({
                judul: addJudul.trim(),
                deskripsi: addDeskripsi.trim(),
                gambarUrl: finalGambarUrl,
                gambarPosisi: addGambarPosisi,
                acaraId: acara.id,
            });
            if (result.success) {
                toast.success(result.message);
                setAddJudul(''); setAddDeskripsi(''); setAddGambarUrl(''); setAddGambarFile(null);
                setShowAddForm(false);
                if (result.data) {
                    setAcara(prev => ({ ...prev, tabs: [...prev.tabs, result.data as AcaraTab] }));
                }
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsAdding(false); }
    };

    const openEdit = (item: AcaraTab) => {
        setEditItem(item);
        setEditJudul(item.judul);
        setEditDeskripsi(item.deskripsi);
        setEditGambarPosisi(item.gambarPosisi);
        setEditGambarUrl(item.gambarUrl ?? '');
        setEditGambarFile(null);
    };

    const handleEdit = async () => {
        if (!editItem || !editJudul.trim() || !editDeskripsi.trim()) {
            toast.error('Judul dan Deskripsi wajib diisi');
            return;
        }
        setIsEditing(true);
        try {
            let finalGambarUrl = editGambarUrl.trim() || undefined;
            if (editGambarFile) {
                finalGambarUrl = await uploadImage(editGambarFile);
            }
            const payload = {
                judul: editJudul.trim(),
                deskripsi: editDeskripsi.trim(),
                gambarUrl: finalGambarUrl,
                gambarPosisi: editGambarPosisi,
            };
            const result = await updateAcaraTab(editItem.id, payload);
            if (result.success) {
                toast.success(result.message);
                setAcara((prev) => ({
                    ...prev,
                    tabs: prev.tabs.map((t) =>
                        t.id === editItem.id ? { ...t, ...payload, gambarUrl: finalGambarUrl || null } : t
                    ),
                }));
                setEditGambarFile(null);
                setEditItem(null);
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsEditing(false); }
    };

    const handleDelete = async (id: string, judul: string) => {
        if (!confirm(`Hapus tab "${judul}"?`)) return;
        setDeletingId(id);
        try {
            const result = await deleteAcaraTab(id);
            if (result.success) {
                toast.success(result.message);
                setAcara((prev) => ({ ...prev, tabs: prev.tabs.filter((t) => t.id !== id) }));
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setDeletingId(null); }
    };

    return (
        <Card>
            <CardHeader>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                        <div className="p-2 bg-primary/10 rounded-lg">
                            <Layers className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                            <CardTitle className="text-base">Tabs Acara</CardTitle>
                            <CardDescription>Kelola tab konten yang akan ditampilkan di halaman detail Acara.</CardDescription>
                        </div>
                    </div>
                    <Button size="sm" onClick={() => setShowAddForm(!showAddForm)} variant={showAddForm ? 'outline' : 'default'}>
                        {showAddForm ? <X className="h-4 w-4 mr-1" /> : <Plus className="h-4 w-4 mr-1" />}
                        {showAddForm ? 'Batal' : 'Tambah Tab'}
                    </Button>
                </div>
            </CardHeader>
            <CardContent className="space-y-4">
                {/* Add form */}
                {showAddForm && (
                    <div className="border border-dashed border-primary/40 rounded-lg p-4 space-y-4 bg-primary/5">
                        <div className="space-y-2">
                            <Label className="text-xs">Judul Tab</Label>
                            <Input value={addJudul} onChange={(e) => setAddJudul(e.target.value)} placeholder="Contoh: Deskripsi, Jadwal, Aturan..." />
                        </div>
                        <div className="space-y-2">
                            <Label className="text-xs">Deskripsi / Konten (Mendukung Markdown)</Label>
                            <Textarea value={addDeskripsi} onChange={(e) => setAddDeskripsi(e.target.value)} rows={5} placeholder="Konten tab..." />
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label className="text-xs">Gambar (opsional)</Label>
                                <Input type="file" accept="image/*" onChange={(e) => setAddGambarFile(e.target.files?.[0] || null)} />
                            </div>
                            <div className="space-y-2">
                                <Label className="text-xs">Posisi Gambar</Label>
                                <select 
                                    className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                    value={addGambarPosisi} 
                                    onChange={(e) => setAddGambarPosisi(e.target.value)}
                                >
                                    <option value="atas">Atas</option>
                                    <option value="tengah">Tengah</option>
                                    <option value="bawah">Bawah</option>
                                </select>
                            </div>
                        </div>
                        <div className="flex justify-end pt-2">
                            <Button size="sm" onClick={handleAdd} disabled={isAdding}>
                                {isAdding ? 'Menambahkan...' : 'Simpan Tab'}
                            </Button>
                        </div>
                    </div>
                )}

                {/* List tabs */}
                {acara.tabs.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                        Belum ada tab ditambahkan.
                    </div>
                ) : (
                    <div className="divide-y divide-border rounded-lg border border-border overflow-hidden">
                        {acara.tabs.map((t, i) => (
                            <div key={t.id} className="flex items-start gap-4 px-4 py-4">
                                <span className="text-xs font-mono text-muted-foreground mt-1 w-5 shrink-0">{i + 1}.</span>
                                {t.gambarUrl && (
                                    <div className="w-16 h-16 shrink-0 rounded bg-slate-100 overflow-hidden border">
                                        <img src={t.gambarUrl} alt="tab image" className="w-full h-full object-cover" />
                                    </div>
                                )}
                                <div className="flex-1 min-w-0 space-y-1">
                                    <p className="font-semibold text-sm text-foreground">{t.judul}</p>
                                    <p className="text-xs text-muted-foreground line-clamp-2">{t.deskripsi}</p>
                                    <p className="text-xs text-primary/70 mt-1 font-mono">Posisi Gambar: {t.gambarPosisi}</p>
                                </div>
                                <div className="flex gap-1 shrink-0">
                                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(t)}>
                                        <Pencil className="h-4 w-4" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-destructive"
                                        onClick={() => handleDelete(t.id, t.judul)}
                                        disabled={deletingId === t.id}
                                    >
                                        <Trash2 className="h-4 w-4" />
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </CardContent>

            {/* Edit Dialog */}
            <Dialog open={!!editItem} onOpenChange={(o) => { if (!o) setEditItem(null); }}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Edit Tab</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-2">
                            <Label>Judul</Label>
                            <Input value={editJudul} onChange={(e) => setEditJudul(e.target.value)} />
                        </div>
                        <div className="space-y-2">
                            <Label>Deskripsi / Konten</Label>
                            <Textarea value={editDeskripsi} onChange={(e) => setEditDeskripsi(e.target.value)} rows={6} />
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Ganti Gambar</Label>
                                <div className="flex items-center gap-2">
                                    {editGambarUrl && <img src={editGambarUrl} className="w-10 h-10 object-cover rounded" alt="img" />}
                                    <Input type="file" accept="image/*" onChange={(e) => setEditGambarFile(e.target.files?.[0] || null)} />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <Label>Posisi Gambar</Label>
                                <select 
                                    className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                    value={editGambarPosisi} 
                                    onChange={(e) => setEditGambarPosisi(e.target.value)}
                                >
                                    <option value="atas">Atas</option>
                                    <option value="tengah">Tengah</option>
                                    <option value="bawah">Bawah</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="ghost" onClick={() => setEditItem(null)}>Batal</Button>
                        <Button onClick={handleEdit} disabled={isEditing}>
                            {isEditing ? 'Menyimpan...' : 'Simpan Perubahan'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </Card>
    );
}
