'use client';

import { useEffect, useState } from 'react';
import { heroApi } from '@/lib/api/admin';
import type { Hero } from '@/types';
import {
    PageHeader, AddButton, Table, TableRow, TableCell, StatusBadge,
    ActionButton, ConfirmDialog, Modal, FormField, Input, Textarea,
    Toggle, ImageUpload, SubmitButton, ErrorAlert, EmptyState, LoadingSpinner, ImagePreview
} from '@/components/Ui';

export default function HeroesPage() {
    const [heroes, setHeroes] = useState<Hero[]>([]);
    const [loading, setLoading] = useState(true);
    const [modalOpen, setModalOpen] = useState(false);
    const [editing, setEditing] = useState<Hero | null>(null);
    const [deleteTarget, setDeleteTarget] = useState<Hero | null>(null);
    const [deleting, setDeleting] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [form, setForm] = useState({ title: '', description: '', is_active: true });
    const [imageFile, setImageFile] = useState<File | null>(null);

    const fetch = async () => { try { const r = await heroApi.getAll(); setHeroes(r.data); } finally { setLoading(false); } };
    useEffect(() => { fetch(); }, []);

    const openCreate = () => { setEditing(null); setForm({ title: '', description: '', is_active: true }); setImageFile(null); setError(''); setModalOpen(true); };
    const openEdit = (h: Hero) => { setEditing(h); setForm({ title: h.title, description: h.description, is_active: h.is_active }); setImageFile(null); setError(''); setModalOpen(true); };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault(); setSaving(true); setError('');
        try {
            const fd = new FormData();
            fd.append('title', form.title);
            fd.append('description', form.description);
            fd.append('is_active', form.is_active ? '1' : '0');
            if (imageFile) fd.append('image', imageFile);
            if (editing) { await heroApi.update(editing.id, fd); } else { await heroApi.create(fd); }
            setModalOpen(false); fetch();
        } catch (err: any) { setError(err.message || 'Failed to save'); } finally { setSaving(false); }
    };

    const handleDelete = async () => {
        if (!deleteTarget) return; setDeleting(true);
        try { await heroApi.delete(deleteTarget.id); setDeleteTarget(null); fetch(); } finally { setDeleting(false); }
    };

    if (loading) return <LoadingSpinner />;

    return (
        <div className="space-y-6">
            <PageHeader title="Heroes" subtitle="Manage hero sliders on homepage" action={<AddButton onClick={openCreate} />} />

            {heroes.length === 0 ? <div className="bg-white rounded-xl shadow-sm"><EmptyState /></div> : (
                <Table headers={['#', 'Image', 'Title', 'Description', 'Status', 'Actions']}>
                    {heroes.map((h, i) => (
                        <TableRow key={h.id}>
                            <TableCell>{i + 1}</TableCell>
                            <TableCell><ImagePreview src={h.image} alt={h.title} size={10} /></TableCell>
                            <TableCell><span className="font-medium">{h.title}</span></TableCell>
                            <TableCell className="max-w-xs"><p className="truncate text-sec">{h.description}</p></TableCell>
                            <TableCell><StatusBadge active={h.is_active} /></TableCell>
                            <TableCell>
                                <div className="flex gap-1">
                                    <ActionButton variant="edit" onClick={() => openEdit(h)} />
                                    <ActionButton variant="delete" onClick={() => setDeleteTarget(h)} />
                                </div>
                            </TableCell>
                        </TableRow>
                    ))}
                </Table>
            )}

            <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Edit Hero' : 'Add Hero'}>
                <form onSubmit={handleSubmit} className="space-y-4">
                    <ErrorAlert message={error} />
                    <FormField label="Title" required><Input value={form.title} onChange={e => setForm(p => ({ ...p, title: e.target.value }))} placeholder="Hero title" required /></FormField>
                    <FormField label="Description" required><Textarea value={form.description} onChange={e => setForm(p => ({ ...p, description: e.target.value }))} placeholder="Hero description" rows={3} required /></FormField>
                    <ImageUpload currentImage={editing?.image} onChange={setImageFile} />
                    <Toggle checked={form.is_active} onChange={v => setForm(p => ({ ...p, is_active: v }))} label="Active" />
                    <SubmitButton loading={saving} />
                </form>
            </Modal>

            <ConfirmDialog isOpen={!!deleteTarget} onClose={() => setDeleteTarget(null)} onConfirm={handleDelete} loading={deleting} title="Delete Hero" message={`Are you sure you want to delete "${deleteTarget?.title}"?`} />
        </div>
    );
}