import Table from '@/components/Table';
import { buttonVariants } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import { Head, Link, router } from '@inertiajs/react';
import { Edit, Settings, Trash } from 'lucide-react';
import { useRef, useState } from 'react';
import { toast } from 'sonner';

interface QuestionRow {
    id: number;
    question: string;
    type: string;
    status: string;
    explanation: string | null;
    sub_topic: {
        id: number;
        name: string;
        topic: {
            id: number;
            name: string;
        } | null;
    } | null;
    options: { id: number; option: string | null; is_correct: boolean }[];
    question_rules: { id: number }[];
    created_at: string;
    updated_at: string;
    actions?: string;
}

interface SubTopicItem {
    id: number;
    name: string;
    topic: {
        id: number;
        name: string;
    } | null;
}

interface PaginatedQuestions {
    data: QuestionRow[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: {
        url: string | null;
        label: string;
        active: boolean;
    }[];
}

interface Props {
    questions: PaginatedQuestions;
    subTopics: SubTopicItem[];
}

const columns = [
    { label: 'Question', key: 'question' as const, sortable: true },
    { label: 'Answer Choice A', key: 'answer_choice_a' as const },
    { label: 'Answer Choice B', key: 'answer_choice_b' as const },
    { label: 'Answer Choice C', key: 'answer_choice_c' as const },
    { label: 'Answer Choice D', key: 'answer_choice_d' as const },
    { label: 'Answer Choice E', key: 'answer_choice_e' as const },
    { label: 'Correct Answer', key: 'correct_answer' as const },
    { label: 'Answer Explanation', key: 'answer_explanation' as const },
    { label: 'Topic', key: 'topic' as const },
    { label: 'Sub Topic', key: 'sub_topic' as const },
    { label: 'Status', key: 'status' as const, sortable: true },
    { label: 'Actions', key: 'actions' as const },
];

export default function Index({ questions, subTopics }: Props) {
    const queryParams = new URLSearchParams(window.location.search);
    const search = queryParams.get('search') || '';
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const [csvFile, setCsvFile] = useState<File | null>(null);

    const deleteQuestion = (id: number) => {
        if (confirm('Are you sure you want to delete this question?')) {
            router.delete(route('question.destroy', { question: id }), {
                onSuccess: () => toast.success('Question deleted successfully!'),
                onError: () => toast.error('Failed to delete the question.'),
            });
        }
    };

    const importCsv = () => {
        if (!csvFile) {
            toast.error('Please choose a CSV file first.');
            return;
        }

        router.post(
            route('question.importCsv'),
            {
                csv_file: csvFile,
            },
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: () => {
                    toast.success('CSV import finished.');
                    setCsvFile(null);
                    if (fileInputRef.current) {
                        fileInputRef.current.value = '';
                    }
                },
                onError: () => toast.error('CSV import failed. Please check your file format.'),
            },
        );
    };

    const getOptionLabel = (row: QuestionRow, optionIndex: number) => {
        return row.options?.[optionIndex]?.option ?? '—';
    };

    const getCorrectAnswerLabel = (row: QuestionRow) => {
        const letters = ['A', 'B', 'C', 'D', 'E'];
        const selected = (row.options ?? [])
            .slice(0, 5)
            .map((opt, idx) => (opt.is_correct ? letters[idx] : null))
            .filter(Boolean) as string[];

        return selected.length ? selected.join(', ') : '—';
    };

