"use client";

import { useState } from "react";

import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import IconButton from "@mui/material/IconButton";
import TableRow from "@mui/material/TableRow";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import CloseIcon from "@mui/icons-material/Close";
import MoreVertIcon from "@mui/icons-material/MoreVert";

import type { DecisionRow } from "../progress-report-view-details.types";
import {
    BodyCell,
    SectionTable,
    type TableColumn,
} from "../table/section-table";

const decisionColumns: TableColumn[] = [
    { label: "N.O", width: 70 },
    { label: "PSWG Secretariat", width: 260 },
    { label: "Issue", width: 320 },
    { label: "Category of RGC Decision", width: 260 },
    { label: "Meeting Date", width: 170 },
    { label: "RGC Decision", width: 520 },
    { label: "Status", width: 150 },
    { label: "Progress Solution", width: 300 },
    { label: "Solution Indicators", width: 260 },
    { label: "Challenge", width: 300 },
    { label: "Request", width: 260 },
    { label: "Action", width: 90 },
];

type ProgressReportDecisionsSectionProps = {
    rows: DecisionRow[];
};

const statusColorMap: Record<DecisionRow["status"], string> = {
    Solved: "#16a34a",
    "In Progress": "#f59e0b",
    "Not Addressed": "#ef4444",
};

function StatusChip({ status }: { status: DecisionRow["status"] }) {
    const theme = useTheme();

    const color = statusColorMap[status];

    return (
        <Chip
            label={status}
            size="small"
            sx={{
                height: 22,
                minWidth: 74,
                borderRadius: "999px",
                bgcolor: alpha(color, theme.palette.mode === "dark" ? 0.18 : 0.12),
                color,
                border: `1px solid ${alpha(color, 0.22)}`,
                fontSize: 11,
                fontWeight: 600,
            }}
        />
    );
}

function RequiredLabel({ children }: { children: string }) {
    return (
        <Typography sx={{ mb: 0.8, fontSize: 12, fontWeight: 500, color: "#344054" }}>
            {children} <Box component="span" sx={{ color: "#ef4444" }}>*</Box>
        </Typography>
    );
}

function FieldBox({ label, value }: { label: string; value: string }) {
    return (
        <Box>
            <RequiredLabel>{label}</RequiredLabel>
            <Box
                sx={{
                    minHeight: 39,
                    px: 1.5,
                    display: "flex",
                    alignItems: "center",
                    border: "1px solid #E5E7EB",
                    borderRadius: "6px",
                    bgcolor: "#fff",
                    fontSize: 12,
                    color: "#111827",
                }}
            >
                {value || "No data"}
            </Box>
        </Box>
    );
}

function TextBox({ label, value }: { label: string; value: string }) {
    return (
        <Box>
            <RequiredLabel>{label}</RequiredLabel>
            <Box
                sx={{
                    minHeight: 90,
                    p: 1.5,
                    border: "1px solid #E5E7EB",
                    borderRadius: "6px",
                    bgcolor: "#fff",
                    fontSize: 12,
                    lineHeight: 1.8,
                    color: "#111827",
                }}
            >
                {value || "No data"}
            </Box>
        </Box>
    );
}

