import { DataGridInner, 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 { columns, 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';

export interface IDataGridContextProps<TData extends object> {
  props: TDataGridProps<TData>;
  table: Table<TData>;
  totalRows: number;
  loading: (state: boolean) => void;
  reload: () => void;
  children?: React.ReactNode;
}

const DataGridContext = createContext<IDataGridContextProps<any> | undefined>(undefined);

export const useDataGrid = () => {
  const context = useContext(DataGridContext);
  if (!context) {
    throw new Error('useDataGrid must be used within a DataGridProvider');
  }
  return context;
};

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: 'fullname',
          order_direction: 'ASC',
          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 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_id;
    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) await axios.post(`${BASE_URL}/customer/approve`, { customerid: customerId, description: description});
      }
      await fetchCustomers();
      setDialogOpen(false);
      setIsDialogOpen(false);
      toast.success(`Success Update & ${dialogType} Kyc Member`);
    } catch (error: any) {
      setDialogOpen(false);
      setIsDialogOpen(false);
      toast.error(error.message);
    } finally {
      setLoading(false)
    }
  };

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

  if (loading) return <LoaderTransparant />;

  return (
    <>
      <Helmet>
        <title>TPAY | KYC</title>
      </Helmet>
      <div>
        <div className="container mx-auto w-full">
          <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-3 grid gap-5 lg:gap-7.5 mx-8 w-auto">Manage Member KYC</h1>
          <div className='grid gap-5 lg:gap-7.5 mx-8 w-auto'>
            <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">Manage Member KYC</span>
              </Link>
            </Breadcrumbs>
          </div>
          <div className="w-full overflow-x-auto px-4">
            <div className="min-w-[800px]">
              <DataTable
                data={members}
                columns={columns}
                onUpdate={handleUpdate}
                onDelete={null}
              />
            </div>
          </div>

        </div>
      </div>
    </>
  );
};

export default Kyc;
