import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem, PaginatedSurveyQuestions, SurveyQuestion } from '@/types';
import { Head, router, Link } from '@inertiajs/react';
import { toast } from 'sonner';
import Table from '@/components/Table';
import { Button, buttonVariants } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardHeader,
} from "@/components/ui/card"

interface Props {
    survey: any;
    questions: PaginatedSurveyQuestions;
}

const columns = [
    { label: 'Question', key: 'question', sortable: true },
    { label: 'Type', key: 'type', sortable: true },
    { label: 'Options Count', key: 'options_count' },
    { label: 'Status', key: 'status', sortable: true },
    { label: 'Actions', key: 'actions' },
];

export default function Index({ survey, questions }: Props) {
    const queryParams = new URLSearchParams(window.location.search);
    const search = queryParams.get('search') || '';

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

    const toggleStatus = (id: number) => {
        router.patch(route('survey.survey_question.updateStatus', { survey: survey.id, surveyQuestion: id }), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success('Status updated!'),
            onError: () => toast.error('Failed to update status.'),
        });
    };

    return (
        <AppLayout breadcrumbs={[
            { title: 'Surveys', href: '/survey' },
            { title: 'Survey Questions', href: route('survey.survey_question.index', survey.id) }
        ]}>
            <Head title="Survey Questions List" />

            <div className="m-5">
                <Card>
                    <CardHeader>
                        <div className="flex items-center justify-between">
                            <h1 className="text-2xl font-semibold text-gray-800 dark:text-white">
                                Questions for Survey: {survey.title}
                            </h1>
                            <Link className={(buttonVariants({ variant: 'default', className: 'ml-auto' }))} href={route('survey.survey_question.create', survey.id)}>
                                Create New Question
                            </Link>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table<SurveyQuestion>
                            data={questions.data}
                            total={questions.total}
                            currentPage={questions.current_page}
                            rowsPerPage={questions.per_page}
                            columns={columns}
                            searchableKeys={['question']}
                            renderCell={(key, value, row) => {

                                if (key === 'options_count') {
                                    return row.options ? row.options.length : 0;
                                }

                                if (key === 'status') {
                                    return (
                                        <button
                                            onClick={() => toggleStatus(row.id)}
                                            className={`px-3 py-1 rounded-full text-sm font-medium ${
                                                row.status === 'Active'
                                                    ? 'bg-green-100 text-green-800 hover:bg-green-200'
                                                    : 'bg-red-100 text-red-800 hover:bg-red-200'
                                            } transition-colors`}
                                        >
                                            {row.status}
                                        </button>
                                    );
                                }

                                if (key === 'actions') {
                                    return (
                                        <div className="flex gap-2">

                                            <Link className={(buttonVariants({ variant: 'default' }))} href={route('survey.survey_question.edit', { survey: survey.id, survey_question: row.id })}>
                                                Edit
                                            </Link>

                                            <button
                                                className={(buttonVariants({ variant: 'default' }))}
                                                onClick={() => deleteQuestion(row.id)}
                                            >
                                                Delete
                                            </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>
    );
}
