/**
 * Core
 * ============================================
 */
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Box, FormControlLabel, Grid, Checkbox, Typography, CircularProgress , Button, styled, Stack, IconButton, Card} from '@mui/material';
import { LoadingButton } from '@mui/lab';

/**
 * Components
 * ============================================
*/
// - Global -
import Label from '@/components/Label';
// - Local -
import FormCreateSearch from './FormCreateSearch';
import FormCreateListChoose from './FormCreateListChoose';
import FormCreateBtnUpload from './FormCreateBtnUpload';

/**
 * Icon, Utils, Types, Functions, theme, hook
 * ============================================
 */
import { ArrowBackIosNew } from '@mui/icons-material';
import { fDateTimesecond } from '@/utils/formatTime';
import { MemberListType } from '../Model/Types';
import { addClaimRequest, getMemberList } from '../Model/Functions';
import palette from '@/theme/palette';
import FormCreateFilesUpload from './FormCreateFilesUpload';
import useLoadOnScroll from '@/hooks/useLoadOnScroll';
import useCollapseDrawer from '@/hooks/useCollapseDrawer';
import FormCreateBtnChoose from './FormCreateBtnChoose';
import axios from '../../../utils/axios';

export default function FormCreate() {
    const navigate = useNavigate()
    const defaultListChoosed:MemberListType[] = [];

    // State
    // -------------------------
    const [keyword, setKeyword]             = useState<string>('');
    const [listChoosed, setListChoosed]     = useState<MemberListType[]>([]);
    const [isChoosed, setIsChoosed]         = useState<boolean>(false);
    const [formIsLoading, setFormIsLoading] = useState<boolean>(false);

    // List Choose - auto Scroll
    // -------------------------
    const fetchFunction = async (page: number): Promise<MemberListType[]> => getMemberList(page, keyword)

    const {data: MemberList, isLoading: scrollIsLoading, setData, resetLastPage, refetchData} = useLoadOnScroll<MemberListType>(fetchFunction);

    // List Choose - Search
    // -------------------------
    const handleSearch = (keyword: string) => {
        setData([])
        resetLastPage()
        setKeyword(keyword)
        refetchData()
    }

    // Function - Clear Form
    // -----------------------------
    const clearForm = () => {
        setListChoosed(defaultListChoosed);
        setIsChoosed(false);
    }

    // Function - Choose Patien Type
    // -----------------------------
    const handleChoosePatienType = (data: MemberListType, type: string) => {
        let newListChoosed = listChoosed.map((list) => {
            if (data.id == list.id) {
                list.patien_type = type
            }
            
            return list;
        })
        setListChoosed(newListChoosed)
    }

    // Function - Handle Btn Upload
    // -----------------------------
    const handleChangeInput = (data: MemberListType, type_file: 'kondisi'|'diagnosa'|'penunjang', file: any) => {
        let newListChoosed = listChoosed.map((list) => {
            if (data.id == list.id) {
                if (type_file == 'kondisi') {
                    if (list.file_kondisi == undefined) {
                        list.file_kondisi = [file];
                    }
                    else {
                        list.file_kondisi.push(file);
                    }
                }

                if (type_file == 'diagnosa') {
                    if (list.file_diagnosa == undefined) {
                        list.file_diagnosa = [file];
                    }
                    else {
                        list.file_diagnosa.push(file);
                    }
                }

                if (type_file == 'penunjang') {
                    if (list.file_penunjang == undefined) {
                        list.file_penunjang = [file];
                    }
                    else {
                        list.file_penunjang.push(file);
                    }
                }
            }

            return list;
        })

        setListChoosed(newListChoosed)
    }

    // Function - Handle Remove Fle
    // -----------------------------
    const handleRemoveFile = (data: MemberListType, type_file: 'kondisi'|'diagnosa'|'penunjang', target_index: number) => {
        let newListChoosed = listChoosed.map((list) => {
            if (data.id == list.id) {
                if (type_file == 'kondisi') {
                    list.file_kondisi = list.file_kondisi?.filter((file: any, index: number) =>{
                        if (target_index !== index) {
                            return file;
                        }
                    });
                }

                if (type_file == 'diagnosa') {
                    list.file_diagnosa = list.file_diagnosa?.filter((file: any, index: number) =>{
                        if (target_index !== index) {
                            return file;
                        }
                    });
                }

                if (type_file == 'penunjang') {
                    list.file_penunjang = list.file_penunjang?.filter((file: any, index: number) =>{
                        if (target_index !== index) {
                            return file;
                        }
                    });
                }
            }

            return list;
        })

        setListChoosed(newListChoosed)
    }

    // Function - Handle Submit Form
    // -----------------------------
    const handleSubmit = async () => {
        setFormIsLoading(true)
        let response = await addClaimRequest(listChoosed)
        setFormIsLoading(false)

        if (response == true) {
            clearForm()
        }
    }



    let isDirty = listChoosed.some((row) => {
        if (row.patien_type == undefined) {
            return true
        }
    })

    return (
        <Box>
            {/* Back Button */}
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 5}}>
                <IconButton size='large' color='inherit' onClick={() => isChoosed==false ? navigate(`/claim-requests`) : setIsChoosed(false)} >
                    <ArrowBackIosNew/>
                </IconButton>

                <Typography variant="h5" sx={{ marginLeft: '24px' }}>
                    {'Create Claim Requests'}
                </Typography>
            </Box>

            {/* Choose Section */}
            <Grid container spacing={4} sx={{ px: 2, position: 'relative', display: isChoosed==false ? 'inherit' : 'none' }}>
                {/* Search */}
                <Grid item xs={12}>
                    <FormCreateSearch onEmpty={() => handleSearch('')} onSubmit={(keyword) => handleSearch(keyword)} />
                </Grid>

                <Grid item xs={12}>
                    <Grid container spacing={2}>
                        {/* List */}
                        <Grid item xs={12}>
                            <Grid container spacing={2}>
                                {
                                    MemberList.map((row, index) => {
                                        return (
                                            <FormCreateListChoose
                                                key={index}
                                                data={row}
                                                ListChoosed={listChoosed}
                                                handleCheckedProp={(checked, data) => {
                                                    checked ? setListChoosed((prevData) => [...prevData, data]) : setListChoosed((items) => items.filter(item => item.id != data.id))
                                                }}
                                            />
                                        )
                                    })
                                }
                            </Grid>
                        </Grid>

                        {/* Loading */}
                        <Grid item xs={12} sx={{ display: scrollIsLoading === false ? 'none' : 'flex', justifyContent: 'center', marginTop: '40px' }}>
                            <CircularProgress />
                        </Grid>

                        {/* Submit List */}
                        <Grid item xs={12}>
                            <FormCreateBtnChoose disabled={listChoosed.length==0} title={`Create Number Batch (${listChoosed.length})`} handleClickProp={() => setIsChoosed(true)} />
                        </Grid>
                    </Grid>
                </Grid>
            </Grid>

            {/* Input Section */}
            <Grid container spacing={10} sx={{ px: 2, display: isChoosed==true ? 'inherit' : 'none' }}>
                {
                    listChoosed.map((row, index) => {
                        return (
                            <Grid key={index} item xs={12}>
                                <Grid container spacing={6}>
                                    {/* Patien Name */}
                                    <Grid item xs={12}>
                                        <Card sx={{ border: '1px solid rgba(0,0,0,0.05)', display: 'flex', justifyContent: 'space-between', borderRadius: '12px', px: '24px', py: '16px' }}>
                                            <Box>
                                                <Typography variant="body2" sx={{ fontWeight: 600 }}>
                                                    {row.name}
                                                </Typography>
                                                <Typography variant="caption" color={palette.light.grey[500]} sx={{ fontWeight: 600 }}>
                                                    {row.member_id}
                                                </Typography>
                                            </Box>

                                            <Label variant="ghost" color="default">
                                                {fDateTimesecond(new Date())}
                                            </Label>
                                        </Card>
                                    </Grid>
                                    {/* Patien Type */}
                                    <Grid item xs={12}>
                                        <Grid container spacing={2}>
                                            {row.service_type.map((r,i) => {
                                                const code = r.code
                                                return (
                                                    <Grid item xs={6}>
                                                        <Button
                                                            sx={{ padding: 2, width: '100%',border: row.patien_type === code ? '1px solid #19BBBB' : '1px solid #919EAB52' }}
                                                            variant="outlined"
                                                            color={row.patien_type === code ? 'primary' : 'inherit'}
                                                            onClick={() => {
                                                                handleChoosePatienType(row, code)
                                                            }}
                                                        >
                                                            {r.name}
                                                        </Button>
                                                    </Grid>
                                                )
                                            })}
                                        </Grid>
                                    </Grid>

                                    {/* File Kondisi */}
                                    <Grid item xs={12}>
                                        <Grid container spacing={2}>
                                            <Grid item xs={12}>
                                                <Typography variant="h6">Condition Document</Typography>
                                            </Grid>

                                            {row.file_kondisi && row.file_kondisi.map((file, index) => (
                                                <Grid item xs={12} key={index}>
                                                    <FormCreateFilesUpload file={file} handleRemoveFileProp={() => handleRemoveFile(row, 'kondisi', index)} />
                                                </Grid>
                                            ))}

                                            <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                                <FormCreateBtnUpload handleChangeInputProp={(file) => handleChangeInput(row, 'kondisi', file)} />
                                            </Grid>
                                        </Grid>
                                    </Grid>

                                    {/* File Diagnosa */}
                                    <Grid item xs={12}>
                                        <Grid container spacing={2}>
                                            <Grid item xs={12}>
                                                <Typography variant="h6">Diagnosis Document</Typography>
                                            </Grid>

                                            {row.file_diagnosa && row.file_diagnosa.map((file, index) => (
                                                <Grid item xs={12} key={index}>
                                                    <FormCreateFilesUpload file={file} handleRemoveFileProp={() => handleRemoveFile(row, 'diagnosa', index)} />
                                                </Grid>
                                            ))}

                                            <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                                <FormCreateBtnUpload handleChangeInputProp={(file) => handleChangeInput(row, 'diagnosa', file)} />
                                            </Grid>
                                        </Grid>
                                    </Grid>

                                    {/* File Penunjang */}
                                    <Grid item xs={12}>
                                        <Grid container spacing={2}>
                                            <Grid item xs={12}>
                                                <Typography variant="h6">Supporting Result Document</Typography>
                                            </Grid>

                                            {row.file_penunjang && row.file_penunjang.map((file, index) => (
                                                <Grid item xs={12} key={index}>
                                                    <FormCreateFilesUpload file={file} handleRemoveFileProp={() => handleRemoveFile(row, 'penunjang', index)} />
                                                </Grid>
                                            ))}

                                            <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                                <FormCreateBtnUpload handleChangeInputProp={(file) => handleChangeInput(row, 'penunjang', file)} />
                                            </Grid>
                                        </Grid>
                                    </Grid>

                                </Grid>
                            </Grid>
                        )
                    })
                }

                <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Box display="flex" gap={1}>
                        <Button variant="outlined" color="inherit" onClick={() => clearForm()}>
                            Cancel
                        </Button>
                        <LoadingButton disabled={isDirty} type="submit" variant="contained" loading={formIsLoading} onClick={() => handleSubmit()}>
                            Save Changes
                        </LoadingButton>
                    </Box>
                </Grid>
            </Grid>
        </Box>
    )
}
