import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import { Stack, Typography, Switch, Tooltip, Divider, IconButton } from '@mui/material';
import Chip from '@mui/material/Chip';
import React from 'react';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import MainCard from 'components/MainCard';
import { useQuery } from '@tanstack/react-query';
import { gettenantlocations } from './api';
import OpenToast from 'components/third-party/OpenToast';
import axios from 'axios';
import CreateLocation from './CreateLocation';
import TitleCard from 'components/TitleCard';
const columns = [
  { id: 'sno', label: 'S.No', align: 'left' },
  { id: 'locationname', label: 'Location Name', align: 'left' },
  { id: 'locationcontact', label: 'Contact', align: 'left' },
  {
    id: 'locationaddress',
    label: 'Address',
    align: 'left'
  },

  {
    id: 'timing',
    label: 'Timing',
    align: 'center'
  },
  {
    id: 'coordinates',
    label: 'Co-Ordinates',
    align: 'center'
  },
  {
    id: 'action',
    label: 'Actions',
    align: 'right'
  }
];

function Locations() {
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [isLocationDialogOpen, setIsLocationDialogOpen] = React.useState(false);
  const [selectedLocation, setSelectedLocation] = React.useState(null);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  const { data: locationList, refetch: locationListrefetch } = useQuery({
    queryKey: ['locationlistlocation'],
    queryFn: gettenantlocations
  });

  const handleCreateOpen = () => {
    setSelectedLocation(null);
    setIsLocationDialogOpen(true);
  };

  const handleEditOpen = (location) => {
    setSelectedLocation(location);
    setIsLocationDialogOpen(true);
  };

  const handleLocationDialogClose = () => {
    setIsLocationDialogOpen(false);
    setSelectedLocation(null);
  };

  const updateLocation = async (obj) => {
    try {
      let response = await axios.put(`${process.env.REACT_APP_URL2}/tenants/updatetenantlocation`, obj);
      console.log('updateLocation', response);
      OpenToast(response.data.message, 'success', 2000);
      locationListrefetch();
    } catch (err) {
      OpenToast(err.message, 'error', 2500);
    }
  };

  return (
    <Stack>
      <TitleCard title={'Locations'}>
        <Stack>
          <Chip
            variant="combined"
            color="primary"
            size="large"
            icon={<PlusOutlined />}
            label={'       Create Locations'}
            onClick={handleCreateOpen}
          />
        </Stack>
      </TitleCard>
      <MainCard contentSX={{ p: 0 }} sx={{ width: '100%', overflow: 'hidden' }}>
        <TableContainer sx={{ maxHeight: 'calc(100vh - 230px)' }}>
          <Table stickyHeader sx={{ tableLayout: 'auto', width: '100%' }} aria-label="sticky table">
            <TableHead>
              <TableRow>
                {columns.map((column) => (
                  <TableCell
                    key={column.id}
                    align={column.align}
                    sx={{ position: 'sticky !important', p: 2, m: 1, backgroundColor: 'bg.lighter' }}
                  >
                    {column.label}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {locationList?.map((location, index) => (
                <TableRow key={index}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>
                    <Stack>
                      <Typography variant="body1" noWrap>{`${location.suburb}`}</Typography>
                      <Typography variant="caption" color={location.roleid == 1 ? 'error' : 'primary'} sx={{ fontWeight: 1000 }}>{`${
                        location.roleid == 1 ? 'Admin' : 'Locations'
                      } : ${location?.locationid}`}</Typography>
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Stack>
                      <Typography variant="body1">{location.email}</Typography>
                      <Typography variant="body1" color={'secondary'}>
                        {location.contactno}
                      </Typography>
                    </Stack>
                  </TableCell>
                  <TableCell sx={{ whiteSpace: 'nowrap' }}>
                    <Stack>
                      <Typography
                        variant="body1"
                        noWrap
                        sx={{
                          maxWidth: 'auto', // set as per your layout needs
                          width: 'auto',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'wrap'
                        }}
                      >
                        {location.address}
                      </Typography>
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Stack direction="row" spacing={1}>
                      <Chip
                        // label={dayjs(location.opentime).format('hh:mm A')}
                        label={location.opentime}
                        color="warning"
                        variant="combined"
                        sx={{
                          maxWidth: 100,
                          width: '100%'
                        }}
                      />
                      <Chip
                        // label={dayjs(location.closetime).format('hh:mm A') || ''}
                        label={location.closetime}
                        color="warning"
                        variant="combined"
                        sx={{
                          maxWidth: 100,
                          width: '100%'
                        }}
                      />
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Stack direction="row" spacing={1}>
                      <Tooltip title={`lati : ${location.latitude}`}>
                        <Chip
                          label={location.latitude}
                          color="info"
                          variant="combined"
                          sx={{
                            maxWidth: 80,
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            cursor: 'pointer'
                          }}
                        />
                      </Tooltip>
                      <Tooltip title={`long : ${location.longitude}`}>
                        <Chip
                          label={location.longitude}
                          color="info"
                          variant="combined"
                          sx={{
                            maxWidth: 80,
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            cursor: 'pointer'
                          }}
                        />
                      </Tooltip>
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Stack direction="row" spacing={2} alignItems={'center'}>
                      <IconButton onClick={() => handleEditOpen(location)}>
                        <EditOutlined style={{ fontSize: 20, color: 'red' }} />
                      </IconButton>
                      <Switch
                        size="small"
                        checked={location.status == 'Active'}
                        onChange={(e) => {
                          console.log(e.target.checked);
                          updateLocation({ locationid: location.locationid, status: e.target.checked ? 'Active' : 'InActive' });
                        }}
                        name="isActive"
                        color="primary"
                      />
                    </Stack>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />
        <TablePagination
          rowsPerPageOptions={[10, 25, 100]}
          component="div"
          count={locationList?.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
          sx={{ backgroundColor: 'bg.lighter', mb: -2.5 }}
        />
      </MainCard>
      <CreateLocation
        dialogMode
        open={isLocationDialogOpen}
        onClose={handleLocationDialogClose}
        onSuccess={locationListrefetch}
        editLocationData={selectedLocation}
      />
    </Stack>
  );
}
export default Locations;
