// @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';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import HistoryIcon from '@mui/icons-material/History';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { enqueueSnackbar } from 'notistack';

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>
          <TableCell align="center">{row.id ? row.id : '-'}</TableCell>
          <TableCell align="left">{row.code ? row.code : '-'}</TableCell>
          <TableCell align="left">{row.name ? row.name : '-'}</TableCell>
          <TableCell align="left">{row.description ? row.description : '-'}</TableCell>
          <TableCell align="left">
          <TableMoreMenu actions={
            <>
              <MenuItem onClick={() => navigate ('')}>
                <FindInPageOutlinedIcon />
                Details
              </MenuItem>
              <MenuItem onClick={() => handleEditData(row)}>
                <EditOutlinedIcon />
                Edit
              </MenuItem>
              <MenuItem onClick={() => handleEditDataStatus(row)}>
                <CachedOutlinedIcon />
                Update Status
              </MenuItem>
              <MenuItem onClick={() => navigate ('')}>
                <HistoryIcon />
                History
              </MenuItem>
            </>
            }
          />
          </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,
    });
    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();
  }, []);

  // Dialog for devisions
  const [openDialog, setOpenDialog] = useState(false);
  //validation dialog
  const [nameField, setNameField] = useState('');
  const [nameFieldError, setNameFieldError] = useState('');
  const [codeField, setCodeField] = useState('');
  const [codeFieldError, setCodeFieldError] = useState('');
  const [descriptionField, setDescriptionField] = useState('');
  // ID for edit data
  const [idField, setIdField] = useState('');

  const isRequiredFieldsFilled = () => {
    return nameField.trim() !== '' && codeField.trim() !== '';
  };

  const handleAddData = () => {
    setOpenDialog(true);
  }

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setNameField('');
    setCodeField('');
    setDescriptionField('');
    setIdField('');
  }

  const handleSaveData = () => {
    const addData = {
      code: codeField,
      name: nameField,
      description: descriptionField,
    };
    // Check conditions add or update data
    if(idField)
    {
      // Update data
      axios
      .put('/corporates/'+corporate_id+'/divisions/'+idField+'', addData)
      .then((response) => {
        enqueueSnackbar('Data saved successfully', { variant: 'success' });
        loadDataTableData();
        handleCloseDialog();
      })
      .catch((error) => {
        enqueueSnackbar('Failed to add data', { variant: 'error' });
      });
    }
    else{
      // Save data
      axios
      .post('/corporates/'+corporate_id+'/divisions', addData)
      .then((response) => {
        enqueueSnackbar('Data saved successfully', { variant: 'success' });
        loadDataTableData();
        handleCloseDialog();
      })
      .catch((error) => {
        enqueueSnackbar('Failed to add data', { variant: 'error' });
      });
    }
  }
  //Edit data
  const handleEditData = (data) => {
    setIdField(data.id)
    setNameField(data.name);
    setCodeField(data.code);
    setDescriptionField(data.description);
    setOpenDialog(true);    
  }
  // End dialog for devisions

  // Dialog for update status devisions
  const [openDialogStatus, setOpenDialogStatus] = useState(false);
  // Active for update status
  const [activeField, setActiveField] = useState('');
  const handleCloseDialogStatus = () => {
    setOpenDialogStatus(false);
    setNameField('');
    setCodeField('');
    setDescriptionField('');
    setIdField('');
    setActiveField('');
  }

  const handleSaveDataStatus = () => {
    
  }

  const handleEditDataStatus = (data) => {
    setIdField(data.id)
    setNameField(data.name);
    setCodeField(data.code);
    setDescriptionField(data.description);
    setActiveField(data.active);
    setOpenDialogStatus(true);    
  }
  // End dialog for update status devisions

  

  return (
    <Stack>
      <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
        <SearchInput onSearch={applyFilter} />
        <Button
          component="button"
          id="upload-button"
          startIcon={<AddIcon />}
          sx={{ p: 1.8, color: '#FFFFFF', backgroundColor: '#19BBBB', width: '125px', height: '48px' }}
          onClick={handleAddData}
        >
          Create
        </Button>
      </Stack>
      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableHead>
              <TableRow>
                <TableCell sx={{width: '10%'}} align="center">
                  <Typography variant='subtitle2'>ID</Typography>
                </TableCell>
                <TableCell sx={{width: '10%'}} align="left">
                  <Typography variant='subtitle2'>Code</Typography>
                </TableCell>
                <TableCell sx={{width: '20%'}} align="left">
                  <Typography variant='subtitle2'>Name</Typography>
                </TableCell>
                <TableCell sx={{width: '50%'}} align="left">
                  <Typography variant='subtitle2'>Description</Typography>
                </TableCell>
                <TableCell sx={{width: '10%'}} align="left">
                </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>
                {dataTableData.data.map((row) => (
                  <Row key={row.code} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>
        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      </Card>
      {/* Dialog */}
      <Dialog open={openDialog} onClose={handleCloseDialog} fullWidth={true}>
        <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Stack direction="row" alignItems='center' spacing={1}>
                {idField ? (
                  <>
                    <Typography variant="h6">Edit Data</Typography>
                  </>
                ): (
                  <>
                    <Typography variant="h6">Create Data</Typography>
                  </>
                )}
                
              </Stack>
              <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialog}>
                <CloseIcon />
              </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent>
        <Stack spacing={2} sx={{marginTop: 2}}>
          <TextField
            label="Code"
            required
            value={codeField ? codeField : ''}
            onChange={(e) =>{
              setCodeField(e.target.value);
              setCodeFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
            }}
            fullWidth
            inputProps={{ maxLength: 50 }}
            error={!!codeFieldError}
            helperText={codeFieldError}
          />
          <TextField
            label="Name"
            required
            value={nameField ? nameField : ''}
            onChange={(e) =>{
              setNameField(e.target.value);
              setNameFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
            }}
            fullWidth
            inputProps={{ maxLength: 50 }}
            error={!!nameFieldError}
            helperText={nameFieldError}
          />
          <TextField
            label="Description"
            value={descriptionField ? descriptionField : ''}
            onChange={(e) =>{
              setDescriptionField(e.target.value);
            }}
            fullWidth
            inputProps={{ maxLength: 255 }}
          />
        </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Cancel</Button>
          <Button onClick={handleSaveData} variant="contained" color="primary" disabled={!isRequiredFieldsFilled()}>Save</Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Update Status */}
      <Dialog open={openDialogStatus} onClose={handleCloseDialogStatus} fullWidth={true}>
        <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Stack direction="row" alignItems='center' spacing={1}>
                <Typography variant="h6">Update Status</Typography>
              </Stack>
              <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogStatus}>
                <CloseIcon />
              </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <Stack spacing={2} padding={2}>
            <Typography variant='body1'>Are you sure to inactive this division ?</Typography>
            <Card>
              <Stack direction='row' spacing={2}>
                <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Code</Typography>
                <Typography variant='subtitle2' sx={{width: '70%'}}>{codeField}</Typography>
              </Stack>
            </Card>
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialogStatus}>Cancel</Button>
          <Button onClick={handleSaveDataStatus} variant="contained" color="error">Inactive</Button>
        </DialogActions>
      </Dialog>

    </Stack>
  );
}
