import { useNavigate, useParams } from "react-router-dom";
import HeaderBreadcrumbs from "../../../components/HeaderBreadcrumbs";
import Page from "../../../components/Page";
import { useContext, useEffect, useState } from 'react';
import { Hospital } 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 HospitalHistory() {
    const { corporate_id, id } = useParams();
    const navigate = useNavigate();

    const [corporate, setCorporate] = useState<Corporate|null>();
    
    const [ currentHospital, setCurrentHospital ] = useState<Hospital>();

    const configuredCorporateContext = useContext(ConfiguredCorporateContext);

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

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

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

    return (
        <Page title="History Hospital">
        <HeaderBreadcrumbs
            heading={'History Hospital'}
            links={[
                {
                name: 'Corporates',
                href: '/corporates',
                },
                {
                name: corporate?.name ?? '-',
                href: '/corporates/'+corporate_id,
                },
                {
                name: 'Hospital',
                href: '/corporates/'+corporate_id+'/hospitals',
                },
                {
                name: 'History',
                href: '/corporates/'+corporate_id+'/hospitals/history',
                },
            ]}
        />
        <Card>
            <TableContainer component={Paper}>
                <Table aria-label="collapsible table">
                    {/* Condition Table Body */}
                    {currentHospital?.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 (key === 'code' || key === 'name') {
                                                        renderedValue = item.new_values[key];    
                                                        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>
    );
}