    return (
        <AppLayout breadcrumbs={[{ title: 'Questions', href: '/question' }]}>
            <Head title="Questions List" />

            <div className="m-5">
                <Card>
                    <CardHeader>
                        <div className="flex items-center justify-between gap-3">
                            <h1 className="text-2xl font-semibold text-gray-800 dark:text-white">Questions List</h1>
                            <div className="flex items-center gap-2">
                                <Link className={buttonVariants({ variant: 'outline' })} href={route('question-rules.edit')}>
                                    <Settings />
                                    Question Rules
                                </Link>
                                <a className={buttonVariants({ variant: 'outline' })} href={route('question.exportCsv')}>
                                    Export CSV
                                </a>
                                <button
                                    type="button"
                                    className={buttonVariants({ variant: 'outline' })}
                                    onClick={() => fileInputRef.current?.click()}
                                >
                                    Upload CSV
                                </button>
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept=".csv,.txt"
                                    className="hidden"
                                    onChange={(e) => {
                                        const file = e.target.files?.[0] ?? null;
                                        if (file) {
                                            setCsvFile(file);
                                            // Auto-submit immediately after file selection
                                            router.post(
                                                route('question.importCsv'),
                                                { csv_file: file },
                                                {
                                                    forceFormData: true,
                                                    preserveScroll: true,
                                                    onSuccess: () => {
                                                        toast.success('CSV import finished.');
                                                        setCsvFile(null);
                                                        if (fileInputRef.current) {
                                                            fileInputRef.current.value = '';
                                                        }
                                                    },
                                                    onError: () => toast.error('CSV import failed. Please check your file format.'),
                                                },
                                            );
                                        }
                                    }}
                                />
                                <Link className={buttonVariants({ variant: 'default' })} href={route('question.create')}>
                                    Create Question
                                </Link>
                            </div>
                        </div>
                    </CardHeader>

                    <CardContent>
                        <Table<QuestionRow>
                            data={questions.data}
                            total={questions.total}
                            currentPage={questions.current_page}
                            rowsPerPage={questions.per_page}
                            columns={columns}
                            searchableKeys={['question']}
                            renderCell={(key, value, row) => {
                                if (key === 'topic') return row.sub_topic?.topic?.name ?? '—';
                                if (key === 'sub_topic') return row.sub_topic?.name ?? '—';
                                if (key === 'answer_choice_a') return getOptionLabel(row, 0);
                                if (key === 'answer_choice_b') return getOptionLabel(row, 1);
                                if (key === 'answer_choice_c') return getOptionLabel(row, 2);
                                if (key === 'answer_choice_d') return getOptionLabel(row, 3);
                                if (key === 'answer_choice_e') return getOptionLabel(row, 4);
                                if (key === 'correct_answer') return getCorrectAnswerLabel(row);
                                if (key === 'answer_explanation') {
                                    return row.explanation ? (
                                        <div
                                            className="prose prose-sm dark:prose-invert max-h-32 max-w-xs overflow-hidden overflow-y-auto text-sm leading-6 break-words whitespace-normal"
                                            dangerouslySetInnerHTML={{ __html: row.explanation }}
                                        />
                                    ) : (
                                        '—'
                                    );
                                }

                                if (key === 'status') {
                                    return (
                                        <button
                                            type="button"
                                            className={`cursor-pointer rounded-full px-3 py-1 text-sm font-medium transition-colors duration-200 ${
                                                row.status === 'Active'
                                                    ? 'bg-green-100 text-green-800 hover:bg-green-200'
                                                    : 'bg-red-100 text-red-800 hover:bg-red-200'
                                            }`}
                                            onClick={() => {
                                                router.patch(
                                                    route('question.toggleStatus', { question: row.id }),
                                                    {},
                                                    {
                                                        preserveScroll: true,
                                                        onSuccess: () =>
                                                            toast.success(
                                                                `Question status changed to ${row.status === 'Active' ? 'Inactive' : 'Active'}`,
                                                            ),
                                                        onError: () => toast.error('Failed to update status.'),
                                                    },
                                                );
                                            }}
                                        >
                                            {row.status}
                                        </button>
                                    );
                                }

                                if (key === 'actions') {
                                    return (
                                        <div className="flex gap-2">
                                            <Link
                                                href={route('question.edit', row.id)}
                                                className={buttonVariants({ variant: 'secondary', size: 'icon' })}
                                            >
                                                <Edit className="h-4 w-4 text-blue-500" />
                                            </Link>
                                            <button
                                                className={buttonVariants({ variant: 'secondary', size: 'icon' })}
                                                onClick={() => deleteQuestion(row.id)}
                                            >
                                                <Trash className="h-4 w-4 text-red-500" />
                                            </button>
                                        </div>
                                    );
                                }

                                return value;
                            }}
                            onPageChange={(page) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                router.get(
                                    window.location.pathname,
                                    {
                                        ...params,
                                        page,
                                    },
                                    { preserveState: true, replace: true },
                                );
                            }}
                            onPerPageChange={(perPage) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                router.get(
                                    window.location.pathname,
                                    {
                                        ...params,
                                        page: 1,
                                        per_page: perPage,
                                    },
                                    { preserveState: true, replace: true },
                                );
                            }}
                            onSearchChange={(searchVal) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                if (searchVal) {
                                    params.search = searchVal;
                                } else {
                                    delete params.search;
                                }
                                router.get(
                                    window.location.pathname,
                                    {
                                        ...params,
                                        page: 1,
                                    },
                                    { preserveState: true, replace: true },
                                );
                            }}
                            searchValue={search}
                        />
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
