/* ---------------------------------- @mui ---------------------------------- */
import { Stack, Button, MenuItem, SelectChangeEvent, Tab, Tabs, Card, Box } from '@mui/material';
/* ---------------------------------- axios --------------------------------- */
// import axios from 'axios';
import axios from '../../utils/axios';
import { styled } from '@mui/material/styles';
/* ---------------------------------- react --------------------------------- */
import { useContext, useEffect, useState } from 'react';

/* -------------------------------- component ------------------------------- */
import Iconify from '../../components/Iconify';
import TableComponent from '../../components/Table';
/* ---------------------------------- theme --------------------------------- */
import palette from '../../theme/palette';
//import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { fDate, fDateSuffix, fDateTime } from '../../utils/formatTime';
import Typography from '@mui/material/Typography';
import { format } from 'date-fns';
import TableMoreMenu from '../../components/table/TableMoreMenu';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
import HistoryIcon from '@mui/icons-material/History';
import SearchIcon from '@mui/icons-material/Search';
import Label from '../../components/Label';
import { enqueueSnackbar } from 'notistack';
import { LoadingButton, TabPanel } from "@mui/lab";
import { LanguageContext } from '@/contexts/LanguageContext';
import MuiDialog from '@/components/MuiDialog';
import DialogMember from './DialogMember';
import DialogClaimSubmit from './DialogClaimSubmit';
import { fPostFormat } from '@/utils/formatTime';

