import { LoadingButton } from '@mui/lab';
import 
{ 
    Avatar,
    FormControl,
    InputLabel,
    Select,
    FormHelperText,
    MenuItem 
} from '@mui/material';
import { Card } from '@mui/material';
import { Stack, Typography } from '@mui/material';
import axios from '@/utils/axios';
import { enqueueSnackbar } from 'notistack';
import { useRef, useState, useContext } from 'react';
import { makeFormData } from '@/utils/jsonToFormData';
import { format } from 'date-fns';
import { LanguageContext } from '@/contexts/LanguageContext';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

interface MemberType {
    members: any;
    services: any;
    providers:any;
}
interface FormRequestClaimProps {
    member: MemberType;
    handleSubmitSuccess: () => void;
}
export default function FormRequestClaim({ member, handleSubmitSuccess }: FormRequestClaimProps) {
    const { localeData }: any =  useContext(LanguageContext);
    const [serviceCode, setServiceCode] = useState<string>('');
    const [idProvider, setIdProvider] = useState<number>(0);

    const [submitLoading, setSubmitLoading] = useState<boolean>(false);
    function submitRequest() {
        if(!idProvider&& (name == '' || alamat == ''))
        {
            enqueueSnackbar(localeData.txtAlertProvider, { variant: 'warning' });
            return false;
        }
        if(serviceCode == '')
        {
            enqueueSnackbar(localeData.txtDialogMember4, { variant: 'warning' });
            return false;
        }
        setSubmitLoading(true);
        const formData = {
            member_id: member.members.id,
            service_code: serviceCode,
            organization_id: idProvider,
            organization_name : name,
            address_provider: alamat
        };
        axios
        .post('/request-log', formData)
        .then((response) => {
            if (response && response.data && response.data.meta) {
                setTimeout(() => {
                    window.location.reload();
                  }, 1500);
                enqueueSnackbar(response.data.meta.message, { variant: 'success' });
                handleSubmitSuccess();
               
            }  
        })
        .catch(({ response }) => {
            if (response && response.data && response.data.meta) {
                enqueueSnackbar(response.data.meta.message, { variant: 'error' });
            } 
        })
        .then(() => {
            setSubmitLoading(false);
        });
    }

    interface MemberService {
        service_code: string;
        name: string;
    }

    interface Providers {
        id: number;
        name: string;
    }

    const [showAddNewForm, setShowAddNewForm] = useState(false);
    const [name, setName] = useState('');
    const [alamat, setAlamat] = useState('');

    const handleAddNewData = () => {
        // Logika untuk menambahkan data baru ke database
        // Pastikan untuk menyesuaikan logika ini sesuai dengan kebutuhan aplikasi Anda
        console.log('Adding new data:', { name, alamat });

        // Setelah menambahkan data baru, Anda mungkin ingin melakukan sesuatu seperti menutup formulir tambahan atau melakukan pengaturan lainnya
        setShowAddNewForm(false);
    };

    return (
        <Stack direction="column" spacing={2}>
        <Stack direction="row" justifyContent={'end'} sx={{ marginBottom: 2 }} spacing={2}>
            <Typography variant='body2' sx={{color: '#757575'}}>
            {localeData.txtDialogMember5}
            </Typography>
            <Typography variant='body2' sx={{fontWeight:'bold'}}>{format(new Date(), "d MMM yyyy")}</Typography>
        </Stack>

        <Stack direction="row" spacing={2}>
            <Stack spacing={2} sx={{ width: '100%' }}>
                <Typography variant='subtitle1'>{localeData.txtProvider} *</Typography>
                <Autocomplete
                id="provider"
                options={[{ name: localeData.txtAddNew, id: 0 }, ...member?.providers || []]}
                getOptionLabel={(option: Providers) => option.name || ''}
                value={member?.providers.find((item: Providers) => item.id === idProvider) || null}
                onChange={(event: React.ChangeEvent<{}>, newValue: Providers | null) => {
                    if (newValue?.id === 0) {
                    // Pengguna memilih opsi "Tambahkan Data Baru"
                    setIdProvider(0); // Reset nilai
                    setShowAddNewForm(true); // Menampilkan formulir tambahan
                    } else {
                    // Pengguna memilih opsi dari hasil pencarian
                    setIdProvider(newValue?.id || 0);
                    setShowAddNewForm(false); // Menyembunyikan formulir tambahan
                    }
                }}
                renderInput={(params) => (
                    <TextField
                    {...params}
                    label={localeData.txtProvider}
                    fullWidth
                    />
                )}
                />
                {showAddNewForm && (
                    <Stack direction="column" spacing={1} padding={1}>
                        <Typography variant='body2'>{localeData.txtAddNew} *</Typography>
                        <TextField
                        label={localeData.txtName}
                        fullWidth
                        onChange={(e) => setName(e.target.value)}
                        />
                        <TextField
                        label={localeData.txtAddress}
                        fullWidth
                        onChange={(e) => setAlamat(e.target.value)}
                        />
                    </Stack>
                )}
                <FormHelperText style={{ color: 'red' }}></FormHelperText>
            </Stack>
        </Stack>
        
        <Stack direction="row" spacing={2}>
            <Stack spacing={2} sx={{ width: '100%' }}>
                <Typography variant='subtitle1'>{localeData.txtDialogMember1} *</Typography>
                <Autocomplete
                id="service_type"
                options={member?.services || []}
                getOptionLabel={(option: MemberService) => option.name || ''}
                value={member?.services.find((item: MemberService) => item.service_code === serviceCode) || null}
                onChange={(event: React.ChangeEvent<{}>, newValue: MemberService | null) => {
                    setServiceCode(newValue?.service_code || '');
                }}
                renderInput={(params) => (
                    <TextField
                    {...params}
                    label={localeData.txtDialogMember1}
                    fullWidth
                    />
                )}
                />
                <FormHelperText style={{ color: 'red' }}></FormHelperText>
            </Stack>
        </Stack>

        <Card sx={{ p: 1, background: '#f4f6f8'}}>
            <Stack direction="row">
            <Avatar
                src=""
                alt={member?.members.name ?? ''}
                sx={{ marginTop: 1, width: 48, height: 48 }}
            />
            <Stack sx={{ p: 1 }}>
                <Typography variant="body2">{member?.members.name ?? ''}</Typography>
                <Typography variant="body2" sx={{color:'#637381'}}>{member?.members.member_id ?? ''}</Typography>
            </Stack>
            </Stack>
        </Card>

        <LoadingButton
            variant="contained"
            sx={{ marginTop: 2, p: 2, backgroundColor: '#19BBBB' }}
            onClick={() => {
            submitRequest();
            }}
            loading={submitLoading}
        >
            {localeData.txtDialogMember2}
        </LoadingButton>
        </Stack>
    );
}
