import { useNavigate, useParams } from "react-router-dom";
import HeaderBreadcrumbs from "../../../components/HeaderBreadcrumbs";
import Page from "../../../components/Page";
import { useContext, useEffect, useState } from 'react';
import { Member } from '../../../@types/corporates';
import { Corporate } from "@/@types/corporates";
import { ConfiguredCorporateContext } from "@/contexts/ConfiguredCorporateContext";
import { 
    Stack,
    Typography,
    Card,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Collapse,
    Box,
    Tab, 
} from '@mui/material';
import axios from '@/utils/axios';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { fDate, fDateTime } from '@/utils/formatTime';



export default function MemberHistory() {
    const { corporate_id, member_id } = useParams();
    const navigate = useNavigate();

    const [corporate, setCorporate] = useState<Corporate|null>();
    
    const [ currentMember, setCurrentMember ] = useState<Member>();

    const configuredCorporateContext = useContext(ConfiguredCorporateContext);

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

    const [openRows, setOpenRows] = useState({});

    const handleRowToggle = (index) => {
        setOpenRows((prevOpenRows) => ({
        ...prevOpenRows,
        [index]: !prevOpenRows[index],
        }));
    };

    return (
        <Page title="History Member">
        <HeaderBreadcrumbs
            heading={'History Member'}
            links={[
                {
                name: 'Corporates',
                href: '/corporates',
                },
                {
                name: corporate?.name ?? '-',
                href: '/corporates/'+corporate_id,
                },
                {
                name: 'Member',
                href: '/corporates/'+corporate_id+'/members',
                },
                {
                name: 'History',
                href: '/corporates/'+corporate_id+'/members/history',
                },
            ]}
        />
        <Card>
            <TableContainer component={Paper}>
                <Table aria-label="collapsible table">
                    {/* Condition Table Body */}
                    {currentMember?.data.map((item, index) => (
                        <TableBody key={index}>
                            <TableRow sx={{backgroundColor: '#919EAB29'}}>
                                <TableCell align="left" sx={{fontWeight: 'bold', width: '95%'}}><Typography variant="subtitle1">Data has {item.action} by {item.user_id} on {fDateTime(item.updated_at)}</Typography></TableCell>
                                <TableCell align="left" sx={{width: '5%'}}>
                                {openRows[index] ? (
                                    <KeyboardArrowDownIcon sx={{ cursor: 'pointer' }} onClick={() => handleRowToggle(index)} />
                                ) : (
                                    <KeyboardArrowRightIcon sx={{ cursor: 'pointer' }} onClick={() => handleRowToggle(index)} />
                                )}
                                </TableCell>
                            </TableRow>
                            <TableRow sx={{display: openRows[index] ? '' : 'none',}}>
                                <TableCell colSpan={2}>
                                    {/* COLLAPSIBLE ROW */}
                                    <Collapse in={openRows[index]} timeout="auto" unmountOnExit>
                                        <TableContainer component={Paper}>
                                            <Table aria-label="collapsible table">
                                                <TableHead>
                                                    <TableRow>
                                                        <TableCell align="left">
                                                            <Typography sx={{width: '25%'}} variant="subtitle2">Field</Typography>
                                                        </TableCell>
                                                        <TableCell align="left">
                                                            <Typography sx={{width: '25%'}} variant="subtitle2">Old Value</Typography>
                                                        </TableCell>
                                                        <TableCell align="left">
                                                            <Typography sx={{width: '50%'}} variant="subtitle2">New Value</Typography>
                                                        </TableCell>
                                                    </TableRow>
                                                </TableHead>
                                                <TableBody>
                                                    {Object.entries(item.old_values).map(([key, value]) => {
                                                        let renderedValue;
                                                        if (renderedValue !== value) {
                                                            switch (key) {
                                                                case 'updated_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);
        
                                                            return (
                                                                <TableRow key={key}>
                                                                    <TableCell align="left">
                                                                        <Typography variant="body2">{field ? field : '-'}</Typography>
                                                                    </TableCell>
                                                                    <TableCell align="left">
                                                                        <Typography variant="body2">{value ? value : '-'}</Typography>
                                                                    </TableCell>
                                                                    <TableCell align="left">
                                                                        <Typography variant="body2">{renderedValue ? renderedValue : ''}</Typography>
                                                                    </TableCell>
                                                                </TableRow>
                                                            );
                                                        }
                                                        else{
                                                            return null;
                                                        }
                                                        })}
                                                </TableBody>
                                            </Table>
                                        </TableContainer>
                                    </Collapse>
                                </TableCell>
                            </TableRow>
                        </TableBody>
                    ))}
                </Table>    
            </TableContainer>
        </Card>
        </Page>
    );
}
