import { Container, DataGridInner, DataGridProvider, TDataGridProps } from '@/components';
import { DataTable } from '@/components/ui/DataTable';
import { Table } from '@tanstack/react-table';
import React, { createContext, useContext, useState, useEffect } from 'react';
import { ManageKycContextProvider } from './hooks';
import { getColumns, initialMember } from './Columns';
import { useAuthContext } from '@/auth';
import { LoaderTransparant } from '@/components';
import { apiConfig } from '@/config/api.config';
import ConfirmDialog from '@/components/confirm';
import axios from 'axios';
import { toast } from 'sonner';
const BASE_URL = apiConfig.service_customer;
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
// import CustomerDialog from '../manage-members/CustomerDetailModal';
import DetailMember from '../manage-members/blocks/DetailMember';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
import { ListToolBar } from './blocks/ListToolBar';

const Kyc = () => {
  const [loading, setLoading] = useState(false);
  const [members, setMembers] = useState([]);
  const [member, setMember] = useState(initialMember);
  const [profession, setProfession] = useState([]);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const closeDialog = () => setIsDialogOpen(false);
  const { getUser } = useAuthContext();

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

  async function fetchCustomers() {
    try {
      let customers = await axios.get(`${BASE_URL}/customer/list`, {
        params: {
          limit: 10,
          page: 1,
          with_deleted: false,
          order_field: 'created_at',
          order_direction: 'DESC',
          type: 'kyc'
        }
      });
      let temp = 1;
      let resMembers = customers.data.data.list.map((el: any) => {
        el.no = temp++;
        el.name = el.fullname;
        return el;
      });
      setMembers(resMembers);
      let getProfession: any = await axios.get(`${BASE_URL_MASTER_DATA}/profession/list`, {
        params: {
          limit: 50,
          page: 1,
          with_deleted: false,
          order_field: 'name',
          order_direction: 'ASC'
        }
      });
      setProfession(getProfession.data.data.list);
    } catch (error: any) {
      toast.error(error.message);
      console.log(error);
    }
  }

  const handleUpdate = (data: any) => {
    setMember(data);
    setIsDialogOpen(true);
  };

  async function handleSubmit(data: any) {
    setDialogType('update');
    setMember(data);
    setDialogOpen(true);
  }

  function handleReject(data: any) {
    setDialogType('reject');
    setMember(data);
    setDialogOpen(true);
  }

  const resetForm = () => {
    setMember(initialMember);
  };

  const handleYes = async () => {
    setLoading(true);
    const userLogin: any = await getUser();
    const updateData: any = member;
    const customerId = member.id;
    const description = member.description;
    const destinationGroup = updateData.destinationGroup;
    updateData.updated_by = userLogin.data ? userLogin.data.id : '';
    let today = new Date();
    updateData.updated_at = today.toString();
    updateData.municipio = updateData.municipio_id;
    updateData.posto_adms = updateData.posto_adms_id;
    updateData.suco = updateData.suco_id;
    updateData.aldeia = updateData.aldeia_id;
    delete updateData.id;
    delete updateData.pin;
    delete updateData.name;
    delete updateData.longitude;
    delete updateData.latitude;
    delete updateData.created_at;
    delete updateData.no;
    delete updateData.destinationGroup;
    delete updateData.statusApproval;
    delete updateData.description;
    delete updateData.municipio_id;
    delete updateData.municipio_name;
    delete updateData.posto_adms_id;
    delete updateData.posto_adms_name;
    delete updateData.suco_id;
    delete updateData.suco_name;
    delete updateData.aldeia_id;
    delete updateData.aldeia_name;
    delete updateData.group_name;
    delete updateData.group_description;
    delete updateData.group_status;
    delete updateData.group_created_by;
    delete updateData.group_created_at;
    delete updateData.group_updated_by;
    delete updateData.group_updated_at;
    delete updateData.group_deleted_by;
    delete updateData.group_deleted_at;
    delete updateData.updated_at;
    try {
      const form = new FormData();
      for (const property in updateData) {
        if (updateData[property]) form.append(property, updateData[property]);
      }
      if (dialogType === 'reject') {
        if (destinationGroup === 'Premium')
          await axios.post(`${BASE_URL}/customer/reject`, {
            customerid: customerId,
            description: updateData.approval_description_premium
          });
        if (destinationGroup === 'Agent')
          await axios.post(`${BASE_URL}/customer/reject`, {
            customerid: customerId,
            description: updateData.approval_description_agent
          });
      }
      if (dialogType === 'update') {
        await axios.put(`${BASE_URL}/customer/update/${customerId}`, form);
        if (updateData.isneedapproval == 1 && destinationGroup === 'Premium')
          await axios.post(`${BASE_URL}/customer/approve`, {
            customerid: customerId,
            description: updateData.approval_description_premium
          });
        if (updateData.isneedapproval == 1 && destinationGroup === 'Agent')
          await axios.post(`${BASE_URL}/customer/approve`, {
            customerid: customerId,
            description: updateData.approval_description_agent
          });
      }
      setDialogOpen(false);
      setIsDialogOpen(false);
      toast.success(`Success Update & ${dialogType} Kyc Member`);
    } catch (error: any) {
      if (error?.response?.data?.error) error.message = error?.response?.data?.error;
      setDialogOpen(false);
      setIsDialogOpen(false);
      toast.error(error.message);
    } finally {
      await fetchCustomers();
      setLoading(false);
    }
  };

  function setShowAddDialog(el: any) {
    setIsDialogOpen(el);
  }

  if (loading) return <LoaderTransparant />;

  useEffect(() => {
    if (!isDialogOpen) resetForm();
  }, [isDialogOpen]);

  return (
    <>
      <Helmet>
        <title>TPAY | KYC</title>
      </Helmet>
      <Container>
        <ConfirmDialog
          open={dialogOpen}
          onClose={() => setDialogOpen(false)}
          title="Confirm Action"
          content={`Are you sure you want to ${dialogType}?`}
          onYes={handleYes}
          onNo={() => setDialogOpen(false)}
        />
        {member.id ? (
          // <CustomerDialog
          //   open={isDialogOpen}
          //   handleClose={closeDialog}
          //   handleSubmit={handleSubmit}
          //   initialData={member}
          //   viewStats={true}
          //   page={'kyc'}
          // />
          <DetailMember
            showAddDialog={isDialogOpen}
            setShowAddDialog={setShowAddDialog}
            handleClose={closeDialog}
            handleReject={handleReject}
            handleSubmit={handleSubmit}
            initialData={member}
            fetchCustomers={fetchCustomers}
            profession={profession}
            page={'kyc'}
          />
        ) : (
          ''
        )}
        <h1 className="text-xl font-medium leading-none text-gray-900 mb-5">KYC Upgrade Members</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">KYC Upgrade Members</span>
          </Link>
        </Breadcrumbs>
        {/* <div className="w-full overflow-x-auto"> */}
        <div className="grid gap-5 lg:gap-7.5 mt-5">
          <DataGridProvider
            data={members}
            columns={getColumns(handleUpdate)}
            pagination={{ size: 25 }}
            toolbar={<ListToolBar />}
            layout={{ card: true }}
            sorting={[{ id: 'created_at', desc: true }]}
            serverSide={false}
            onRowSelectionChange={(selected, table: any) => {
              const selectedRow = table.getSelectedRowModel().rows[0];
              if (selectedRow) handleUpdate(selectedRow.original);
            }}
          ></DataGridProvider>
        </div>
        {/* </div> */}
      </Container>
    </>
  );
};

export default Kyc;
