import { DataTable } from '@/components/ui/DataTable';
import { getColumns } from './Column';
import { apiConfig } from '@/config/api.config';
import axios, { AxiosResponse } from 'axios';
import { Helmet } from 'react-helmet';
import {
  DialogContent,
  MenuItem,
  Radio,
  RadioGroup,
  FormControlLabel,
  FormControl,
  Dialog,
  DialogTitle,
  Typography,
  Button,
  Box,
  Breadcrumbs,
  Link
} from '@mui/material';
import { useState, useEffect } from 'react';
import CloseIcon from '@mui/icons-material/Close';
import Divider from '@mui/material/Divider';
import ConfirmDialog from '@/components/confirm';
import { toast } from 'sonner';
import { Container, DataGridLoader, DataGridProvider, LoaderTransparant } from '@/components';
import { ListToolBar } from './ListToolbar';
import { RefreshCw } from 'lucide-react';
import { setgroups } from 'process';
const BASE_URL = apiConfig.service_customer;

let initBalance = {
  id: '',
  msisdn: '',
  fullname: '',
  username: '',
  agent_name: '',
  balance_emoney: '',
  balance_merchant: '',
  balance_point: '',
  balance_deposit: ''
};

const AgentBalance = () => {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [dataBalance, setDataBalance] = useState([]);
  const [formData, setFormData] = useState(initBalance);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dialogType, setDialogType] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isReloading, setIsReloading] = useState(false);

  useEffect(() => {
   fetchAgentBalance();
  }, []);

  async function fetchAgentBalance(): Promise<void> {
    setIsReloading(true);
    try {
      let balances = await axios.get(`${BASE_URL}/customer/agent-balance`, {
        params: {
          limit: 20,
          page: 1,
          with_deleted: false,
          order_field: 'created_at',
          order_direction: 'DESC'
        }
      });
      let temp = 1;
      let resBalance = balances.data.data.list.map((el: any) => {
        el.no = temp++;
        if (!el.agent_name) el.agent_name = ''
        return el;
      });
      setDataBalance(resBalance);
    } catch (error: any) {
      alert(error.message);
      console.log(error);
    } finally {
      setIsReloading(false);
    }
  }

  const openDialog = () => setIsDialogOpen(true);
  const closeDialog = () => {
    setIsDialogOpen(false);
    setFormData(initBalance);
  };

  function createGroup() {
    setDialogType('create');
    openDialog();
  }

  const handleUpdate = (group: any) => {
    setDialogType('update');
    setIsDialogOpen(true);
  };

  const handleReload = () => {
    setIsReloading(true);
    fetchAgentBalance();
  };

  if (loading) return <LoaderTransparant />;

  return (
    <>
      <Helmet>
        <title>TPAY | Agent Balance</title>
      </Helmet>
      <Container>
        {/* <ConfirmDialog
          open={dialogOpen}
          onClose={() => setDialogOpen(false)}
          title="Confirm Action"
          content={''}
          onYes={handleYes}
          onNo={() => setDialogOpen(false)}
        /> */}
        <h1 className="text-xl font-medium leading-none text-gray-900 mb-5">Agent Balances</h1>
        <Breadcrumbs>
          <Link underline="none" color="inherit" href="/">
            <span className="text-sm hover:underline">Dashboard</span>
          </Link>

          <Link underline="none" color="inherit">
            <span className="text-sm">Members</span>
          </Link>

          <Link underline="none" color="inherit">
            <span className="text-sm">Agent Balances</span>
          </Link>
        </Breadcrumbs>

        <div className="grid gap-5 lg:gap-7.5 mt-5 relative">
          {isReloading && (
            <DataGridLoader />
          )}
          <DataGridProvider
            data={dataBalance}
            columns={getColumns(handleUpdate)}
            pagination={{ size: 10 }}
            toolbar={
              <ListToolBar
                createGroup={createGroup}
                onReload={handleReload}
                isReloading={isReloading}
              />
            }
            layout={{ card: true }}
            serverSide={false}
            onRowSelectionChange={(selected, table: any) => {
              const selectedRow = table.getSelectedRowModel().rows[0];
              if (selectedRow) handleUpdate(selectedRow.original);
            }}
          />
        </div>
        {/* </div> */}

        {/* <Dialog open={isDialogOpen} onClose={closeDialog}>
          <DialogContent className="w-full">
            <div className="flex justify-between">
              <DialogTitle>
                {dialogType === 'create' ? 'Create New Group' : 'Update Group'}
              </DialogTitle>
              <Box display="flex" justifyContent="flex-end">
                <Button
                  variant="outlined"
                  sx={{ borderColor: 'white', color: 'grey' }}
                  onClick={closeDialog}
                >
                  <CloseIcon />
                </Button>
              </Box>
            </div>
            <Divider />
            <div className="p-5 mt-5">
              <form onSubmit={handleSubmit} className="flex flex-col gap-4 w-full">
                <div className="grid grid-cols-4 items-center gap-4 w-full">
                  <label className="form-label text-sm">
                    <span className="text-red-500">*</span>Group Name:
                  </label>
                  <input
                    type="text"
                    name="groupName"
                    className="input w-full col-span-3"
                    value={formData.groupName}
                    onChange={handleChange}
                  />
                </div>
                <div className="grid grid-cols-4 items-center gap-4 w-full">
                  <label className="form-label text-sm">
                    <span className="text-red-500">*</span>Active Status:
                  </label>
                  <FormControl>
                    <RadioGroup name="status" row value={formData.status} onChange={handleChange}>
                      <FormControlLabel
                        value="Y"
                        checked={formData.status === 'Y'}
                        control={<Radio />}
                        label="Yes"
                      />
                      <FormControlLabel
                        value="N"
                        checked={formData.status === 'N'}
                        control={<Radio />}
                        label="No"
                      />
                    </RadioGroup>
                  </FormControl>
                </div>
                <div className="grid grid-cols-4 items-center gap-4 w-full">
                  <label className="form-label text-sm">
                    <span className="text-red-500">*</span>Description:
                  </label>
                  <input
                    type="text"
                    name="description"
                    className="input w-full col-span-3"
                    value={formData.description}
                    onChange={handleChange}
                  />
                </div>
                <Button type="submit">Submit</Button>
              </form>
            </div>
          </DialogContent>
        </Dialog> */}
      </Container>
    </>
  );
};

export default AgentBalance;
