/* ---------------------------------- @mui ---------------------------------- */
import { styled } from '@mui/material/styles';
import {
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Button,
  TableSortLabel,
  Box,
  IconButton,
  Card,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  SelectChangeEvent,
  Stack,
  Typography,
  LinearProgress,
  linearProgressClasses,
} from '@mui/material';
import { visuallyHidden } from '@mui/utils';
/* ---------------------------------- axios --------------------------------- */
import axios from '@/utils/axios';
/* ---------------------------------- react --------------------------------- */
import { useContext, useEffect, useState } from 'react';
/* -------------------------------- component ------------------------------- */
import Iconify from '@/components/Iconify';
import BaseTablePagination from '@/components/BaseTablePagination';
/* ---------------------------------- theme --------------------------------- */
import palette from '@/theme/palette';
import { useSearchParams } from 'react-router-dom';
// import { UserCurrentCorporateContext } from '@/contexts/UserCurrentCorporate';
import { fSplit } from '@/utils/formatNumber';
import { Chip } from '@mui/material';
import { enqueueSnackbar } from 'notistack';
import DialogDetailClaim from '@/components/dialogs/DialogDetailClaim';

/* ---------------------------------- types --------------------------------- */
type PaginationTableProps = {
  current_page: number;
  from: number;
  last_page: number;
  links: [];
  path: string;
  per_page: number;
  to: number;
  total: number;
};

type DataTableProps = {
  fullName: string;
  memberId: string;
  division: string;
  limit: {
    current: number;
    total: number;
    percentage: number;
  };
  status: string;
};

type Order = 'asc' | 'desc';

interface HeadCell {
  id: string;
  align: string;
  label: string;
  isSort: boolean;
}

interface EnhancedTableProps {
  onRequestSort: (event: React.MouseEvent<unknown>, property: string) => void;
  order: Order;
  orderBy: string;
}

type DivisionDataProps = {
  id: number;
  name: string;
};
/* -------------------------------------------------------------------------- */

/* --------------------------------- styled --------------------------------- */
const BorderLinearProgress = styled(LinearProgress)(({ theme }) => ({
  height: 10,
  borderRadius: 6,
  [`&.${linearProgressClasses.colorPrimary}`]: {
    backgroundColor: '#D1F1F1',
  },
  [`& .${linearProgressClasses.bar}`]: {
    borderRadius: 6,
    backgroundColor: theme.palette.primary.main,
  },
}));
/* -------------------------------------------------------------------------- */

/* -------------------------- enchanced table head -------------------------- */
const headCells: readonly HeadCell[] = [
  {
    id: 'code',
    align: 'left',
    label: 'Request Code',
    isSort: true,
  },
  {
    id: 'member.name',
    align: 'center',
    label: 'Member',
    isSort: false,
  },
  {
    id: 'submission_date',
    align: 'center',
    label: 'Submission Date',
    isSort: true,
  },
  {
    id: 'log_url',
    align: 'right',
    label: 'Download LOG',
    isSort: false,
  },
  {
    id: 'status',
    align: 'right',
    label: 'Status',
    isSort: false,
  },
];

function EnhancedTableHead({ order, orderBy, onRequestSort }: EnhancedTableProps) {
  const createSortHandler = (property: string) => (event: React.MouseEvent<unknown>) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            sortDirection={orderBy === headCell.id ? order : false}
            // @ts-ignore
            align={headCell.align}
            sx={{ padding: 2 }}
          >
            {headCell.isSort ? (
              <TableSortLabel
                active={orderBy === headCell.id}
                direction={orderBy === headCell.id ? order : 'asc'}
                onClick={createSortHandler(headCell.id)}
              >
                {headCell.label}
                {orderBy === headCell.id ? (
                  <Box component="span" sx={visuallyHidden}>
                    {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                  </Box>
                ) : null}
              </TableSortLabel>
            ) : (
              headCell.label
            )}
          </TableCell>
        ))}
        <TableCell align="center">{''}</TableCell>
      </TableRow>
    </TableHead>
  );
}
/* -------------------------------------------------------------------------- */

