import * as React from "react";
import type { FormElementProps, FormElementRegistration } from "@vertigis/workflow";
import Box, { BoxProps } from "@vertigis/web/ui/Box";
import Table, { TableProps } from "@vertigis/web/ui/Table";
import TableBody from "@vertigis/web/ui/TableBody";
import TableCell, { TableCellProps } from "@vertigis/web/ui/TableCell";
import TableHead from "@vertigis/web/ui/TableHead";
import TableRow from "@vertigis/web/ui/TableRow";
import Radio from "@vertigis/web/ui/Radio";
import RadioGroup from "@vertigis/web/ui/RadioGroup";
import FormControlLabel from "@vertigis/web/ui/FormControlLabel";
import Tooltip from "@mui/material/Tooltip";

/** Interface for table columns */
interface Column {
    name: string; // Used for value
    alias?: string; // Used for display
    align?: TableCellProps["align"];
    weight?: number;
    tooltip?: string;
}

/** Interface for row headers */
interface Row {
    name: string; // Used for value
    alias?: string; // Used for display
    tooltip?: string;
    align?: TableCellProps["align"];
}

type SettableBoxProps = Pick<BoxProps, "maxHeight" | "maxWidth">;
type SettableTableProps = Pick<TableProps, "stickyHeader">;
type OverrideProps = Pick<TableProps, "size">;

interface TableRadioGroupProps
    extends FormElementProps<Record<string, string>>,
    SettableBoxProps,
    SettableTableProps {
    rows?: Row[];
    columns?: Column[];
}
/**
 * A Workflow element built using React.
 * @displayName Table Radio Group
 * @description Table Radio Group
 * @param props The props that will be provided by the Workflow runtime.
 */
function TableRadioGroup(props: TableRadioGroupProps): React.ReactElement {
    const {
        setValue,
        maxHeight,
        maxWidth,
        value = {},
        rows = [
            { name: "asset_ownership", alias: "Asset Ownership", tooltip: "Defines who legally owns the asset." },
            { name: "asset_management", alias: "Asset Management", tooltip: "Covers the maintenance and lifecycle planning of the asset." },
            { name: "asset_maintenance", alias: "Asset Operation and Maintenance", tooltip: "Ensures daily operation and upkeep of the asset." },
        ],
        columns = [
            { name: "category", alias: "Category", weight: 2, tooltip: "This is the category column" },
            { name: "accept", alias: "Accept", weight: 1, tooltip: "Accept the asset responsibility" },
            { name: "refuse", alias: "Refuse", weight: 1, tooltip: "Refuse asset responsibility" },
            { name: "amendment", alias: "Amendment or Clarification Required", weight: 2, tooltip: "Additional information is needed" },
        ],
    } = props;

    const { size } = props as OverrideProps;

    // Calculate total weight dynamically (including first column)
    const totalWeight = columns.reduce((sum, col) => sum + (col.weight || 1), 0);

    return (
        <Box maxHeight={maxHeight} maxWidth={maxWidth} sx={{ overflow: "auto" }}>
            <Table
                size={size}
                sx={{
                    "& span": {
                        display: "inline-flex !important",
                    },
                }}
            >
                <TableHead>
                    <TableRow>
                        {columns.map((col, index) => (
                            <TableCell
                                key={index}
                                align={col.align || "center"}
                                sx={{ width: `${((col.weight || 1) / totalWeight) * 100}%`, fontWeight: "bold" }}
                            >
                                <Tooltip title={col.tooltip || "No description available"} arrow>
                                    <span>{col.alias || col.name}</span>
                                </Tooltip>
                            </TableCell>
                        ))}
                    </TableRow>
                </TableHead>
                <TableBody>
                    {rows.map((row, rowIndex) => (
                        <TableRow key={rowIndex}>
                            {columns.map((col, colIndex) => (
                                <TableCell key={colIndex} align={row.align || "left"} sx={{ width: `${((col.weight || 1) / totalWeight) * 100}%` }}>
                                    {colIndex === 0 ? ( // ✅ First column (Category)
                                        <Tooltip title={row.tooltip || "No description available"} arrow>
                                            <span style={{ fontWeight: "bold", cursor: "help" }}>{row.alias || row.name}</span>
                                        </Tooltip>
                                    ) : (
                                        <RadioGroup
                                            row
                                            name={`group-${rowIndex}`}
                                            value={value[row.name] || ""}
                                            onChange={(event) => setValue({ ...value, [row.name]: event.target.value })}
                                            sx={{ display: "flex", justifyContent: "center" }}
                                        >
                                            <FormControlLabel
                                                value={col.name} // ✅ Name used for value
                                                control={<Radio />}
                                                label=""
                                                sx={{
                                                    margin: 0,
                                                    padding: 0,
                                                    display: "flex",
                                                    justifyContent: "center",
                                                    alignItems: "center",
                                                }}
                                            />
                                        </RadioGroup>
                                    )}
                                </TableCell>
                            ))}
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </Box>
    );
}

const TableRadioGroupElementRegistration: FormElementRegistration<TableRadioGroupProps> = {
    component: TableRadioGroup,
    getInitialProperties: () => ({
        value: {
            asset_ownership: "accept", // ✅ Default selection: "Accept" for Asset Ownership
            asset_management: "refuse", // ✅ Default selection: "Refuse" for Asset Management
            asset_maintenance: "amendment", // ✅ Default selection: "Amendment" for Asset Operation and Maintenance
        },
        rows: [
            { name: "asset_ownership", alias: "Asset Ownership", tooltip: "Defines who legally owns the asset." },
            { name: "asset_management", alias: "Asset Management", tooltip: "Covers the maintenance and lifecycle planning of the asset." },
            { name: "asset_maintenance", alias: "Asset Operation and Maintenance", tooltip: "Ensures daily operation and upkeep of the asset." },
        ],
        size: "medium",
        columns: [
            { name: "category", alias: "Category", weight: 2, tooltip: "This is the category column" },
            { name: "accept", alias: "Accept", weight: 1, tooltip: "Accept the asset responsibility" },
            { name: "refuse", alias: "Refuse", weight: 1, tooltip: "Refuse asset responsibility" },
            { name: "amendment", alias: "Amendment or Clarification Required", weight: 1.1, tooltip: "Additional information is needed" },
        ],
    }),
    id: "TableRadioGroup",
};


export default TableRadioGroupElementRegistration;
