// @mui
import { Box, Button, Card, Collapse, IconButton, InputLabel, MenuItem, OutlinedInput, Paper, Grid, Select, SelectChangeEvent, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Badge, Tab, Tabs, CardHeader, Stack, Menu, ButtonGroup, Pagination } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import BasePagination from '../../../components/BasePagination';
import FormulariumRow from "./FormulariumRow";
import { MasterFormularium } from "./Type";

export default function List() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  
  // Default data
  const [dataTableRow, setDataTableRow] = useState<MasterFormularium[] | null>(null)
  const [dataTableIsLoading, setDataTableLoading] = useState(true);
  const [dataTableData, setDataTableData] = useState<LaravelPaginatedData>({
    current_page: 1,
    data: [],
    path: "",
    first_page_url: "",
    last_page: 1,
    last_page_url: "",
    next_page_url: "",
    prev_page_url: "",
    per_page: 10,
    from: 0,
    to: 0,
    total: 0
  });

  const loadDataTableData =async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/master/formularium-template', { params: filter });
    console.log(response.data);
    console.log(response.data.data)
    setDataTableLoading(false);

    setDataTableData(response.data);
    setDataTableRow(response.data.data);
  }

  const applyFilter = async (searchFilter: string) => {
    await loadDataTableData({'search' : searchFilter });
    setSearchParams({ 'search' : searchFilter })
  }

  const handlePageChange = (event : ChangeEvent, value: number) => {
    const filter = Object.fromEntries([...searchParams.entries(), ['page', value]]);
    loadDataTableData(filter);
    setSearchParams(filter);
  }

  useEffect(() => {
    loadDataTableData();
  }, [])

  function SearchInput(props: any) {
    const searchInput = useRef<HTMLInputElement>(null);
    const [searchText, setSearchText] = useState("");

    const handleSearchChange = (event: any) => {
      const newSearchText = event.target.value ?? ""
      setSearchText(newSearchText)
    }

    const handleSearchSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText);
    }

    useEffect(() => {
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams])

    return (
      <form onSubmit={handleSearchSubmit} style={{width: '100%'}}>
        <TextField
          id='search-input'
          ref={searchInput}
          label='Search'
          variant='outlined'
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
        />
      </form>
    )
  }

  function SearchCreate(props: any) {
    return (
      <div>
        <Stack direction={'row'} spacing={2} sx={{p:2}}>
          <SearchInput onSearch={applyFilter}/>
          <Button
            id='create-button'
            variant='contained'
            startIcon={<AddIcon />}
            onClick={() => navigate('/master/formularium-template-v2/create')}
            sx={{
              p: 1.8,
              width: '200px',
              backgroundColor: '#19BBBB', color: '#FFF',
              "&:hover":{
                backgroundColor: "#19BBBB", color: '#FFF'
              },
            }}
          >
            Create
          </Button>
        </Stack>
      </div>
    )
  }
  
  const headStyle = {
    fontWeight: 'bold'
  }

  return (
    <React.Fragment>
      <Stack>
        <SearchCreate />
        <Card>
          <TableContainer component={Paper}>
            <Table aria-label='collapsible table'>
              <TableHead>
                <TableRow>
                  <TableCell align='left' width={50}></TableCell>
                  <TableCell align='left' style={headStyle}>Name</TableCell>
                  <TableCell align='left' style={headStyle}>Description</TableCell>
                  <TableCell align='center' style={headStyle} width={100}></TableCell>
                </TableRow>
              </TableHead>
              {dataTableIsLoading ? (
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={4} align='center'>
                      Loading
                    </TableCell>
                  </TableRow>
                </TableBody>
              ) : dataTableData.data.length == 0 ? (
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={4} align='center'>
                      No Data
                    </TableCell>
                  </TableRow>
                </TableBody>
              ) : (
                <TableBody>
                  {dataTableRow?.map(item => (
                    <FormulariumRow props={item}/>
                  ))}
                </TableBody>
              )}
            </Table>
          </TableContainer>
          <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
        </Card>
      </Stack>
    </React.Fragment>
  )
}