// @mui
import {
    Box,
    Button,
    Card,
    Collapse,
    Container,
    FormControl,
    Grid,
    IconButton,
    InputLabel,
    MenuItem,
    OutlinedInput,
    Paper,
    Select,
    SelectChangeEvent,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Typography,
    Badge,
    Stack,
  } from '@mui/material';
  import * as React from 'react';
  import { useParams } from 'react-router-dom';
  import { styled } from '@mui/material/styles';
  import ArrowForwardIosSharpIcon from '@mui/icons-material/ArrowForwardIosSharp';
  import MuiAccordion, { AccordionProps } from '@mui/material/Accordion';
  import { useContext, useEffect, useState } from 'react';
  import MuiAccordionSummary, {
    AccordionSummaryProps,
  } from '@mui/material/AccordionSummary';
  import useSettings from '../../../../hooks/useSettings';
  import axios from '../../../../utils/axios';
  import { ConfiguredCorporateContext } from '@/contexts/ConfiguredCorporateContext';
  import MuiAccordionDetails from '@mui/material/AccordionDetails';
  import HeaderBreadcrumbs from '../../../../components/HeaderBreadcrumbs';
  import { Corporate } from '@/@types/corporates';
  import { fDate, fDateTime } from '@/utils/formatTime';

  const Accordion = styled((props: AccordionProps) => (
    <MuiAccordion disableGutters elevation={0} square {...props} />
  ))(({ theme }) => ({
    border: `1px solid ${theme.palette.divider}`,
    '&:not(:last-child)': {
        borderBottom: 0,
    },
    '7:before': {
        display: 'none',
    },
  }));

  const AccordionSummary = styled((props: AccordionSummaryProps) => (
    <MuiAccordionSummary expandIcon={<ArrowForwardIosSharpIcon sx={{ fontSize: '0.9rem'}} />}
        {...props}
    />
  ))(({ theme }) => ({
    backgroundColor: theme.palette.mode === 'dark'
        ? 'rgba(255,255,255, .85)'
        : 'rgba(0,0,0, .03)',
    flexDirection: 'row-reverse', 
    '& .MuiAccordionSummary-expandIconWrapper.Mui-expanded' : {
        transform: 'rotate(90deg)',
    },
    '& .MuiAccordionSummary-content': {
        marginLeft: theme.spacing(1),
    },    
  }));

  const AccordionDetails = styled(MuiAccordionDetails)(({ theme }) => ({
    padding: theme.spacing(2),
    borderTop: '1px solid rgba(0, 0, 0, .125)',
  }));

  export default function CustomizedAccordions() {
    const [expanded, setExpanded] = React.useState<String | false>('panel1');

    const handleChange = (panel: string) => (event: React.SyntheticEvent, newExpanded: boolean) => {
        setExpanded(newExpanded ? panel : false);
    };

    const pageTitle = 'Corporate Formularium History'
    const { id } = useParams();
    const { corporate_id } = useParams();
    const [corporate, setCorporate] = useState<Corporate | null>();
    const [currentCorporate, setCurrentCorporate] = useState<Corporate>();
    const configuredCorporateContext = useContext(ConfiguredCorporateContext);

    useEffect(() => {
      setCorporate(configuredCorporateContext.currentCorporate);
      const model = 'App\\Models\\CorporateFormularium';
      const url = `/audittrail/${id}?model=${model}`;
      axios.get(url)
        .then((res) => {
          setCurrentCorporate(res.data);
        })
        .catch((error) => {
          console.error('Terjadi kesalahan', error)
        });
    }, [configuredCorporateContext]);

    return (
      <div>
        <HeaderBreadcrumbs 
          heading={pageTitle}
          links={[
            {
              name: 'Corporates',
              href: '/corporates',
            },
            {
              name: corporate?.name ?? '-',
              href: '/corporates/' + corporate_id,
            },
            {
              name: 'Formularium',
              href: '/corporates/' + corporate_id + '/formulariums',
            },
            {
              name: 'History',
              href: '/corporates/' + corporate_id + '/formulariums'
            },
          ]}
        />
        {currentCorporate?.data.map((item, index) => (
          <Accordion
            key={index}
            expanded={expanded === `panel${index}`}
            onChange={handleChange(`panel${index}`)}
          >
            <AccordionSummary
              aria-controls={`panel${index}d-content`}
              id={`panel${index}d-header`}
            >
              <Typography>{`Data has ${item.action} by ${item.user_id} on ${fDateTime(item.updated_at)}`}</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <TableContainer component={Paper}>
                <Table aria-label='collapsible table'>
                  <TableHead>
                    <TableRow>
                      <TableCell align='center'>Field</TableCell>
                      <TableCell align='center'>Old Value</TableCell>
                      <TableCell align='center'>New Value</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {Object.entries(item.old_values).map(([key, value]) => {
                      let renderedValue;
                      if (key === 'deleted_by' || 
                          key === 'deleted_at' || 
                          key === 'created_by' || 
                          key === 'created_at' || 
                          key === 'updated_by' ||
                          key === 'description' 
                        ) {
                        return null; // Melewati iterasi saat key adalah 'deleted_by'
                      }
                      switch (key) {
                        case 'welcome_message':
                          renderedValue = item.new_values[key].replace(/<[^>]*>/g, '');
                          value = value.replace(/<[^>]*>/g, '');
                          break;
                        case 'help_text':
                          renderedValue = item.new_values[key].replace(/<[^>]*>/g, '');
                          value = value.replace(/<[^>]*>/g, '');
                          break;
                        case 'active':
                          renderedValue = item.new_values[key] == 1 ? 'Active' : 'Inactive';
                          value = value == 1 ? 'Active' : 'Inactive';
                          break;
                        case 'created_at':
                          renderedValue = fDateTime(item.new_values[key]);
                          value = fDateTime(value);
                          break;
                        case 'updated_at':
                          renderedValue = fDateTime(item.new_values[key]);
                          value = fDateTime(value);
                          break;
                        case 'updated_at':
                          renderedValue = fDateTime(item.new_values[key]);
                          value = fDateTime(value);
                          break;
                        case 'delete_at':
                          renderedValue = fDateTime(item.new_values[key]);
                          value = fDateTime(value);
                          break;
                        default:
                          renderedValue = item.new_values[key];
                          break;
                      }

                      const field = key.charAt(0).toUpperCase() + key.slice(1);
                      if (value == renderedValue) {
                        return null
                      } else {
                        return (
                        <TableRow key={key} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
                          <TableCell align="center">{`${field}`}</TableCell>
                          <TableCell align="center">{`${value}`}</TableCell>
                          <TableCell align="center">{renderedValue}</TableCell>
                        </TableRow>
                        );
                      }
                    })}
                  </TableBody>
                </Table>
              </TableContainer>
            </AccordionDetails>
          </Accordion>
        ))}
      </div>
    );
  }