import React, { useState, useMemo } from 'react';
import MermaidDiagram from '../../MermaidDiagram.js';
import {
  Tabs,
  Tab,
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography,
  FormControlLabel,
  Checkbox,
  Tooltip,
  ThemeProvider,
  Button,
  Alert
} from '@mui/material';
import { CheckCircle, WarningAmberOutlined, ErrorOutlineOutlined } from '@mui/icons-material';
import CustomPagination from "../../Common/CustomPagination";
import theme from "../../Common/Theme"; // Assuming your theme path is correct
import { styled } from '@mui/material/styles';

// Helper function to determine if a row/entity is valid based on PHP response
const isValidValue = (value) => {
  // Treats "1" (string), 1 (number), or true (boolean) as valid.
  // Treats "", 0, false, null, undefined etc. as invalid.
  return value === '1' || value === 1 || value === true;
};

export const BundleImport = ({ validationResponse, baseUrl, importRef }) => {

  const [selectedTab, setSelectedTab] = useState(0);
  const [page, setPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(30);
  const [showOnlyInvalid, setShowOnlyInvalid] = useState(true);
  const [hoveredRow, setHoveredRow] = useState(null);
  const [showDiagram, setShowDiagram] = useState(false);


  const errorKeys = useMemo(() =>
    validationResponse?.data ? Object.keys(validationResponse.data) : [],
    [validationResponse]
  );

  const handleTabChange = (_, newValue) => {
    setSelectedTab(newValue);
    setPage(1); // Reset to first page when switching tabs
  };

  const isAllTabsValid = useMemo(() => {
    return errorKeys.every(key => {
      const data = validationResponse.data[key];
      if (Array.isArray(data)) {
        return data.every(row => isValidValue(row.valid));
      } else if (typeof data === 'object') {
        return isValidValue(data.valid);
      }
      return false;
    });
  }, [errorKeys, validationResponse]);

  // Check for errors and warnings separately
  const hasErrors = useMemo(() => {
    return errorKeys.some(key => {
      const data = validationResponse.data[key];
      if (Array.isArray(data)) {
        return data.some(row => row?.errors && row.errors.length > 0);
      } else if (typeof data === 'object') {
        return data.errors && data.errors.length > 0;
      }
      return false;
    });
  }, [errorKeys, validationResponse]);

  const hasWarnings = useMemo(() => {
    return errorKeys.some(key => {
      const data = validationResponse.data[key];
      if (Array.isArray(data)) {
        return data.some(row => row?.warnings && row.warnings.length > 0);
      } else if (typeof data === 'object') {
        return data.warnings && data.warnings.length > 0;
      }
      return false;
    });
  }, [errorKeys, validationResponse]);

  const handleSave = () => {
    const form = document.createElement('form');
    form.method = 'GET';
    form.action = 'SaveImportedData';
    document.body.appendChild(form);
    form.submit();
  };

  const getHeaders = (data) => {
    if (!Array.isArray(data) || data.length === 0) return ["Info"];

    let hasErrors = false;
    let hasWarnings = false;
    const otherKeys = new Set();

    data.forEach(row => {
      if (typeof row === 'object' && row !== null) {
        if ('errors' in row) hasErrors = true;
        if ('warnings' in row) hasWarnings = true;
        Object.keys(row).forEach(key => {
          if (key !== 'valid' && key !== 'info' && key !== 'errors' && key !== 'warnings') {
            otherKeys.add(key);
          }
        });
      }
    });

    const result = ["Info"];
    if (hasErrors) result.push("errors");
    if (hasWarnings) result.push("warnings");
    return [...result, ...Array.from(otherKeys)];
  };


  const CustomTooltip = styled(({ className, ...props }) => (
    <Tooltip {...props} classes={{ popper: className }} />
  ))({
    [`& .MuiTooltip-tooltip`]: {
      backgroundColor: '#FFF',
      border: '1px solid #AF0D10',
      color: '#000',
      fontSize: '0.875rem',
    },
  });

  const renderTableHeaders = (headers) => (
    <TableRow>
      {headers.map((header, idx) => (
        <TableCell key={idx}>{header.charAt(0).toUpperCase() + header.slice(1)}</TableCell>
      ))}
    </TableRow>
  );

  const renderTableBody = (dataForTable, columnHeaders) => {
    const currentVisibleRows = useMemo(() => {
      let rows = Array.isArray(dataForTable) ? dataForTable : [];
      if (showOnlyInvalid) {
        rows = rows.filter(row =>
          row && typeof row === 'object' && row.hasOwnProperty('valid')
            ? !isValidValue(row.valid)
            : (row && typeof row === 'object' ? true : false) // If no 'valid' prop, consider invalid for filtering
        );
      }
      return rows;
    }, [dataForTable, showOnlyInvalid]);

    if (currentVisibleRows.length === 0) {
      const dataExistsBeforeFilter = Array.isArray(dataForTable) && dataForTable.length > 0;
      return (
        <TableRow>
          <TableCell colSpan={Math.max(1, columnHeaders.length)} align="center">
            {showOnlyInvalid && dataExistsBeforeFilter ? "No invalid data to display" : "No data to display"}
          </TableCell>
        </TableRow>
      );
    }

    return currentVisibleRows
      .slice((page - 1) * rowsPerPage, page * rowsPerPage)
      .map((row, rowIndex) => {
        if (!row || typeof row !== 'object') return null; // Skip if row is not a valid object

        const isRowMarkedValid = row.hasOwnProperty('valid') ? isValidValue(row.valid) : false;

        const isRowHasError = row.hasOwnProperty('errors') ? true : false;
        const isRowhasWarnings = row.hasOwnProperty('warnings') ? true : false;
        const invalidRowColor = isRowhasWarnings && isRowHasError ?'#AF0D10': isRowhasWarnings ?'#443742': '#AF0D10';
        const hasWarningOnly = (invalidRowColor === '#443742') ? true:false;
        return (
          <TableRow
            key={rowIndex} // Consider a more stable unique key if available in `row`
            onMouseEnter={() => !isRowMarkedValid && setHoveredRow(rowIndex)}
            onMouseLeave={() => setHoveredRow(null)}
            sx={{
              '& td': { color: isRowMarkedValid ? '#443742' : invalidRowColor },
              backgroundColor: hoveredRow === rowIndex && !isRowMarkedValid ? '#FFF3E0' : 'transparent',
            }}
          >
              {columnHeaders.map((headerKey, cellIndex) => (
                <TableCell key={cellIndex}>
                  {headerKey === "Info" ? (
                    isRowMarkedValid ? (
                      <CheckCircle
                        role="img"
                        titleAccess="Valid"
                        sx={{ color: '#067A40' }}
                      />
                    ) : hasWarningOnly ? (
                      <CustomTooltip
                        title={row.info || "Warning"} // visual tooltip text
                        open={hoveredRow === rowIndex && hasWarningOnly}
                        arrow
                      >
                        {/* Warning icon with role="img" and accessible label */}
                        <WarningAmberOutlined
                          role="img"
                          titleAccess="Warning"
                          sx={{ color: '#C45221' }}
                        />
                      </CustomTooltip>
                    ) : (
                      <CustomTooltip
                        title={row.info || "Error"} // visual tooltip text
                        open={hoveredRow === rowIndex && !isRowMarkedValid}
                        arrow
                      >
                        {/* Error icon with role="img" and accessible label */}
                        <ErrorOutlineOutlined
                          role="img"
                          titleAccess="Error"
                          sx={{ color: '#AF0D10' }}
                        />
                      </CustomTooltip>
                    )
                  ) : (
                    row[headerKey] !== undefined && row[headerKey] !== null ? String(row[headerKey]) : ""
                  )}
                </TableCell>
              ))}


          </TableRow>
        );
      });
  };

  if (errorKeys.length === 0) {
    return (
      <Typography variant="h6" align="center" sx={{ mt: 5 }}>
        No Errors Found
      </Typography>
    );
  }

  return (
    <ThemeProvider theme={theme}>
        {/* {isAllTabsValid ? (
          <Alert severity="success" sx={{ mb: 2 }}>
            Validation successful.
          </Alert>
        ) : (
          <Alert severity="error" sx={{ mb: 2 }}>
            Validation unsuccessful. The following critical errors were found. Import cannot be completed
          </Alert>
        )} */}

      {hasErrors && (
        <Alert severity="error" sx={{ mb: 2 }} role="alert" aria-live="assertive" aria-atomic="true">
          Validation unsuccessful. The following critical errors were found. Import cannot be completed
        </Alert>
      )}
      {hasWarnings && (
        <Alert severity="warning" sx={{ mb: 2 }} role="alert" aria-live="polite" aria-atomic="true">
          Validation unsuccessful. The following warnings were identified. It is recommended that you address these before import
        </Alert>
      )}
      {isAllTabsValid && (
        <Alert severity="success" sx={{ mb: 2 }} role="alert" aria-live="polite" aria-atomic="true">
          Validation successful.
        </Alert>
      )}
      <Box sx={{ width: '100%' }} >
          <Tabs
              value={selectedTab}
          onChange={handleTabChange}
          variant="scrollable"
          scrollButtons="auto"
          TabIndicatorProps={{ style: { backgroundColor: '#067A40' } }}
        >
          {errorKeys.map((key, index) => {
            const entityData = validationResponse.data?.[key];
            let tabHasInvalidEntries = false;

            if (Array.isArray(entityData)) {
              if (entityData.length > 0) {
                tabHasInvalidEntries = entityData.some(item =>
                  item && typeof item === 'object' && item.hasOwnProperty('valid')
                    ? !isValidValue(item.valid)
                    : (item && typeof item === 'object' ? true : false)
                );
              }
            } else if (entityData && typeof entityData === 'object') { // Sheet-level error object
              tabHasInvalidEntries = entityData.hasOwnProperty('valid')
                ? !isValidValue(entityData.valid)
                : true; // If object has no 'valid' prop, assume it's an error for tab asterisk
            }

            return (
              <Tab
                label={
                  <Box display="flex" alignItems="center">
                    {key}
                    {tabHasInvalidEntries && (
                      <Box component="span" sx={{ color: 'red', fontSize: '18px', marginLeft: '5px', lineHeight: 1 }}>
                        *
                      </Box>
                    )}
                  </Box>
                }
                key={index}
                sx={{
                  borderBottom: selectedTab === index ? '2px solid #067A40' : '1px solid #ccc',
                  color: selectedTab === index ? '#067A40' : '#000',
                  textTransform: "none", // Prevents all-caps
                  '&.Mui-selected': { color: '#067A40' },
                }}
              />
            );
          })}
        </Tabs>

        {errorKeys.map((key, index) => {
          const originalDataForTab = validationResponse.data?.[key];

          const tableData = useMemo(() => {
            if (Array.isArray(originalDataForTab)) {
              return originalDataForTab;
            } else if (typeof originalDataForTab === 'object' && originalDataForTab !== null) {
              return [originalDataForTab]; // Wrap sheet-level/single object into an array
            }
            return []; // Default to empty array
          }, [originalDataForTab]);

          const headersForCurrentTable = useMemo(() => getHeaders(tableData), [tableData]);
          const totalRecordsForPagination = useMemo(() => {
              let dataToCount = tableData;
              if (showOnlyInvalid) {
                  dataToCount = dataToCount.filter(row =>
                      row && typeof row === 'object' && row.hasOwnProperty('valid')
                          ? !isValidValue(row.valid)
                          : (row && typeof row === 'object' ? true : false)
                  );
              }
              return dataToCount.length;
          }, [tableData, showOnlyInvalid]);


          return (
            <TabPanel value={selectedTab} index={index} key={index}>
              <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={showOnlyInvalid}
                      onChange={(e) => {
                        setPage(1);
                        setShowOnlyInvalid(e.target.checked);
                      }}
                    />
                  }
                  label="Show only invalid rows"
                  sx = {{mt:2, ml:1}}
                />
              </Box>

              <TableContainer component={Paper}>
                <Table>
                  <TableHead>{renderTableHeaders(headersForCurrentTable)}</TableHead>
                  <TableBody>{renderTableBody(tableData, headersForCurrentTable)}</TableBody>
                </Table>
              </TableContainer>

              <CustomPagination
                totalRecords={totalRecordsForPagination}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={(newPage) => setPage(newPage)}
                onRowsPerPageChange={(newRows) => {
                  setPage(1);
                  setRowsPerPage(newRows);
                }}
                rowsPerPageOptions={[30,50,100]}
              />
            </TabPanel>
          );
        })}
      </Box>

      <Box>

        {/* {isAllTabsValid && (
          <Box sx={{ textAlign: 'center', my: 2 }}>
            <Button variant="contained" color="success" onClick={handleSave} sx={{color: 'white'}}>
              Complete Import
            </Button>
          </Box>
        )} */}
      </Box>

      <Box sx={{ textAlign: 'center', my: 2 }}>
        <Button
          variant="contained"
          color="success"
          sx={{ color: 'white' }}
          disabled={hasErrors} // Disable only if there are errors
          onClick={!hasErrors ? handleSave : undefined} // Attach handler only if no errors
        >
          Complete Import
        </Button>
      </Box>

        {importRef && (
            <MermaidDiagram
                src={`${baseUrl}pt/import/${importRef}`}
                title="Imported Structure Preview"
            />
        )}

    </ThemeProvider>
  );
};

const TabPanel = ({ children, value, index }) => {
  return value === index ? <Box sx={{ p: 0 }}>{children}</Box> : null;
};

// export default BundleImport; // or however you export it
