import { Head, router, useForm } from '@inertiajs/react';
import { FormEventHandler, useState } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';

interface NewsItem {
    id: number;
    title: string;
    body: string;
    url: string | null;
    published_at: string | null;
}

interface Props {
    news: { data: NewsItem[] };
}

export default function Index({ news }: Props) {
    const [editing, setEditing] = useState<NewsItem | null>(null);
    const { data, setData, post, put, processing, errors, reset } = useForm({
        title: '',
        body: '',
        url: '',
        published_at: '',
    });

    const startEdit = (item: NewsItem) => {
        setEditing(item);
        setData({
            title: item.title,
            body: item.body,
            url: item.url ?? '',
            published_at: item.published_at ?? '',
        });
    };

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        if (editing) {
            put(route('admin.news.update', editing.id), { onSuccess: () => (setEditing(null), reset()) });
        } else {
            post(route('admin.news.store'), { onSuccess: () => reset() });
        }
    };

    return (
        <AdminLayout>
            <Head title="News — Admin" />
            <h1 className="mb-6 text-2xl font-bold">News</h1>

            <form onSubmit={submit} className="mb-8 space-y-3 rounded-lg bg-gray-900 p-5 ring-1 ring-white/10">
                <h2 className="font-semibold">{editing ? `Editing: ${editing.title}` : 'New post'}</h2>
                <input
                    placeholder="Title"
                    value={data.title}
                    onChange={(e) => setData('title', e.target.value)}
                    className="w-full rounded-md border-gray-700 bg-gray-800 text-white"
                />
                {errors.title && <p className="text-sm text-red-400">{errors.title}</p>}

                <textarea
                    placeholder="Body"
                    rows={5}
                    value={data.body}
                    onChange={(e) => setData('body', e.target.value)}
                    className="w-full rounded-md border-gray-700 bg-gray-800 text-white"
                />
                {errors.body && <p className="text-sm text-red-400">{errors.body}</p>}

                <div className="flex gap-3">
                    <input
                        type="datetime-local"
                        value={data.published_at}
                        onChange={(e) => setData('published_at', e.target.value)}
                        className="rounded-md border-gray-700 bg-gray-800 text-white"
                    />
                    <input
                        placeholder="External URL (optional)"
                        value={data.url}
                        onChange={(e) => setData('url', e.target.value)}
                        className="flex-1 rounded-md border-gray-700 bg-gray-800 text-white"
                    />
                </div>

                <div className="flex gap-2">
                    <button
                        type="submit"
                        disabled={processing}
                        className="rounded-md bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
                    >
                        {editing ? 'Save changes' : 'Publish'}
                    </button>
                    {editing && (
                        <button
                            type="button"
                            onClick={() => (setEditing(null), reset())}
                            className="rounded-md bg-gray-800 px-4 py-2 text-sm text-gray-300 hover:bg-gray-700"
                        >
                            Cancel
                        </button>
                    )}
                </div>
            </form>

            <div className="divide-y divide-white/10 rounded-lg bg-gray-900 ring-1 ring-white/10">
                {news.data.map((item) => (
                    <div key={item.id} className="flex items-center justify-between px-5 py-3">
                        <div>
                            <p className="font-medium">{item.title}</p>
                            <p className="text-xs text-gray-500">
                                {item.published_at ? new Date(item.published_at).toLocaleString() : 'Draft'}
                            </p>
                        </div>
                        <div className="flex gap-2">
                            <button onClick={() => startEdit(item)} className="text-sm text-brand-400 hover:text-brand-300">
                                Edit
                            </button>
                            <button
                                onClick={() => confirm('Delete this post?') && router.delete(route('admin.news.destroy', item.id))}
                                className="text-sm text-red-400 hover:text-red-300"
                            >
                                Delete
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        </AdminLayout>
    );
}
