"use client";
import Grid from "@mui/material/Grid";
import Paper from "@mui/material/Paper";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import PageTitle from "../PageTitle/PageTitle";
import { Suspense } from "react";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Link from "next/link";
import { t } from "i18next";
import {
  Box,
  Container,
  Modal,
  Select,
  SelectChangeEvent,
  Typography,
} from "@mui/material";
import { Close } from "@mui/icons-material";
import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import SaveIcon from "@mui/icons-material/Save";
import CancelIcon from "@mui/icons-material/Close";
import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";
import ImageNotSupportedOutlinedIcon from "@mui/icons-material/ImageNotSupportedOutlined";
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import Swal from "sweetalert2";
import { msg } from "../Swal/CustomAlerts";
import React from "react";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import {
  GridRowsProp,
  GridRowModesModel,
  GridRowModes,
  DataGrid,
  GridColDef,
  GridToolbarContainer,
  GridFooterContainer,
  GridActionsCellItem,
  GridEventListener,
  GridRowId,
  GridRowModel,
  GridRowEditStopReasons,
  GridEditInputCell,
  GridValueSetterParams,
} from "@mui/x-data-grid";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import { Props } from "react-intl/src/components/relative";
import palette from "@/theme/devias-material-kit/palette";

const weekdays = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

interface BottomBarProps {
  getCostTotal: () => number;
  setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
  setRowModesModel: (
    newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
  ) => void;
}

interface EditToolbarProps {
  // setDay: (newDay : dayjs.Dayjs) => void;
  setDay: (newDay: (oldDay: dayjs.Dayjs) => dayjs.Dayjs) => void;
  setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
  setRowModesModel: (
    newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
  ) => void;
}

interface EditFooterProps {
  setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
  setRowModesModel: (
    newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
  ) => void;
}

const BottomBar = (props: BottomBarProps) => {
  const { setRows, setRowModesModel, getCostTotal } = props;
  // const getCostTotal = props.getCostTotal;
  const [newId, setNewId] = useState(-1);
  const [invalidDays, setInvalidDays] = useState(0);

  const handleAddClick = () => {
    const id = newId;
    setNewId(newId - 1);
    setRows((oldRows) => [
      ...oldRows,
      { id, projectCode: "", task: "", isNew: true },
    ]);
    setRowModesModel((oldModel) => ({
      ...oldModel,
      [id]: { mode: GridRowModes.Edit, fieldToFocus: "projectCode" },
    }));
  };

  const totalColDef = {
    flex: 1,
    // style: {color:getCostTotal('mon')>24?"red":"black"}
  };

  const TotalCell = ({ value }: Props) => {
    const [invalid, setInvalid] = useState(false);

    useEffect(() => {
      const newInvalid = (value ?? 0) < 0;
      setInvalid(newInvalid);
    }, [value]);

    return (
      <Box flex={1} style={{ color: invalid ? "red" : "black" }}>
        $ {value}
      </Box>
    );
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "flex", width: "100%" }}>
        <Box flex={1.5} textAlign={"right"} marginRight="4rem">
          <b>Total:</b>
        </Box>
        <TotalCell value={getCostTotal()} />
      </div>
      <Button
        variant="outlined"
        color="primary"
        startIcon={<AddIcon />}
        onClick={handleAddClick}
        sx={{ margin: "20px" }}
      >
        Add record
      </Button>
    </div>
  );
};

const EditFooter = (props: EditFooterProps) => {
  return (
    <div style={{ display: "flex", justifyContent: "flex", width: "100%" }}>
      <Box flex={1}>
        <b>Total: </b>
      </Box>
      <Box flex={2}>test</Box>
    </div>
  );
};

interface ClaimInputGridProps {
  onClose?: () => void;
}

const initialRows: GridRowsProp = [
  {
    id: 1,
    date: new Date(),
    description: "Taxi to client office",
    cost: 169.5,
    document: "taxi_receipt.jpg",
  },
  {
    id: 2,
    date: dayjs().add(-14, "days").toDate(),
    description: "MTR fee to Kowloon Bay Office",
    cost: 15.5,
    document: "octopus_invoice.jpg",
  },
  {
    id: 3,
    date: dayjs().add(-44, "days").toDate(),
    description: "Starbucks",
    cost: 504,
  },
];

