import AppLayout from '@/layouts/app-layout';
import { Head, router } from '@inertiajs/react';
import Table from '@/components/Table';
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    CardDescription
} from "@/components/ui/card"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { format } from 'date-fns';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { useState } from 'react';
import { EyeIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface SurveyQuestionOptionStats {
    id: number;
    option: string;
    answers_count: number;
}

interface SurveyQuestionStats {
    id: number;
    question: string;
    type: string;
    options: SurveyQuestionOptionStats[];
}

interface UserSurveyAnswer {
    id: number;
    question_id: number;
    option_id: number | null;
    text_answer: string | null;
    created_at: string;
    question?: {
        question: string;
    };
    option?: {
        option: string;
    };
}

interface Respondent {
    id: number;
    name: string;
    email: string;
    survey_answers: UserSurveyAnswer[];
}

interface PaginatedRespondents {
    data: Respondent[];
    current_page: number;
    per_page: number;
    total: number;
}

interface Props {
    survey: any;
    stats: SurveyQuestionStats[];
    users: PaginatedRespondents;
}

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8', '#ffc658'];

const columns = [
    { label: 'User Name', key: 'name', sortable: true },
    { label: 'Email', key: 'email', sortable: true },
    { label: 'Last Submitted Answer At', key: 'last_submitted' },
    { label: 'Actions', key: 'actions' },
];

export default function Show({ survey, stats, users }: Props) {
    const queryParams = new URLSearchParams(window.location.search);
    const search = queryParams.get('search') || '';
    const surveyAnswerId = survey?.id;

    const [selectedUser, setSelectedUser] = useState<Respondent | null>(null);

    // Build the question paper view: group user answers by question, show all options
    const buildQuestionPaper = () => {
        if (!selectedUser) return [];

        const selectedByQuestion: Record<number, Set<number>> = {};
        const textAnswerByQuestion: Record<number, string | null> = {};

        selectedUser.survey_answers?.forEach((ans) => {
            if (!selectedByQuestion[ans.question_id]) {
                selectedByQuestion[ans.question_id] = new Set();
            }
            if (ans.option_id !== null) {
                selectedByQuestion[ans.question_id].add(ans.option_id);
            }
            if (ans.text_answer !== undefined) {
                textAnswerByQuestion[ans.question_id] = ans.text_answer;
            }
        });

        // Map stats (all questions + all options) and mark which are selected
        return stats.map((question) => ({
            id: question.id,
            question: question.question,
            type: question.type,
            options: question.options.map((opt) => ({
                id: opt.id,
                option: opt.option,
                isSelected: selectedByQuestion[question.id]?.has(opt.id) ?? false,
            })),
            textAnswer: textAnswerByQuestion[question.id] ?? null,
            hasAnswer: !!selectedByQuestion[question.id] || textAnswerByQuestion[question.id] !== undefined,
        }));
    };

    return (
        <AppLayout breadcrumbs={[{ title: 'Survey Answers Lists', href: route('survey_answer.index') }, { title: survey.title, href: surveyAnswerId ? route('survey_answer.show', { survey_answer: surveyAnswerId }) : route('survey_answer.index') }]}>
            <Head title={`Survey Analytics - ${survey.title}`} />

            <div className="m-5 flex flex-col gap-5">

                {/* Statistics / Pie Charts Section */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {stats.filter(stat => stat.type !== 'text').map((stat, idx) => {
                        const pieData = stat.options.map((opt) => ({
                            name: opt.option,
                            value: opt.answers_count,
                        }));
                        const hasData = pieData.some((d) => d.value > 0);

                        return (
                            <Card key={stat.id}>
                                <CardHeader>
                                    <CardTitle className="text-lg leading-tight">{stat.question}</CardTitle>
                                    <CardDescription>Responses overview</CardDescription>
                                </CardHeader>
                                <CardContent className="h-[250px] w-full pb-4">
                                    {hasData ? (
                                        <ResponsiveContainer width="100%" height="100%">
                                            <PieChart>
                                                <Pie
                                                    data={pieData}
                                                    cx="50%"
                                                    cy="50%"
                                                    innerRadius={40}
                                                    outerRadius={80}
                                                    paddingAngle={5}
                                                    dataKey="value"
                                                >
                                                    {pieData.map((entry, index) => (
                                                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                                    ))}
                                                </Pie>
                                                <Tooltip />
                                                <Legend wrapperStyle={{ fontSize: '12px' }} />
                                            </PieChart>
                                        </ResponsiveContainer>
                                    ) : (
                                        <div className="h-full flex items-center justify-center text-sm text-gray-500">
                                            No answers submitted yet.
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        );
                    })}
                </div>

                {/* Respondents Table Section */}
                <Card>
                    <CardHeader>
                        <div className="flex items-center justify-between">
                            <h2 className="text-xl font-semibold text-gray-800 dark:text-white">
                                Respondents Data for {survey.title}
                            </h2>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table<Respondent>
                            data={users.data}
                            total={users.total}
                            currentPage={users.current_page}
                            rowsPerPage={users.per_page}
                            columns={columns}
                            searchableKeys={['name', 'email']}
                            renderCell={(key, value, row) => {
                                if (key === 'last_submitted') {
                                    // get newest answer
                                    if (row.survey_answers && row.survey_answers.length > 0) {
                                        const newest = [...row.survey_answers].sort((a,b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
                                        return format(new Date(newest.created_at), 'PPP p');
                                    }
                                    return 'N/A';
                                }

                                if (key === 'actions') {
                                    return (
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            className="flex items-center gap-2"
                                            onClick={() => setSelectedUser(row)}
                                        >
                                            <EyeIcon size={16} /> View Answers
                                        </Button>
                                    );
                                }

                                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>

            {/* Modal for Question Paper View */}
            <Dialog open={!!selectedUser} onOpenChange={(open) => !open && setSelectedUser(null)}>
                <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Survey Answers: {selectedUser?.name}</DialogTitle>
                        <DialogDescription>Email: {selectedUser?.email}</DialogDescription>
                    </DialogHeader>

                    <div className="mt-4 flex flex-col gap-6">
                        {(() => {
                            const paper = buildQuestionPaper();
                            if (paper.length === 0) {
                                return <p className="text-gray-500">No detailed answers available.</p>;
                            }
                            return paper.map((q, i) => (
                                <div key={q.id} className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-100 dark:border-gray-700">
                                    <div className="text-sm font-semibold mb-3 text-gray-800 dark:text-gray-200">
                                        Q{i + 1}. {q.question}
                                        <span className="ml-2 text-xs font-normal text-gray-400">
                                            ({q.type === 'multiple_choice' ? 'Multiple Choice' : q.type === 'single_choice' ? 'Single Choice' : 'Text Answer'})
                                        </span>
                                    </div>
                                    <div className="flex flex-col gap-2 pl-2">
                                        {q.type === 'text' ? (
                                            q.hasAnswer ? (
                                                <div className="bg-white dark:bg-gray-700/30 border border-gray-200 dark:border-gray-600 px-3 py-2 rounded-md text-sm text-gray-800 dark:text-gray-200">
                                                    {q.textAnswer || <span className="text-gray-400 italic">No text provided</span>}
                                                </div>
                                            ) : null
                                        ) : (
                                            q.options.map((opt) => (
                                                <div
                                                    key={opt.id}
                                                    className={`flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors ${
                                                        opt.isSelected
                                                            ? 'bg-indigo-100 dark:bg-indigo-900/40 border border-indigo-300 dark:border-indigo-600'
                                                            : 'bg-white dark:bg-gray-700/30 border border-gray-200 dark:border-gray-600'
                                                    }`}
                                                >
                                                    <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
                                                        opt.isSelected
                                                            ? 'border-indigo-500 bg-indigo-500'
                                                            : 'border-gray-300 dark:border-gray-500'
                                                    }`}>
                                                        {opt.isSelected && (
                                                            <svg className="w-2.5 h-2.5 text-white" fill="currentColor" viewBox="0 0 20 20">
                                                                <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                                            </svg>
                                                        )}
                                                    </span>
                                                    <span className={opt.isSelected ? 'font-bold text-indigo-800 dark:text-indigo-200' : 'text-gray-600 dark:text-gray-300'}>
                                                        {opt.option}
                                                    </span>
                                                </div>
                                            ))
                                        )}
                                        {!q.hasAnswer && (
                                            <p className="text-xs text-gray-400 italic mt-1">Not answered</p>
                                        )}
                                    </div>
                                </div>
                            ));
                        })()}
                    </div>
                </DialogContent>
            </Dialog>

        </AppLayout>
    );
}
