import { DataTable } from '@/components/ui/DataTable';
import { getColumns } from './Column';
import { apiConfig } from '@/config/api.config';
import axios, { AxiosResponse } from 'axios';
import html2canvas from 'html2canvas';
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, useRef } 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';
import { toAbsoluteUrl } from '@/utils';
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);
  const [barcode, setBarcode] = useState('');
  // const [selectedMember, setSelectedMember] = useState(initBalance);

  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 = async (data: any) => {
    await getQrCode(data.id);
    setFormData(data)
    setDialogType('update');
    setIsDialogOpen(true);
  };

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

  async function getQrCode(customerId:any): Promise<void> {
    try {
      setBarcode(``)
      let getToken = await axios.get(`${BASE_URL}/token/get`, { params: { id: customerId }});
      console.log(getToken.data.data);
      setBarcode(getToken.data.data.qrCode);
    } catch (error: any) {
      toast.warning(error.message)
      console.log(error);
    } finally {
      // setBarcode(`https://miro.medium.com/v2/resize:fit:250/1*DcceOyLkzU--EzP4PYKd_g.png`)
    }
  }

  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 flex justify-center items-center">
            <div className="relative">
              <PaymentCard barcode={barcode} customerId={formData.id} agent_name={formData.agent_name}/>
            </div>
          </DialogContent>
        </Dialog>
      </Container>
    </>
  );
};

const PaymentCard = ({ barcode, agent_name, customerId }:any) => {
  const cardRef:any = useRef(null);

  const waitForImageLoad = (img: HTMLImageElement): Promise<void> => {
    return new Promise((resolve) => {
      if (img.complete && img.naturalHeight !== 0) {
        resolve();
      } else {
        toast.warning(`No QR Code`)
        img.onload = () => resolve();
      }
    });
  };


  const handleDownload = async () => {
    if (!cardRef.current) return;

    const img = cardRef.current.querySelector('img');
    if (img) {
      await waitForImageLoad(img);
    } else {
      return toast.warning(`No QR Code`)
    }

    const canvas = await html2canvas(cardRef.current, {
      useCORS: true,
      allowTaint: false,
      backgroundColor: 'white',
      scale: 2,
    });

    const dataUrl = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = `${agent_name}_barcode_card.png`;
    link.click();
  };

  return (
    <div className="flex flex-col items-center">
      {/* Card content to render */}
      <div ref={cardRef}
        className="relative w-[400px] h-[550px] rounded-xl overflow-hidden shadow-xl bg-white"
      >
        <div className="absolute inset-0 z-10 flex flex-col items-center justify-start pt-[100px] px-4 text-center">
          <p className="text-[24px] font-semibold text-[#5b0066] mb-5">
            {agent_name}
          </p>
          {barcode && (
            <img
              src={barcode}
              alt="Barcode"
              className="w-80 h-80 object-contain mb-2"
            />
          )}
        </div>
      </div>

      {/* Download Button */}
      <button
        onClick={handleDownload}
        className="mt-4 border border-red-400 text-red-500 px-4 py-1 rounded hover:bg-red-50 text-sm"
      >
        Print QR
      </button>
    </div>
  );
};

export default AgentBalance;
