import { Head, router } from '@inertiajs/react';
import { Check, CalendarClock, ExternalLink, X } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

import DashboardLayout from '@/components/dashboard/DashboardLayout';
import { DashboardPageHeader } from '@/components/dashboard/DashboardPageHeader';
import DataTable, { Column, Paginator } from '@/components/dashboard/DataTable';
import FormDialog from '@/components/dashboard/FormDialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
    TableActionMenu,
    TableActionMenuContent,
    TableActionMenuItem,
    TableActionMenuLabel,
    TableActionMenuSeparator,
    TableActionMenuTrigger,
} from '@/components/ui/table-action-menu';
import { useTranslation } from '@/contexts/LanguageContext';
import { useAppDate } from '@/lib/date';
import { formatNumber } from '@/lib/format';

interface PendingRow {
    id: number;
    title: string;
    slug: string;
    excerpt: string | null;
    updated_at: string;
    author: { id: number; username: string } | null;
    category: { id: number; name: string; slug: string } | null;
}

interface Props {
    rows: Paginator<PendingRow>;
}

function defaultScheduleValue(): string {
    const d = new Date(Date.now() + 24 * 60 * 60 * 1000);
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export default function ArticleModeration({ rows }: Props) {
    const { t } = useTranslation();
    const { formatDateTime } = useAppDate();
    const [scheduleTarget, setScheduleTarget] = useState<PendingRow | null>(null);
    const [rejectTarget, setRejectTarget] = useState<PendingRow | null>(null);
    const [scheduleAt, setScheduleAt] = useState(defaultScheduleValue());
    const [rejectNote, setRejectNote] = useState('');

    function approveNow(row: PendingRow) {
        router.post(`/dashboard/articles/${row.id}/approve`, {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(t('Article published')),
            onError: (errs) => toast.error((Object.values(errs)[0] as string) || t('Action failed')),
        });
    }

    function submitSchedule() {
        if (!scheduleTarget) return;
        router.post(
            `/dashboard/articles/${scheduleTarget.id}/approve`,
            { published_at: scheduleAt.replace('T', ' ') },
            {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success(t('Article scheduled'));
                    setScheduleTarget(null);
                },
                onError: (errs) => toast.error((Object.values(errs)[0] as string) || t('Action failed')),
            },
        );
    }

    function submitReject() {
        if (!rejectTarget) return;
        router.post(
            `/dashboard/articles/${rejectTarget.id}/reject`,
            { note: rejectNote },
            {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success(t('Article sent back'));
                    setRejectTarget(null);
                    setRejectNote('');
                },
                onError: (errs) => toast.error((Object.values(errs)[0] as string) || t('Action failed')),
            },
        );
    }

    const columns: Column<PendingRow>[] = [
        {
            key: 'title',
            label: t('Title'),
            cell: (row) => (
                <div className="flex flex-col">
                    <span className="font-medium">{row.title}</span>
                    {row.excerpt && (
                        <span className="text-xs text-muted-foreground line-clamp-1">{row.excerpt}</span>
                    )}
                </div>
            ),
        },
        {
            key: 'author',
            label: t('Author'),
            cell: (row) => (
                <span className="text-sm text-muted-foreground">{row.author?.username ?? '—'}</span>
            ),
        },
        {
            key: 'category',
            label: t('Category'),
            cell: (row) =>
                row.category ? (
                    <span className="text-sm">{row.category.name}</span>
                ) : (
                    <span className="text-sm text-muted-foreground">{t('Uncategorized')}</span>
                ),
        },
        {
            key: 'updated_at',
            label: t('Submitted'),
            cell: (row) => (
                <span className="text-sm text-muted-foreground">{formatDateTime(row.updated_at)}</span>
            ),
        },
    ];

    return (
        <DashboardLayout>
            <Head title={t('Article Review')} />
            <DashboardPageHeader
                title={t('Article Review')}
                subtitle={`${formatNumber(rows.total)} ${rows.total === 1 ? t('article awaiting review') : t('articles awaiting review')}`}
            />

            <DataTable
                rows={rows}
                columns={columns}
                searchPlaceholder={t('Search pending articles…')}
                rowActions={(row) => (
                    <div className="flex items-center justify-end gap-1">
                        <Button size="sm" variant="default" onClick={() => approveNow(row)}>
                            <Check className="h-4 w-4" />
                            {t('Approve')}
                        </Button>
                        <TableActionMenu>
                            <TableActionMenuTrigger />
                            <TableActionMenuContent>
                                <TableActionMenuLabel>{t('Actions')}</TableActionMenuLabel>
                                <TableActionMenuItem
                                    onClick={() => {
                                        setScheduleAt(defaultScheduleValue());
                                        setScheduleTarget(row);
                                    }}
                                >
                                    <CalendarClock className="h-4 w-4" />
                                    {t('Schedule…')}
                                </TableActionMenuItem>
                                <TableActionMenuItem
                                    onClick={() => window.open(`/dashboard/articles/${row.id}/preview`, '_blank')}
                                >
                                    <ExternalLink className="h-4 w-4" />
                                    {t('Preview')}
                                </TableActionMenuItem>
                                <TableActionMenuSeparator />
                                <TableActionMenuItem
                                    variant="destructive"
                                    onClick={() => {
                                        setRejectNote('');
                                        setRejectTarget(row);
                                    }}
                                >
                                    <X className="h-4 w-4" />
                                    {t('Reject')}
                                </TableActionMenuItem>
                            </TableActionMenuContent>
                        </TableActionMenu>
                    </div>
                )}
            />

            <FormDialog
                open={scheduleTarget !== null}
                onOpenChange={(open) => !open && setScheduleTarget(null)}
                title={t('Schedule publication')}
                description={t('The article goes live automatically at the chosen time.')}
                size="sm"
            >
                <div className="space-y-4">
                    <div className="space-y-1.5">
                        <Label htmlFor="mod-schedule">{t('Publish date & time')}</Label>
                        <Input
                            id="mod-schedule"
                            type="datetime-local"
                            value={scheduleAt}
                            onChange={(e) => setScheduleAt(e.target.value)}
                        />
                    </div>
                    <div className="flex justify-end gap-2">
                        <Button variant="outline" onClick={() => setScheduleTarget(null)}>
                            {t('Cancel')}
                        </Button>
                        <Button onClick={submitSchedule}>{t('Schedule')}</Button>
                    </div>
                </div>
            </FormDialog>

            <FormDialog
                open={rejectTarget !== null}
                onOpenChange={(open) => !open && setRejectTarget(null)}
                title={t('Send back for changes')}
                description={t('The author is notified with your note and the article returns to draft.')}
                size="sm"
            >
                <div className="space-y-4">
                    <div className="space-y-1.5">
                        <Label htmlFor="mod-note">{t('Note to author')}</Label>
                        <Textarea
                            id="mod-note"
                            value={rejectNote}
                            onChange={(e) => setRejectNote(e.target.value)}
                            rows={3}
                            placeholder={t('What needs to change before this can be published?')}
                        />
                    </div>
                    <div className="flex justify-end gap-2">
                        <Button variant="outline" onClick={() => setRejectTarget(null)}>
                            {t('Cancel')}
                        </Button>
                        <Button variant="destructive" onClick={submitReject}>
                            {t('Send back')}
                        </Button>
                    </div>
                </div>
            </FormDialog>
        </DashboardLayout>
    );
}
