// @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, Input, Grid } 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';
import { enqueueSnackbar } from 'notistack';


export default function PlanList() {
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

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

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

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

    const handleStatusChange = (event: any) => {
      const newSearchStatus = event.target.value ?? ''
      console.log('changing to', newSearchStatus)
      setSearchStatus(newSearchStatus)
      // console.log(searchStatus);
      
      const searchFilter = {
        "search" : searchText,
        "status" : newSearchStatus
      };
      
      props.onSearch(searchFilter); 
    }

    const handleSubmit = (event?: any) => {
      event?.preventDefault();
      const searchFilter = {
        "search" : searchText,
        "status" : searchStatus
      };
      
      props.onSearch(searchFilter); // Trigger to Parent
    }

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

    return (
      <form id="search-form" onSubmit={handleSubmit} style={{ width: '100%' }}>
        <Grid container spacing={2}>
          <Grid item xs={9}>
            <TextField id="search-input" ref={searchInput} label="Search" variant="outlined" fullWidth onChange={handleSearchChange} value={searchText}/>
          </Grid>

          <Grid item xs={3}>
          <Select
            label="Status"
            value={searchStatus}
            onChange={handleStatusChange}
            sx={{ width: '100%' }}
          >
            <MenuItem value="active">Active</MenuItem>
            <MenuItem value="inactive">Inactive</MenuItem>
            <MenuItem value="all">All</MenuItem>
            </Select>
          </Grid>
          {/* ITS FUCKING MAGIC, SUBMIT BY ENTER WORKING IF THIS BUTTON IS AVAILABLE */}
          <Button type='submit' variant="outlined" sx={{ p: 1.8, display: 'none' }}>Search</Button>
        </Grid>
      </form>
    );
  }

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

  const handleInactiveAction = (formularium : any) => {
        enqueueSnackbar('Fuck yuo'), { variant: 'error' };
    axios
      .put('/corporates/'+corporate_id+'/formulariums/'+formularium.id+'/activate')
      .then(() => {
        setDataTableData(
          { 
            ...dataTableData, 
            data: dataTableData.data.map((item: any) => {
              if (item.id === formularium.id) {
                return {
                  ...item,
                  status: 'active'
                }
              }
  
              return item;
            })
        })
      })
      .catch((error) => {
        console.log(error)
        enqueueSnackbar(error.data?.message ?? (error.message ?? 'Failed Processing Request'), { variant: 'error' });
      })
  }

  const handleActiveAction = (formularium : any) => {
    axios
      .put('/corporates/'+corporate_id+'/formulariums/'+formularium.id+'/deactivate')
      .then(() => {
        setDataTableData(
          { 
            ...dataTableData, 
            data: dataTableData.data.map((item: any) => {
              if (item.id === formularium.id) {
                return {
                  ...item,
                  status: 'inactive'
                }
              }

              return item;
            })
        })
      })
      .catch((error) => {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      })
  }

  // 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.code}</TableCell>
          <TableCell align="left">{row.atc_code}</TableCell>
          <TableCell align="left">{row.name}</TableCell>
          <TableCell align="left">{row.category_name}</TableCell>
          <TableCell align="left">{row.uom}</TableCell>
          {/* <TableCell align="left">{row.items_count}</TableCell> */}
          <TableCell align="right">{( row.status == 'active' ? 
              <Button variant="outlined" onClick={() => { handleActiveAction(row) }} color="success" size="small">Active</Button> : 
              <Button variant="outlined" onClick={() => { handleInactiveAction(row) }} color="error" size="small">Tidak Digunakan</Button>
            )}</TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell />
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ pb: 2 }}>
                <Typography sx={{ fontWeight: '600', mb: 1 }}>Detail</Typography>
                <Grid container sx={{ pb: 2, mb: 2, borderBottom: 1 }}>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={4}>
                        Description
                      </Grid>
                      <Grid item xs={8}>
                        : {row.description ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        General Indication
                      </Grid>
                      <Grid item xs={8}>
                        : {row.general_indication ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        Composition
                      </Grid>
                      <Grid item xs={8}>
                        : {row.composition ?? '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={4}>
                        Kategori Obat
                      </Grid>
                      <Grid item xs={8}>
                        : {row.kategori_obat ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        BPOM Registration
                      </Grid>
                      <Grid item xs={8}>
                        : {row.bpom_registration ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        Classifications
                      </Grid>
                      <Grid item xs={8}>
                        : {row.classifications ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        Cat For
                      </Grid>
                      <Grid item xs={8}>
                        : {row.cat_for ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        Class
                      </Grid>
                      <Grid item xs={8}>
                        : {row.class ?? '-'}
                      </Grid>
                      <Grid item xs={4}>
                        Manufacturer
                      </Grid>
                      <Grid item xs={8}>
                        : {row.manufacturer ?? '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  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+'/formulariums', { params: filter });
    // console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  }

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

  const applyFilter = async (searchFilter: any) => {
    await loadDataTableData(searchFilter);
    setSearchParams(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}/>
        </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">Code</TableCell>
                <TableCell style={headStyle} align="left">ATC Code</TableCell>
                <TableCell style={headStyle} align="left">Name</TableCell>
                <TableCell style={headStyle} align="left">Category Name</TableCell>
                <TableCell style={headStyle} align="left">UOM</TableCell>
                <TableCell style={headStyle} align="center">Status</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>
  );
}
