import AppLayout from '@/layouts/app-layout';
import { Head, router } from '@inertiajs/react';
import Table from '@/components/Table';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { useState } from 'react';

interface ReportRow {
    id: number;
    user_name: string;
    email: string;
    question_id: number;
    question: string;
    type: string;
    details: string;
    status: string;
    created_at: string;
}

interface PaginatedReports {
    data: ReportRow[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
}

interface Props {
    reports: PaginatedReports;
}

const STATUS_OPTIONS = [
    'Unread',
    'Read',
    'Pending',
    'Reviewed',
    'Resolved',
];

const columns = [
    { label: 'User Name', key: 'user_name' as const, sortable: true },
    { label: 'Email', key: 'email' as const, sortable: true },
    { label: 'Question Id', key: 'question_id' as const, sortable: true },
    { label: 'Question', key: 'question' as const },
    { label: 'Type', key: 'type' as const, sortable: true },
    { label: 'Details', key: 'details' as const },
    { label: 'Status', key: 'status' as const, sortable: true },
];

export default function Index({ reports }: Props) {

    const queryParams = new URLSearchParams(window.location.search);
    const search = queryParams.get('search') || '';

    // 🔥 MODAL STATE
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [pendingStatus, setPendingStatus] = useState<string | null>(null);
    const [activeRowId, setActiveRowId] = useState<number | null>(null);

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

            <div className="m-5">
                <Card>
                    <CardHeader>
                        <h1 className="text-2xl font-semibold text-gray-800 dark:text-white">
                            Report Questions
                        </h1>
                    </CardHeader>

                    <CardContent>
                        <Table<ReportRow>
                            data={reports.data}
                            total={reports.total}
                            currentPage={reports.current_page}
                            rowsPerPage={reports.per_page}
                            columns={columns}
                            searchableKeys={[
                                'user_name',
                                'email',
                                'question_id',
                                'question',
                                'type',
                                'details',
                                'status',
                            ]}
                            renderCell={(key, value, row) => {

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

                                            {/* STATUS SELECT */}
                                            <select
                                                value={row.status}
                                                onChange={(e) => {
                                                    setPendingStatus(e.target.value);
                                                    setActiveRowId(row.id);
                                                    setConfirmOpen(true);
                                                }}
                                                className="
                                                    rounded-md border px-2 py-1 text-sm
                                                    bg-white dark:bg-gray-900
                                                    cursor-pointer
                                                    focus:outline-none focus:ring-2 focus:ring-blue-500
                                                "
                                            >
                                                {STATUS_OPTIONS.map((status) => (
                                                    <option key={status} value={status}>
                                                        {status}
                                                    </option>
                                                ))}
                                            </select>

                                            {/* STATUS BADGE */}
                                            <span
                                                className={`
                                                    text-xs px-2 py-1 rounded-full
                                                    ${
                                                        row.status === 'Resolved'
                                                            ? 'bg-green-100 text-green-700'
                                                            : row.status === 'Reviewed'
                                                            ? 'bg-blue-100 text-blue-700'
                                                            : row.status === 'Pending'
                                                            ? 'bg-yellow-100 text-yellow-700'
                                                            : row.status === 'Read'
                                                            ? 'bg-purple-100 text-purple-700'
                                                            : row.status === 'Unread'
                                                            ? 'bg-gray-200 text-gray-700'
                                                            : 'bg-gray-200 text-gray-700'
                                                    }
                                                `}
                                            >
                                                {row.status}
                                            </span>
                                        </div>
                                    );
                                }

                                if (key === 'details') {
                                    return value || 'N/A';
                                }

                                return value || 'N/A';
                            }}
                            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>

            {/* ✅ CUSTOM MODAL */}
            {confirmOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
                    <div className="w-[380px] rounded-lg bg-white dark:bg-gray-900 p-5 shadow-lg">

                        <h2 className="text-lg font-semibold text-gray-800 dark:text-white">
                            Confirm Status Change
                        </h2>

                        <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                            Are you sure you want to change status to
                            <span className="font-semibold"> "{pendingStatus}"</span>?
                        </p>

                        <div className="mt-5 flex justify-end gap-3">

                            <button
                                onClick={() => {
                                    setConfirmOpen(false);
                                    setPendingStatus(null);
                                    setActiveRowId(null);
                                }}
                                className="px-3 py-1.5 rounded-md border text-sm hover:bg-gray-100 dark:hover:bg-gray-800"
                            >
                                Cancel
                            </button>

                            <button
                                onClick={() => {
                                    if (!activeRowId || !pendingStatus) return;

                                    router.post(
                                        `/report-question/${activeRowId}/status-update`,
                                        { status: pendingStatus },
                                        {
                                            preserveScroll: true,
                                            onSuccess: () => {
                                                router.reload({ only: ['reports'] });
                                            },
                                        }
                                    );

                                    setConfirmOpen(false);
                                    setPendingStatus(null);
                                    setActiveRowId(null);
                                }}
                                className="px-3 py-1.5 rounded-md bg-blue-600 text-white text-sm hover:bg-blue-700"
                            >
                                Confirm
                            </button>

                        </div>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}