// @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 axiosInstance from '../../../../utils/axios';
import axios from '../../../../utils/axios';
import { LaravelPaginatedData } from '../../../../@types/paginated-data';
import BasePagination from '../../../../components/BasePagination';
import CategoryRow from './CategoryRow'
import {CorporateFormulariumList} from "./Types";


export default function List() {
  const navigate = useNavigate();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [dataRow, setDataRow] = useState<CorporateFormulariumList[] | null>(null);

  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = React.useState(true);
  const [dataTableData, setDataTableData] = React.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,
  });

  // Load Data
  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const resp = await axios.get(`/corporates/${corporate_id}/formulariums`, {params: filter});
    setDataTableLoading(false);
    setDataTableData(resp.data);
    setDataRow(resp.data.data);
  }

  const applyFilter = async (searchFilter: any) => {
    await loadDataTableData({ search: searchFilter });
    setSearchParams({ search: searchFilter });
    console.log("here")
  };

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

  useEffect(() => {
    loadDataTableData();
    console.log(dataTableData);
    console.log(dataRow);
  }, []);

  
  function SearchInput(props: any) {
     // SEARCH
    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); // Trigger to Parent
    }

    useEffect(() =>  { // Trigger First Search
      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(`/corporates/${corporate_id}/formulariums/create`)}
            sx={{
              p: 1.8,
              backgroundColor: '#19BBBB', color: '#FFF',
              "&:hover":{
                backgroundColor: '#19BBBB', color: '#FFF',
              },
              width: '200px'
            }}
          >
            Create
          </Button>
        </Stack>
      </div>
    )
  }

  const headStyle = {
    fontWeight: 'bold',
  };
  
  return(
    <React.Fragment>
      <Stack>
        <SearchCreate />
          <Card>
            {/* The Main Table */}
            <TableContainer component={Paper}>
              <Table aria-label="collapsible table">
                <TableHead>
                  <TableRow>
                    <TableCell align='left' width={50}></TableCell>
                    <TableCell style={headStyle} align="left">Formularium Name</TableCell>
                    <TableCell style={headStyle} align="left">Description</TableCell>
                    <TableCell style={headStyle} align="center" 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>
                    {dataRow?.map(item => (
                      <CategoryRow {...item}/>
                    ))}
                  </TableBody> 
                )}             
              </Table>
            </TableContainer>
            <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
          </Card>
      </Stack>
    </React.Fragment>
  )
}