// @mui
import { Box, Button, Card, Collapse, IconButton, InputLabel, MenuItem, OutlinedInput, Paper, Select, SelectChangeEvent, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Badge, Tab, Tabs, CardHeader, Stack, Menu, ButtonGroup } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import AddIcon from '@mui/icons-material/Add';
import UploadIcon from '@mui/icons-material/Upload';
import CancelIcon from '@mui/icons-material/Cancel';
// 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 { CorporatePlan } from '../../../@types/corporates';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import BasePagination from '../../../components/BasePagination';

export default function PlanList() {
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  
  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 handleSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText); // Trigger to Parent
    }

    useEffect(() =>  {
      // console.log('Search Input: useEffect')
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams])

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

  // Called on every row to map the data to the columns
  function createData( plan: CorporatePlan ): CorporatePlan {
    return {
      ...plan,
    }
  }

  // Generate the every row of the table
  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
          <TableCell>
            <IconButton
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell>
          <TableCell align="left">{row.id}</TableCell>
          <TableCell align="left">{row.code}</TableCell>
          <TableCell align="left">{row.name}</TableCell>
          <TableCell align="left">{row.description}</TableCell>
          <TableCell align="right"><Button variant="outlined" color="success" size="small">Active</Button></TableCell>
          <TableCell align="right"><Link to={`/corporates/${row.corporate_id}/divisions/${row.id}/edit`}><Button variant="outlined" color="success" size="small">Edit</Button></Link></TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={10}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ borderBottom: 1 }}>
                <Typography variant="body2" gutterBottom component="div">
                  No Extra Data
                </Typography>
              </Box>
            {false && <Box sx={{ margin: 1 }}>
                <Typography variant="h6" gutterBottom component="div">
                  Rules
                </Typography>
                <Table size="small" aria-label="purchases">
                  <TableHead>
                    <TableRow>
                      <TableCell>Date</TableCell>
                      <TableCell>Customer</TableCell>
                      <TableCell align="right">Amount</TableCell>
                      <TableCell align="right">Total price ($)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {/* {row.history ? row.history.map((historyRow) => ( */}
                      <TableRow key={row.id}>
                        <TableCell component="th" scope="row">{row.start} - {row.end}</TableCell>
                        <TableCell>{row.start}</TableCell>
                        <TableCell align="right">{row.start}</TableCell>
                        <TableCell align="right">{row.start}</TableCell>
                      </TableRow>
                    {/* ))
                    : (
                      <TableRow>
                        <TableCell colSpan={8}>No Data</TableCell>
                      </TableRow>
                      )
                    } */}
                  </TableBody>
                </Table>
              </Box>}
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  // 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
  });

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

    setDataTableData(response.data);
  }

  const headStyle = {
    fontWeight: 'bold',
  };

  const applyFilter = async (searchFilter: any) => {
    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();
  }, [])
  
  return (
    <Stack>
        <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
          <SearchInput onSearch={applyFilter}/>
          <Link to={`/corporates/${corporate_id}/divisions/create`}>
            <Button
              component="button"
              id="upload-button"
              variant='outlined'
              startIcon={<AddIcon />} sx={{ p: 1.8 }}
            >
              Create
            </Button>
          </Link>
        </Stack>

        <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left" />
                <TableCell style={headStyle} align="left">ID</TableCell>
                <TableCell style={headStyle} align="left">Code</TableCell>
                <TableCell style={headStyle} align="left">Name</TableCell>
                <TableCell style={headStyle} align="left">Description</TableCell>
              </TableRow>
            </TableBody>
            {dataTableIsLoading ?
              (
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={8} align="center">Loading</TableCell>
                  </TableRow>
                </TableBody>
              ) : (
                dataTableData.data.length == 0 ? 
                (
                  <TableBody>
                    <TableRow>
                      <TableCell colSpan={8} align="center">No Data</TableCell>
                    </TableRow>
                  </TableBody>
                ) : (
                  <TableBody>
                    {dataTableData.data.map(row => (
                      <Row key={row.code} row={row} />
                    ))}
                  </TableBody>
                )
            )}
          </Table>
        </TableContainer>
        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange}/>
        </Card>
    </Stack>
  );
}