const ClaimInputGrid: React.FC<ClaimInputGridProps> = ({ ...props }) => {
  const [rows, setRows] = useState(initialRows);
  const [day, setDay] = useState(dayjs());
  const [rowModesModel, setRowModesModel] = React.useState<GridRowModesModel>(
    {},
  );

  const handleRowEditStop: GridEventListener<"rowEditStop"> = (
    params,
    event,
  ) => {
    if (params.reason === GridRowEditStopReasons.rowFocusOut) {
      event.defaultMuiPrevented = true;
    }
  };

  const handleEditClick = (id: GridRowId) => () => {
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
  };

  const handleSaveClick = (id: GridRowId) => () => {
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
  };

  const handleDeleteClick = (id: GridRowId) => () => {
    setRows(rows.filter((row) => row.id !== id));
  };

  const handleCancelClick = (id: GridRowId) => () => {
    setRowModesModel({
      ...rowModesModel,
      [id]: { mode: GridRowModes.View, ignoreModifications: true },
    });

    const editedRow = rows.find((row) => row.id === id);
    if (editedRow!.isNew) {
      setRows(rows.filter((row) => row.id !== id));
    }
  };

  const processRowUpdate = (newRow: GridRowModel) => {
    const updatedRow = { ...newRow, isNew: false };
    setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
    return updatedRow;
  };

  const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
    setRowModesModel(newRowModesModel);
  };

  const getCostTotal = () => {
    let sum = 0;
    rows.forEach((row) => {
      sum += row["cost"] ?? 0;
    });
    return sum;
  };

  const commonGridColConfig: any = {
    type: "number",
    // sortable: false,
    //width: 100,
    flex: 1,
    align: "left",
    headerAlign: "left",
    // headerClassName: 'header',
    editable: true,
    renderEditCell: (value: any) => (
      <GridEditInputCell
        {...value}
        inputProps={{
          max: 24,
          min: 0,
          step: 0.25,
        }}
      />
    ),
  };

  const columns: GridColDef[] = [
    {
      field: "actions",
      type: "actions",
      headerName: t("Actions"),
      width: 100,
      cellClassName: "actions",
      getActions: ({ id }) => {
        const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

        if (isInEditMode) {
          return [
            <GridActionsCellItem
              key={`actions-${id}-save`}
              icon={<SaveIcon />}
              title={t("Save")}
              label={t("Save")}
              sx={{
                color: "primary.main",
              }}
              onClick={handleSaveClick(id)}
            />,
            <GridActionsCellItem
              key={`actions-${id}-cancel`}
              icon={<CancelIcon />}
              title={t("Cancel")}
              label={t("Cancel")}
              className="textPrimary"
              onClick={handleCancelClick(id)}
              color="inherit"
            />,
          ];
        }

        return [
          <GridActionsCellItem
            key={`actions-${id}-edit`}
            icon={<EditIcon />}
            title={t("Edit")}
            label={t("Edit")}
            className="textPrimary"
            onClick={handleEditClick(id)}
            color="inherit"
          />,
          <GridActionsCellItem
            key={`actions-${id}-delete`}
            title={t("Delete")}
            label={t("Delete")}
            icon={<DeleteIcon />}
            onClick={handleDeleteClick(id)}
            sx={{ color: "red" }}
          />,
        ];
      },
    },
    {
      field: "date",
      headerName: t("Invoice Date"),
      // width: 220,
      flex: 1,
      editable: true,
      type: "date",
    },
    {
      field: "description",
      headerName: t("Description"),
      // width: 220,
      flex: 2,
      editable: true,
      type: "string",
    },
    {
      field: "cost",
      headerName: t("Cost (HKD)"),
      editable: true,
      type: "number",
      valueFormatter: (params) => {
        return `$ ${params.value ?? 0}`;
      },
    },
    {
      field: "document",
      headerName: t("Supporting Document"),
      type: "string",
      editable: true,
      flex: 2,
      renderCell: (params) => {
        return params.value ? (
          <span>
            <a href="" target="_blank" rel="noopener noreferrer">
              {params.value}
            </a>
          </span>
        ) : (
          <span style={{ color: palette.text.disabled }}>No Documents</span>
        );
      },
      renderEditCell: (params) => {
        return params.value ? (
          <span>
            <a href="" target="_blank" rel="noopener noreferrer">
              {params.value}
            </a>
            <Button
              title={t("Remove Document")}
              onClick={(event) => console.log(event)}
            >
              <ImageNotSupportedOutlinedIcon
                sx={{ fontSize: "25px", color: "red" }}
              />
            </Button>
          </span>
        ) : (
          <Button title={t("Add Document")}>
            <AddPhotoAlternateOutlinedIcon
              sx={{ fontSize: "25px", color: "green" }}
            />
          </Button>
        );
      },
    },
  ];

  return (
    <Box
      sx={{
        // marginBottom: '-5px',
        display: "flex",
        "flex-direction": "column",
        // 'justify-content': 'flex-end',
        height: "100%", //'25rem',
        width: "100%",
        "& .actions": {
          color: "text.secondary",
        },
        "& .header": {
          backgroundColor: "#F8F9FA",
          // border: 1,
          // 'border-width': '1px',
          // 'border-color': 'grey',
        },
        "& .textPrimary": {
          color: "text.primary",
        },
      }}
    >
      <DataGrid
        sx={{ flex: 1 }}
        rows={rows}
        columns={columns}
        editMode="row"
        rowModesModel={rowModesModel}
        onRowModesModelChange={handleRowModesModelChange}
        onRowEditStop={handleRowEditStop}
        processRowUpdate={processRowUpdate}
        disableRowSelectionOnClick={true}
        disableColumnMenu={true}
        hideFooterPagination={true}
        slots={
          {
            // footer: EditFooter,
          }
        }
        slotProps={
          {
            // footer: { setDay, setRows, setRowModesModel },
          }
        }
        initialState={{
          pagination: { paginationModel: { pageSize: 100 } },
        }}
      />

      <BottomBar
        getCostTotal={getCostTotal}
        setRows={setRows}
        setRowModesModel={setRowModesModel}
        // sx={{flex:2}}
      />
    </Box>
  );
};

export default ClaimInputGrid;
