// mui
import { styled } from '@mui/material/styles';
import { LoadingButton, TabPanel } from "@mui/lab";
import { 
  Button, 
  Card, 
  Divider, 
  Grid, 
  LinearProgress, 
  linearProgressClasses, 
  Typography, 
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Collapse, } from "@mui/material";
import { Tab, Tabs } from "@mui/material";
import { Box, Stack } from "@mui/material";
import React, { useEffect, useState, useContext } from "react";
import { fCurrency } from '@/utils/formatNumber';
import { fPostFormat } from '@/utils/formatTime';
import { Avatar } from '@mui/material';
import Iconify from '@/components/Iconify';
import FormRequestClaim from './FormRequestClaim';
import FormRequestLog from './FormRequestLog';
import { LanguageContext } from '@/contexts/LanguageContext';
import { format } from 'date-fns';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';

export default function DialogMember(member:any, handleSubmitSuccess:() => void) {
    const { localeData }: any =  useContext(LanguageContext);
    const [currentTab, setCurrentTab] = useState('request');
        
    // ----------------------------------------------------------------------

    useEffect(() => {
        setCurrentTab('detail')
    }, [member])

    function handleChangeTab(event: React.SyntheticEvent, newValue: string) {
        setCurrentTab(newValue)
    }

    // ----------------------------------------------------------------------

    const BorderLinearProgress = styled(LinearProgress)(({ theme }) => ({
        height: 10,
        borderRadius: 6,
        [`&.${linearProgressClasses.colorPrimary}`]: {
        backgroundColor: theme.palette.grey[theme.palette.mode === 'light' ? 300 : 800],
        },
        [`& .${linearProgressClasses.bar}`]: {
        borderRadius: 6,
        background: 'linear-gradient(270deg, #19BBBB 38.42%, #FF9565 76.21%, #FE7253 104.02%)',
        },
    }));

    function TabPanel(props:any) {
        const { children, value, index, ...other } = props;
        return (
          <div
            role="tabpanel"
            hidden={value !== index}
            id={`simple-tabpanel-${index}`}
            aria-labelledby={`simple-tab-${index}`}
            {...other}
          >
            {value === index && (
              <Box sx={{ p: 3 }}>
                <div>{children}</div>
              </Box>
            )}
          </div>
        );
    }
    
    const [openRows, setOpenRows] = useState<any>({});

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

    return (
        <div>
            <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                <Tabs
                    value={currentTab}
                    onChange={handleChangeTab}
                    aria-label="wrapped label tabs example"
                >
                    <Tab value="detail" label={localeData.txtDialogMember3} />
                    <Tab value="service" label={localeData.txtDialogMember1} />
                    {member?.type !== 'view' ? (
                      <Tab value="request" label={localeData.txtDialogMember2} />
                    ) : ''}
                </Tabs>

                <TabPanel value={currentTab} index={'detail'}>
                    <Stack direction="column" spacing={2}>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">Member ID</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{ member?.members.member_id ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">Policy Number</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{ member?.members.policy_id  ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">NRIC</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.nik ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">NIK</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.nik ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">Email</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.email ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">{localeData.txtDateBirth}</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.birth_date ? format(new Date(member.members.birth_date), "d MMM yyyy") : '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">{localeData.txtGender}</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.gender ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">{localeData.txtMaritalStatus}</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.marital_status ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">{localeData.txtLanguage}</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.language ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">Race</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.race ?? '-'}</Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{width:'50%'}} variant="body2">{localeData.txtRelationship}</Typography>
                        <Typography sx={{width:'50%', fontWeight: 'bold'}} variant="body2">{member?.members.relation_with_principal != '' ? member?.members.relation_with_principal : '-'}</Typography>
                      </Stack>
                    </Stack>
                </TabPanel>
                <TabPanel value={currentTab} index={'service'}>
                        <TableContainer component={Paper}>
                            <Table aria-label="collapsible table">
                            {member && member.groupServices && Object.keys(member.groupServices).map((serviceCode, index) => (
                                    <TableBody key={index}>
                                        <TableRow sx={{backgroundColor: '#FFFFFF', borderBottom: openRows[index] ? '' : '1px solid #e0e0e0'}}>
                                            <TableCell align="left" sx={{fontWeight: 'bold', width: '95%'}}><Typography variant="subtitle1">{serviceCode}</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', borderBottom: openRows[index] ? '1px solid #e0e0e0' : ''}}>
                                            <TableCell colSpan={2}>
                                                {/* COLLAPSIBLE ROW */}
                                                <Collapse in={openRows[index]} timeout="auto" unmountOnExit>
                                                <Grid container spacing={2}>
                                                {/* Loop through the array for the current serviceCode */}
                                                {member.groupServices[serviceCode].map((item:any, innerIndex:number) => (
                                                    <Grid item sm={6} key={innerIndex}>
                                                    <Card sx={{ p: 2 }}>
                                                        <Typography variant="body2" sx={{ fontWeight: 'bold' }}>{item.description}</Typography>
                                                        <Typography variant="body2" sx={{ color: '#919EAB' }}>{item.code}</Typography>
                                                    </Card>
                                                    </Grid>
                                                ))}
                                                </Grid>
                                                </Collapse>
                                            </TableCell>
                                        </TableRow>
                                    </TableBody>
                            ))}
                            </Table>    
                        </TableContainer>
                </TabPanel>
                <TabPanel value={currentTab} index={'request'}>
                    <FormRequestLog member={member} handleSubmitSuccess={handleSubmitSuccess} />
                </TabPanel>
            </Box>
        </div>
    )
}