function IssueDetailPopup({
    open,
    row,
    onClose,
}: {
    open: boolean;
    row: DecisionRow | null;
    onClose: () => void;
}) {
    if (!row) return null;

    return (
        <Dialog
            open={open}
            onClose={onClose}
            maxWidth={false}
            sx={{
                "& .MuiDialog-container": {
                    alignItems: "flex-start",
                    justifyContent: "flex-end",
                },
            }}
            slotProps={{
                paper: {
                    sx: {
                        mt: 1.5,
                        mr: 1.5,
                        width: 620,
                        maxWidth: "calc(100vw - 24px)",
                        height: "calc(100vh - 24px)",
                        maxHeight: "calc(100vh - 24px)",
                        borderRadius: "12px",
                        overflow: "hidden",
                        m: 0,
                    },
                },
                backdrop: {
                    sx: {
                        bgcolor: "rgba(15, 23, 42, 0.48)",
                    },
                },
            }}
        >
            <Box
                sx={{
                    height: 54,
                    mt: 1.8,
                    px: 2,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    borderBottom: "1px solid #EEF2F6",
                }}
            >
                <Typography sx={{ fontSize: 16, fontWeight: 700, color: "#111827" }}>
                    Issue Detail
                </Typography>

                <IconButton size="small" onClick={onClose}>
                    <CloseIcon fontSize="small" />
                </IconButton>
            </Box>

            <DialogContent sx={{ p: 2, bgcolor: "#fff" }}>
                <Box sx={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 2, mb: 2 }}>
                    <FieldBox label="Ministry" value="MAFF" />
                    <FieldBox label="PSWG Secretariat" value={row.secretariat} />

                    <Box>
                        <RequiredLabel>Status</RequiredLabel>
                        <StatusChip status={row.status} />
                    </Box>
                </Box>

                <Box sx={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 2, mb: 2 }}>
                    <FieldBox label="Issue Resolution Date" value={row.meetingDate} />
                    <FieldBox label="Source of Verification/ Reference" value="Reference A - Completed" />
                    <FieldBox label="Link to the Evidence/Reference" value="Reference B - Completed" />
                </Box>

                <Box sx={{ mb: 2 }}>
                    <FieldBox label="Issue Category" value={row.category} />
                </Box>

                <Box sx={{ display: "grid", gap: 2 }}>
                    <TextBox label="RGC Decision" value={row.decision} />
                    <TextBox label="Progress Solution" value={row.progressSolution} />
                    <TextBox label="Solution Indicators" value={row.solutionIndicators} />
                    <TextBox label="Challenge" value={row.challenge} />
                    <TextBox label="Request" value={row.request} />
                </Box>

                {/* Additional Agencies Fields */}
                <Box sx={{ mt: 3 }}>
                    <Box sx={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 2 }}>
                        <FieldBox label="Second Agency" value="No data" />
                        <FieldBox label="Third Agency" value="No data" />
                        <FieldBox label="Fourth Agency" value="No data" />
                        <FieldBox label="Fifth Agency" value="No data" />
                    </Box>
                </Box>
            </DialogContent>
        </Dialog>
    );
}

export function ProgressReportDecisionsSection({
    rows,
}: ProgressReportDecisionsSectionProps) {
    const [selectedRow, setSelectedRow] = useState<DecisionRow | null>(null);

    return (
        <Box sx={{ minWidth: 0, width: "100%" }}>
            <Typography
                sx={{
                    fontSize: 16,
                    fontWeight: 600,
                    mb: 1.5,
                    color: "text.primary",
                }}
            >
                List of RGC Decision
            </Typography>

            <SectionTable columns={decisionColumns} minWidth={2960}>
                {rows.map((row) => (
                    <TableRow key={row.no}>
                        <BodyCell width={70}>{row.no}</BodyCell>
                        <BodyCell width={260}>{row.secretariat}</BodyCell>
                        <BodyCell width={320}>{row.issue}</BodyCell>
                        <BodyCell width={260}>{row.category}</BodyCell>
                        <BodyCell width={170}>{row.meetingDate}</BodyCell>
                        <BodyCell width={520}>{row.decision}</BodyCell>

                        <BodyCell width={150}>
                            <StatusChip status={row.status} />
                        </BodyCell>

                        <BodyCell width={300}>{row.progressSolution}</BodyCell>
                        <BodyCell width={260}>{row.solutionIndicators}</BodyCell>
                        <BodyCell width={300}>{row.challenge}</BodyCell>
                        <BodyCell width={260}>{row.request}</BodyCell>

                        <BodyCell width={90}>
                            <Box sx={{ display: "flex", justifyContent: "center" }}>
                                <Tooltip title="View detail">
                                    <IconButton
                                        size="small"
                                        onClick={() => setSelectedRow(row)}
                                        sx={{
                                            width: 30,
                                            height: 30,
                                            color: "#8A98A8",
                                            "&:hover": {
                                                bgcolor: "#EAF4FF",
                                                color: "#1D69B4",
                                            },
                                        }}
                                    >
                                        <MoreVertIcon fontSize="small" />
                                    </IconButton>
                                </Tooltip>
                            </Box>
                        </BodyCell>
                    </TableRow>
                ))}
            </SectionTable>

            <IssueDetailPopup
                open={Boolean(selectedRow)}
                row={selectedRow}
                onClose={() => setSelectedRow(null)}
            />
        </Box>
    );
}