export default function TableListFinalLog() {
  const navigate = useNavigate();
  const { localeData }: any =  useContext(LanguageContext);

  const [data, setData] = useState([]);

  // Download LOG
  async function handleDownloadLog(request_log_id: any, service_code:any, no_polis:any, full_name:any, provider:any, approved_fina_log_at:any) {
    return axios
      .get(`download-final-log/${request_log_id}`, {
        responseType: 'blob',
      })
      .then((response) => {
        // GL Akhir-010124-OP-00001234 Ratih-LinkSehat
        const namaFile = 'GL Akhir-'+provider+'-'+getFormattedDate(approved_fina_log_at)+'-'+service_code+'-'+no_polis+'-'+full_name+'-LinkSehat.pdf';
        const url = URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', namaFile);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch((error) => {
        enqueueSnackbar(error.message, { variant: 'error' });
      });
  }

  function getFormattedDate(approved_fina_log_at:any) {
      const approvedDate = new Date(approved_fina_log_at.replace(/-/g, '/')); // Mengatasi masalah format pada Safari
      const day = String(approvedDate.getDate()).padStart(2, '0');
      const month = String(approvedDate.getMonth() + 1).padStart(2, '0'); // Bulan dimulai dari 0 (Januari = 0)
      const year = String(approvedDate.getFullYear()).substring(2, 4);

      return `${day}${month}${year}`;
  }

  /* -------------------------------------------------------------------------- */
  /*                          setting up for the table                          */
  /* -------------------------------------------------------------------------- */
  const [isLoading, setIsLoading] = useState(true);

  const loadings = {
    isLoading: isLoading,
    setIsLoading: setIsLoading,
  };

  /* ------------------------------ handle params ----------------------------- */
  const [searchParams, setSearchParams] = useSearchParams();
  const [appliedParams, setAppliedParams] = useState({});

  const params = {
    searchParams: searchParams,
    setSearchParams: setSearchParams,
    appliedParams: appliedParams,
    setAppliedParams: setAppliedParams,
  };
  /* -------------------------------------------------------------------------- */

  /* ------------------------------ handle order ------------------------------ */
  const [order, setOrder] = useState<Order>('desc');
  const [orderBy, setOrderBy] = useState('submission_date');

  const orders = {
    order: order,
    setOrder: setOrder,
    orderBy: orderBy,
    setOrderBy: setOrderBy,
  };
  /* -------------------------------------------------------------------------- */

  /* ---------------------------- handle pagination --------------------------- */
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const [paginationTable, setPaginationTable] = useState<PaginationTableProps>({
    current_page: 0,
    from: 0,
    last_page: 0,
    links: [],
    path: '',
    per_page: 0,
    to: 0,
    total: 0,
  });

  const paginations = {
    page: page,
    setPage: setPage,
    rowsPerPage: rowsPerPage,
    setRowsPerPage: setRowsPerPage,
    paginationTable: paginationTable,
    setPaginationTable: setPaginationTable,
  };

  /* -------------------------------------------------------------------------- */

  /* ------------------------------ handle search ----------------------------- */
  const [searchText, setSearchText] = useState('');

  const handleSearchSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (searchText === '') {
      searchParams.delete('search');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['search', searchText]]);
      setAppliedParams(params);
    }
  };

  const searchs = {
    useSearchs: true,
    searchText: searchText,
    setSearchText: setSearchText,
    handleSearchSubmit: handleSearchSubmit,
  };

  /* ------------------------------ handle filter ----------------------------- */
  const [statusValue, setStatusValue] = useState('all');
  const [filterData, setStatusData] = useState([]);

  // handle status
  const handleStatusChanges = (event: SelectChangeEvent) => {
    setStatusValue(event.target.value as string);

    if (event.target.value === 'all') {
      searchParams.delete('status');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([
        ...searchParams.entries(),
        ['status', event.target.value as string],
      ]);
      setAppliedParams(params);
    }
  };

  const filterStatus = {
    useFilter: true,
    config: {
      label: 'Status',
      statusValue: statusValue,
      filterData: filterData,
      handleStatusChange: handleStatusChanges,
    },
  };

  // handle start date
  const [startDateValue, setStartDateValue] = useState('');

  const handleStartDateChanges = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const newStartDateValue = event.currentTarget.elements['date-input'].value;
    setStartDateValue(newStartDateValue);
    if (newStartDateValue === '') {
      searchParams.delete('start_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['start_date', newStartDateValue]]);
      setAppliedParams(params);
    }
  };

  const filterStartDate = {
    useFilter: true,
    startDate: startDateValue,
    setStartDate: setStartDateValue,
    handleStartDateChange: handleStartDateChanges,
  };

  // handle end date
  const [endDateValue, setEndDateValue] = useState('');

  const handleEndDateChanges = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const newEndDateValue = event.currentTarget.elements['date-input'].value;
    setEndDateValue(newEndDateValue);
    if (newEndDateValue === '') {
      searchParams.delete('end_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['end_date', newEndDateValue]]);
      setAppliedParams(params);
    }
  };

  const filterEndDate = {
    useFilter: true,
    endDate: endDateValue,
    setEndDate: setEndDateValue,
    handleEndDateChange: handleEndDateChanges,
  };

  /* -------------------------------- headCell Final LOG -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'code',
      align: 'left',
      label: localeData.txtRequestCode,
      isSort: true,
    },
    {
      id: 'provider',
      align: 'left',
      label: localeData.txtProvider,
      isSort: true,
    },
    {
      id: 'full_name',
      align: 'left',
      label: localeData.txtName,
      isSort: true,
    },
    {
      id: 'submission_date',
      align: 'center',
      label: localeData.txtSubmissionDate,
      isSort: true,
    },
    {
      id: 'service_type',
      align: 'center',
      label: localeData.txtServiceType,
      isSort: true,
    },
    {
      id: 'discharge_date',
      align: 'center',
      label: localeData.txtDischargeDate,
      isSort: true,
    },
    {
      id: 'status',
      align: 'center',
      label: localeData.txtStatus,
      isSort: true,
    },
    {
      id: 'action',
      align: 'right',
      label: '',
      isSort: false,
    },
  ];
  function handleSearchMember(noPolis:any, birthDate:any) {
    setLoadingClaim(false)
    axios.post('/search-member', { 
      no_polis: noPolis, 
      birth_date: birthDate ? fPostFormat(birthDate, 'yyyy-MM-dd') : null,
      type: 'view'
    })
    .then((response) => {
      setOpenDialogBenefit(true)
      setCurrentMember(response.data.data)
      setNameMember(response.data.data.members.name);
    })
    .catch(({response}) => {
      enqueueSnackbar(response.data.errors ? response.data.errors[0] : (response.data ? response.data.meta.message : 'Opps, Something went Wrong!'), {variant : "error"})
    })
    .then(() => {
    });
  }
  const [openDialogClaimSubmit, setOpenDialogClaimSubmit] = useState(false);
  const [dataViewClaimSubmit, setDataViewClaimSubmit] = useState<any>(null);
  function handleRequestClaimSubmit(member_id:any, service_code:any, id:any, full_name:any, no_polis:any, submission_date:any)
  {
    setOpenDialogClaimSubmit(true);
    const datas_view = {
      'member_id' : member_id,
      'service_code' : service_code,
      'id' : id,
      'full_name' : full_name,
      'no_polis' : no_polis,
      'submission_date' : submission_date
    };
    setDataViewClaimSubmit(datas_view);
  }

  useEffect(() => {
    getData();
  }, [appliedParams, searchParams, order, orderBy, setSearchParams]);

  function getData()
  {
    (async () => {
      setIsLoading(true);

      await new Promise((resolve) => setTimeout(resolve, 250));

      const parameters =
        Object.keys(appliedParams).length !== 0
          ? appliedParams
          : Object.fromEntries([...searchParams.entries(), ['order', order], ['orderBy', orderBy]]);

      const response = await axios.get(`/get-final-log`, {
        params: { ...parameters, search:searchText, order: order,
          orderBy: orderBy, type: 'final-log' },
      });
      setData(
        response.data.data.map((obj: any) => ({
          ...obj,
          provider:formatTitleCase(obj.provider),
          full_name:formatTitleCase(obj.full_name),
          status:
            obj.status === 'requested' ? (
              <Label color='primary'>
                Request
              </Label>
            ) : obj.status === 'approved' ? (
              <Label color='success' >
                Approval
              </Label>
            ) : obj.status === 'declined' ? (
              <Label color='error'>
                Decline
              </Label>
            ) : obj.status === 'reviewed' ? (
              <Label color='info'>
                Review
              </Label>
            ) : (
              <Label color='primary'>
                Pending
              </Label>
            ),
            submission_date:
              <Label>
                {obj.submission_date ? fDateTime(obj.submission_date) : ''}
              </Label>
            ,
            discharge_date:
              obj.discharge_date ? (
                <Label>
                  {obj.discharge_date ? fDateTime(obj.discharge_date) : ''}
                </Label>
              ) : ''
            ,
            action:
                  <TableMoreMenu actions={
                    <>
                      <MenuItem onClick={() => handleSearchMember(obj.no_polis, obj.birth_date) }>
                        <Iconify icon="eva:eye-fill" />
                        View
                      </MenuItem>
                      {obj.status === 'approved' ? (
                      <MenuItem onClick={() => handleDownloadLog(obj.id, obj.service_code, obj.no_polis, obj.full_name, obj.provider, obj.approved_final_log_at)}>
                      <Iconify icon="eva:download-fill" />
                        Download Final LOG
                      </MenuItem>
                      ):''}
                      {!obj.check_claim &&  obj.status === 'approved' ? (
                      <MenuItem onClick={() => handleRequestClaimSubmit(obj.member_id, obj.service_code, obj.id, obj.full_name, obj.no_polis, obj.submission_date) }>
                        <Iconify icon="fa:file-text" />
                        Submit Claim
                      </MenuItem>
                      ):''}
                    </>
                  } />
        }))
      );

      setPaginationTable(response.data);
      setRowsPerPage(response.data.per_page);

      if (searchParams.get('page')) {
        //@ts-ignore
        const currentPage = parseInt(searchParams.get('page')) - 1;

        paginationTable.current_page = currentPage;
        setPage(currentPage);
      }

      const status:any = [
        {"id": "requested", "name": "Request" },
        {"id": "reviewed", "name": "Review" },
        {"id": "approved", "name": "Approval" },
        {"id": "declined", "name": "Decline" },
      ];
      setStatusData(status)

      setIsLoading(false);
    })();
  }

  const [loadingClaim, setLoadingClaim] = useState(false);
  const [openDialogBenefit, setOpenDialogBenefit] = useState(false);
  const [currentMember, setCurrentMember] = useState(null);
  const [nameMember, setNameMember] = useState('');


  const formatTitleCase = (str:any) => {
    if (str) {
      return str.replace(/\w\S*/g, (txt:any) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
    }
    return ''; // Mengembalikan string kosong jika input adalah null atau undefined
  };

  return (
    <>
      <TableComponent
        headCells={headCells}
        rows={data}
        orders={orders}
        paginations={paginations}
        loadings={loadings}
        params={params}
        searchs={searchs}
        filterStatus={filterStatus}
        // filterStartDate={filterStartDate}
        // filterEndDate={filterEndDate}
      />
       <MuiDialog
        title={{name: nameMember}}
        openDialog={openDialogBenefit}
        setOpenDialog={setOpenDialogBenefit}
        content={
          DialogMember(currentMember, () => setOpenDialogBenefit(false))
        }
        maxWidth="sm"
      /> 
      <MuiDialog
        title={{name: dataViewClaimSubmit?.full_name}}
        openDialog={openDialogClaimSubmit}
        setOpenDialog={setOpenDialogClaimSubmit}
        content={
          <DialogClaimSubmit
            member={dataViewClaimSubmit}
            getData={getData}
            onClose={(data:any, getData:any) => {
              console.log('Data returned:', data);
              getData();
              setOpenDialogClaimSubmit(false);
            }}
            handleSubmitSuccess={() => {
            }}
          />
        }
        maxWidth="sm"
      />   
    </>
  );
}