import React, { useEffect, useState } from "react";
import {
  Typography,
  useMediaQuery,
  useTheme,
  Tabs,
  Tab,
  Box,
  Button,
} from "@mui/material";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import DataGrids from "../../components/Datagrid";
import themestyle from "../../theme";
import { useNavigate } from "react-router-dom";
import { GET_ALL_ASSETS } from "../../graphql/query";
import { useQuery, useMutation } from "@apollo/client";
import { EDIT_PROFILE_TEXT, TYPOGRAPHY_TEXT } from "../../const";

const Assets: React.FC = () => {
  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("md"));
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState("");
  const [assets, setAssets] = useState([]);

  const [totalPages, setTotalPages] = useState(0);

  const handlePaginationChange = (newModel: any) => {
    setPaginationModel((prevModel) => ({
      ...prevModel,
      ...newModel,
    }));
  };

  const [paginationModel, setPaginationModel] = React.useState({
    pageSize: 5,
    page: 0,
  });

const columns: GridColDef[] = [
  { field: "S_No", headerName: "S.No", flex: 1 },
  { field: "market", headerName: "Market", flex: 1 },
  {
    field: "numberOfInvestments",
    headerName: "Number of Investments",
    flex: 1,
  },
  { field: "benchmark", headerName: "Benchmark", flex: 1 },
  {
    field: "inceptionDate",
    headerName: "Inception Date",
    flex: 1,
    valueFormatter: (params) => {
      if (!params.value) {
        return "Invalid Date";
      }

      const [day, month, year] = params.value.split("/");
      const date = new Date(`${year}-${month}-${day}`);

      if (!isNaN(date.getTime())) {
        return date.toLocaleDateString("en-GB", {
          day: "2-digit",
          month: "2-digit",
          year: "numeric",
        });
      }
      return "Invalid Date";
    },
  },
  {
      field: "action",
      headerName: "View Markets",
      flex: 1,
      renderCell: (params) => (
        <Button
          variant="outlined"
          color="primary"
          onClick={() => handleViewMarket(params.row.id)} 
          sx={{
            textTransform:"none"
          }}
        >
          {EDIT_PROFILE_TEXT.VIEW}
        </Button>
      ),
    },
];

  const handleViewMarket = (assetId: string) => {
    navigate(`/admin/assetview/${assetId}`);
  };

  const handleSearchQueryChange = (newQuery: string) => {
    setSearchQuery(newQuery);
    if (newQuery.trim() === "") {
      assetRefetch({ variables: { searchQuery: {} } });
    } else {
      assetRefetch();
    }
  };

  const handleAddAssetClick = () => {
    navigate("/admin/addasset");
  };
const {
  loading: assetLoading,
  error: assetError,
  data: assetData,
  refetch: assetRefetch,
} = useQuery(GET_ALL_ASSETS, {
  fetchPolicy: "network-only",
  variables: {
    page: paginationModel.page + 1,
    perPage: paginationModel.pageSize,
    searchQuery: searchQuery || "",
  },
  onCompleted: (data) => {
    const { total, items } = data.getAssetByPage;
    const formattedRows = items.map((asset: any, index: number) => {
      const inceptionDate = asset.inceptionDate && !isNaN(parseInt(asset.inceptionDate))
        ? new Date(parseInt(asset.inceptionDate))
        : null;


      return {
        id: asset.id,
        market: asset.market,
        numberOfInvestments: asset.numberOfInvestments,
        benchmark: asset.benchmark,
        inceptionDate: inceptionDate && !isNaN(inceptionDate.getTime())
          ? inceptionDate.toLocaleDateString("en-GB", {
              day: "2-digit",
              month: "2-digit",
              year: "numeric",
            })
          : "Invalid Date",
        S_No: index + 1 + paginationModel.page * paginationModel.pageSize,
        products: asset.products,
      };
    });
    setAssets(formattedRows);
    setTotalPages(total);
  },
});

  return (
    <Box sx={{ padding: 2, bgcolor: "#F9FAFC", minHeight: "85vh" }}>
      <Typography
        variant="h5"
        gutterBottom
        sx={{
          color: "#1A202C",
          fontWeight: 600,
          letterSpacing: "-0.3px",
          padding: "5px",
        }}
      >
        {TYPOGRAPHY_TEXT.ASSETS}
      </Typography>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: "20px",
        }}
      >
        <Button
          onClick={handleAddAssetClick}
          variant="contained"
          color="primary"
          sx={{
            marginLeft: "auto",
            fontSize: isMobile ? "12px" : "14px",
            textTransform: "none",
            bgcolor: themestyle.colors.primary,
            borderRadius: "8px",
            minWidth: "100px",
            padding: isMobile ? "8px 16px" : "10px 20px",
          }}
        >
          {TYPOGRAPHY_TEXT.ADD_ASSET}
        </Button>
      </Box>
      <Typography
        style={{
          fontWeight: 400,
          fontFamily: "Roboto",
          fontSize: isSmallScreen ? "32px" : "26px",
          color: "black",
          textAlign: "center",
        }}
      >
        <DataGrids
          rows={assets}
          columns={columns}
          pageSizeOptions={[5, 10, 20, 30]}
          rowCount={totalPages}
          style={{ border: "0px" }}
          paginationMode="server"
          paginationModel={paginationModel}
          onPaginationModelChange={handlePaginationChange}
          onSearchQueryChange={handleSearchQueryChange}
          searchQuery={searchQuery}
          loading={assetLoading}
        />
      </Typography>
    </Box>
  );
};

export default Assets;
