import * as React from 'react';
import { router } from '@inertiajs/react';
import AdminLayout from '../layout';
import {
    questionsApi,
    type Question,
} from '@/features/admin/questions/services/api';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import {
    Table,
    TableHead,
    TableBody,
    TableRow,
    TableHeaderCell,
    TableCell,
    TableEmpty,
} from '@/components/ui/table';
import { Pagination } from '@/components/ui/pagination';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Spinner } from '@/components/ui/spinner';
import { toast } from '@/components/ui/sonner';
import { debounce } from '@/lib/utils';

export default function QuestionsIndex() {
    const [questions, setQuestions] = React.useState<Question[]>([]);
    const [meta, setMeta] = React.useState({
        page: 1,
        lastPage: 1,
        total: 0,
        perPage: 15,
    });
    const [search, setSearch] = React.useState('');
    const [activeFilter, setActiveFilter] = React.useState<
        '' | 'true' | 'false'
    >('');
    const [loading, setLoading] = React.useState(true);
    const [pendingDelete, setPendingDelete] = React.useState<Question | null>(
        null,
    );
    const [deleting, setDeleting] = React.useState(false);
    const [togglingId, setTogglingId] = React.useState<number | null>(null);

    const load = React.useCallback(
        (page: number) => {
            setLoading(true);
            questionsApi
                .index({
                    page,
                    search: search || undefined,
                    active:
                        activeFilter === ''
                            ? undefined
                            : activeFilter === 'true',
                })
                .then((res) => {
                    setQuestions(res.data || []);
                    setMeta({
                        page: res.meta?.current_page || 1,
                        lastPage: res.meta?.last_page || 1,
                        total: res.meta?.total || 0,
                        perPage: res.meta?.per_page || 15,
                    });
                })
                .catch(() => toast.error('Failed to load questions.'))
                .finally(() => setLoading(false));
        },
        [search, activeFilter],
    );

    React.useEffect(() => load(1), [load]);

    const debouncedSearch = React.useMemo(
        () => debounce((value: string) => setSearch(value), 300),
        [],
    );

    async function handleToggle(question: Question) {
        setTogglingId(question.id);
        try {
            await questionsApi.toggleActive(question.id);
            load(meta.page);
        } catch {
            toast.error('Failed to update question status.');
        } finally {
            setTogglingId(null);
        }
    }

    async function handleDelete() {
        if (!pendingDelete) return;
        setDeleting(true);
        try {
            await questionsApi.delete(pendingDelete.id);
            toast.success('Question deleted.');
            setPendingDelete(null);
            load(meta.page);
        } catch {
            toast.error('Failed to delete question.');
        } finally {
            setDeleting(false);
        }
    }

    return (
        <AdminLayout title="Questions">
            <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                <div className="flex flex-wrap gap-3">
                    <Input
                        placeholder="Search question text"
                        className="w-full sm:w-64"
                        aria-label="Search questions"
                        onChange={(e) => debouncedSearch(e.target.value)}
                    />
                    <Select
                        className="w-full sm:w-40"
                        placeholder="All statuses"
                        aria-label="Filter by status"
                        options={[
                            { value: 'true', label: 'Active' },
                            { value: 'false', label: 'Inactive' },
                        ]}
                        value={activeFilter}
                        onChange={(e) =>
                            setActiveFilter(
                                e.target.value as '' | 'true' | 'false',
                            )
                        }
                    />
                </div>
                <div className="flex w-full gap-2 sm:w-auto">
                    <Button
                        variant="outline"
                        className="flex-1 sm:flex-none"
                        onClick={() => router.visit('/admin/questions/import')}
                    >
                        Import
                    </Button>
                    <Button
                        className="flex-1 sm:flex-none"
                        onClick={() => router.visit('/admin/questions/create')}
                    >
                        Add question
                    </Button>
                </div>
            </div>

            <Card>
                <Table>
                    <TableHead>
                        <tr>
                            <TableHeaderCell>Question</TableHeaderCell>
                            <TableHeaderCell>Correct</TableHeaderCell>
                            <TableHeaderCell>Status</TableHeaderCell>
                            <TableHeaderCell className="text-right">
                                Actions
                            </TableHeaderCell>
                        </tr>
                    </TableHead>
                    <TableBody>
                        {loading ? (
                            <tr>
                                <TableCell colSpan={4}>
                                    <div className="flex justify-center py-10">
                                        <Spinner className="h-5 w-5 text-(--color-accent)" />
                                    </div>
                                </TableCell>
                            </tr>
                        ) : questions.length === 0 ? (
                            <TableEmpty
                                colSpan={4}
                                message="No questions found."
                            />
                        ) : (
                            questions.map((q) => (
                                <TableRow key={q.id}>
                                    <TableCell
                                        className="max-w-md truncate font-medium"
                                        title={q.text}
                                    >
                                        {q.text}
                                    </TableCell>
                                    <TableCell>
                                        <Badge tone="accent">
                                            {q.correct_option}
                                        </Badge>
                                    </TableCell>
                                    <TableCell>
                                        <button
                                            type="button"
                                            onClick={() => handleToggle(q)}
                                            disabled={togglingId === q.id}
                                            aria-label={`Toggle status for question ${q.id}`}
                                            className="rounded focus-visible:ring-2 focus-visible:ring-(--color-accent) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-bg)"
                                        >
                                            <Badge
                                                tone={
                                                    q.active
                                                        ? 'success'
                                                        : 'neutral'
                                                }
                                            >
                                                {togglingId === q.id
                                                    ? '…'
                                                    : q.active
                                                      ? 'Active'
                                                      : 'Inactive'}
                                            </Badge>
                                        </button>
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <div className="inline-flex gap-2">
                                            <Button
                                                variant="secondary"
                                                size="sm"
                                                onClick={() =>
                                                    router.visit(
                                                        `/admin/questions/${q.id}/edit`,
                                                    )
                                                }
                                            >
                                                Edit
                                            </Button>
                                            <Button
                                                variant="danger-outline"
                                                size="sm"
                                                onClick={() =>
                                                    setPendingDelete(q)
                                                }
                                            >
                                                Delete
                                            </Button>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
                <Pagination
                    page={meta.page}
                    lastPage={meta.lastPage}
                    total={meta.total}
                    perPage={meta.perPage}
                    onPageChange={load}
                />
            </Card>

            <ConfirmDialog
                open={!!pendingDelete}
                title="Delete question"
                description="This will permanently remove this question from the quiz bank."
                confirmLabel="Delete"
                loading={deleting}
                onConfirm={handleDelete}
                onCancel={() => setPendingDelete(null)}
            />
        </AdminLayout>
    );
}