// TODO Don't use emit
export default function TableList(props: any) {
  const [dataTable, setDataTable] = useState([]);
  const [paginationTable, setPaginationTable] = useState<PaginationTableProps>({
    current_page: 0,
    from: 0,
    last_page: 0,
    links: [],
    path: '',
    per_page: 0,
    to: 0,
    total: 0,
  });

  const [isLoading, setIsLoading] = useState(true);
  const [searchParams, setSearchParams] = useSearchParams();
  const [appliedParams, setAppliedParams] = useState({});

  const [order, setOrder] = useState<Order>('asc');
  const [orderBy, setOrderBy] = useState('name');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  /* ------------------------------- handle sort ------------------------------ */
  const handleRequestSort = async (event: React.MouseEvent<unknown>, property: string) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
    const params = Object.fromEntries([
      ...searchParams.entries(),
      ['order', isAsc ? 'desc' : 'asc'],
      ['orderBy', property],
    ]);
    setAppliedParams(params);
  };
  /* -------------------------------------------------------------------------- */

  /* ----------------------------- status field ----------------------------- */
  const [filterStatus, setFilterStatus] = useState('All');
  const [statusOptions, setStatusOptions] = useState(['All', 'Requested', 'Approved', 'Declined']);

  const handleStatusChange = (event: SelectChangeEvent) => {
    setFilterStatus(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.toLowerCase() as string],
      ]);
      setAppliedParams(params);
    }
  };
  /* -------------------------------------------------------------------------- */

  /* ------------------------------ Search field ------------------------------ */
  const [searchText, setSearchText] = useState('');
  const [searchStatus, setSearchStatus] = useState('all');

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

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

    await new Promise((resolve) => setTimeout(resolve, 500));
    setIsLoading(false);
  };
  /* -------------------------------------------------------------------------- */

  /* ------------------------ button change pagination ------------------------ */
  const onPageChangeHandle = async (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    setIsLoading(true);
    const params = Object.fromEntries([...searchParams.entries(), ['page', newPage + 1]]);
    setPage(newPage);
    await new Promise((resolve) => setTimeout(resolve, 500));
    setAppliedParams(params);
    setIsLoading(false);
  };
  /* -------------------------------------------------------------------------- */

  /* --------------------------- row page per limit --------------------------- */
  const onRowsPerPageChangeHandle = async (event: React.ChangeEvent<HTMLInputElement>) => {
    setIsLoading(true);
    searchParams.delete('page');
    const params = Object.fromEntries([
      ...searchParams.entries(),
      ['per_page', parseInt(event.target.value, 10)],
    ]);
    setRowsPerPage(parseInt(event.target.value, 10));
    await new Promise((resolve) => setTimeout(resolve, 500));
    setAppliedParams(params);
    setIsLoading(false);
  };
  /* -------------------------------------------------------------------------- */

  useEffect(() => {
    (async () => {
      setIsLoading(true);

      // const division = await axios.get(`${corporateValue}/division`);
      // setDivisionData(division.data);

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

      const response = await axios.get(`/claim-requests`, {
        params: { ...params },
      });

      setSearchParams(params);
      setDataTable(response.data.data.data);
      setPaginationTable(response.data.data);
      setRowsPerPage(response.data.data.per_page);
      setIsLoading(false);

      // TODO Remove This
      props.dataLoaded(response.data.data.data);
    })();
  }, [appliedParams, searchParams, order, orderBy, setSearchParams]);

  // ---------------------------------------------------------
  // Dialog Detail Claim
  const [openDialogDetailClaim, setOpenDialogDetailClaim] = useState(false);
  const [loadingClaimDetail, setLoadingClaimDetail] = useState(true);
  const [currentClaim, setCurrentClaim] = useState(null);

  function handleShowClaim(claimRequest) {
    setLoadingClaimDetail(true);
    setOpenDialogDetailClaim(true);

    axios.get(`/claim-requests/${claimRequest.id}`)
      .then(({data}) => {
        console.log(data.data);
        setCurrentClaim(data.data);
        setLoadingClaimDetail(false);
      })
      .catch((err) => {
        enqueueSnackbar(err.message, {variant: 'error'})
      })
  }

  // -----------------------------------------------------------------
  // Download LOG
  async function handleDownloadLog(claimRequest) {
    return axios
      .get(`claim-requests/${claimRequest.id}/log`, {
        responseType: 'blob',
      })
      .then((response) => {
        window.open(URL.createObjectURL(response.data));
        // setLoadingLog(false);
      })
      // .then((blobFile) => {
      //   new File([blobFile], 'asdads.pdf', { type: blobFile.type })
      //   setLoadingLog(false);
      // })
      .catch((response) => {
        enqueueSnackbar(response.message, { variant: 'error' });
        // setLoadingLog(false);
      });
  }

  return (
    <Card>
      <Grid container>
        {/* Field 1 */}
        <Grid item xs={12} paddingX="24px" paddingY="20px">
          <Grid container spacing={2}>
            <Grid item xs={12} lg={3} xl={2}>
              {/* <FormControl fullWidth>
                <InputLabel id="simple-division-select-lable">Division</InputLabel>
                <Select
                  labelId="simple-division-select-lable"
                  id="division-select-lable"
                  value={divisionValue}
                  label="Division"
                  onChange={handleDivisionChange}
                >
                  <MenuItem value="all">All</MenuItem>
                  {divisionData.map((row: DivisionDataProps, index) => (
                    <MenuItem key={index} value={row.id}>
                      {row.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl> */}
            </Grid>
            <Grid item xs={12}>
              <form onSubmit={handleSearchSubmit}>
                <Grid container spacing={2}>
                  <Grid item xs={9}>
                    <TextField
                      id="search-input"
                      label="Search"
                      variant="outlined"
                      onChange={(event) => setSearchText(event.target.value)}
                      value={searchText}
                      fullWidth
                    />
                  </Grid>
                  <Grid item xs={3}>
                    <FormControl fullWidth>
                      <InputLabel id="demo-simple-select-label">Status</InputLabel>
                      <Select
                        labelId="demo-simple-select-label"
                        id="demo-simple-select"
                        value={filterStatus}
                        label="Status"
                        onChange={handleStatusChange}
                        sx={{ width: '100%' }}
                      >
                        {statusOptions &&
                          statusOptions.map((option, index) => (
                            <MenuItem
                              value={option}
                              sx={{ textTransform: 'capitalize' }}
                              key={index}
                            >
                              {option}
                            </MenuItem>
                          ))}
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>
                <input type="submit" style={{ display: 'none' }}></input>
              </form>
            </Grid>
          </Grid>
        </Grid>
        {/* End Field 1 */}
        {/* Field 2 */}
        <Grid item xs={12}>
          <TableContainer component={Paper}>
            <Table aria-label="collapsible table" size="small">
              <EnhancedTableHead
                order={order}
                orderBy={orderBy}
                onRequestSort={handleRequestSort}
              />
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={6} align="center">
                      Loading . . .
                    </TableCell>
                  </TableRow>
                ) : dataTable.length >= 1 ? (
                  dataTable.map((row: DataTableProps, index) => (
                    <TableRow key={index}>
                      <TableCell align="left">{row.code}</TableCell>
                      <TableCell align="center">{row.member?.full_name ?? ''}</TableCell>
                      <TableCell align="center">{row.submission_date}</TableCell>
                      <TableCell align="right">
                        {row.status == 'approved' ? (
                          <Button
                            sx={{
                              backgroundColor: palette.light.grey[400],
                              color: palette.dark.grey[900],
                              paddingY: 0,
                              '&:hover': {
                                backgroundColor: 'rgba(84, 214, 44, 0.32)',
                                color: palette.dark.success.darker,
                              },
                            }}
                            onClick={() => {
                              handleDownloadLog(row);
                            }}
                          >
                            Download LOG
                          </Button>
                        ) : (
                          <Typography>Belum Tersedia</Typography>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <Chip
                          color={
                            row.status == 'requested'
                              ? 'default'
                              : row.status == 'approved'
                              ? 'success'
                              : row.status == 'declined'
                              ? 'error'
                              : 'default'
                          }
                          size="small"
                          label={row.status ?? 'unknown'}
                          sx={{ textTransform: 'capitalize' }}
                        />
                      </TableCell>

                      <TableCell align="right">
                        <IconButton
                          onClick={() => {
                            handleShowClaim(row);
                          }}
                        >
                          <Iconify icon="eva:eye-fill" />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={6} align="center">
                      No Data Found
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>

          {/* Pagination */}
          <BaseTablePagination
            count={paginationTable.total}
            onPageChange={onPageChangeHandle}
            page={page}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={onRowsPerPageChangeHandle}
          />
        </Grid>
        {/* End Field 2 */}
      </Grid>

      
      
      <DialogDetailClaim
        openDialog={openDialogDetailClaim}
        setOpenDialog={setOpenDialogDetailClaim}
        title={{ name: 'Claim Request Detail' }}
        data={{ claim: currentClaim, isLoading: loadingClaimDetail, handleDownloadLog }}
      ></DialogDetailClaim>

    </Card>
  );
}
