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 { apiConfig } from '@/config/api.config';
import ConfirmDialog from '@/components/confirm';
import axios from 'axios';
const BASE_URL = apiConfig.service_customer;
import CustomerDialog from '../manage-members/CustomerDetailModal';

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 [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const closeDialog = () => setIsDialogOpen(false);
  const { getUser } = useAuthContext();

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

  async function fetchGroups() {
    try {
      let groups = 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 = groups.data.data.list.map((el: any) => {
        el.no = temp++
        el.name = el.fullname
        return el
      })
      setMembers(resMembers)
    } catch (error: any) {
      alert(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 () => {
    let userLogin: any = await getUser();
    let updateData: any = member;
    let customerId = member.id;
    updateData.updated_by = userLogin.data ? userLogin.data.id : ''
    let today = new Date();
    updateData.updated_at = today.toString();
    delete updateData.id;
    delete updateData.pin;
    delete updateData.name;
    delete updateData.longitude;
    delete updateData.latitude;
    delete updateData.created_at;
    delete updateData.no;
    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;
    try {
      if (dialogType === 'reject') {
        await axios.post(`${BASE_URL}/customer/reject`, {customerid: customerId})
      }
      if (dialogType === 'update') {
        await axios.put(`${BASE_URL}/customer/update/${customerId}`, updateData)
        if (updateData.isneedapproval == 1) await axios.post(`${BASE_URL}/customer/approve`, {customerid: customerId})
      }
      await fetchGroups();
      setDialogOpen(false)
      setIsDialogOpen(false)
    } catch (error: any) {
      alert(error.message)
      setDialogOpen(false)
      setIsDialogOpen(false)
    }
  }

  return (
    <div>
      <div className="container mx-auto py-5">
        <ConfirmDialog
          open={dialogOpen}
          onClose={() => setDialogOpen(false)}
          title="Confirm Action"
          content={`Are you sure you want to ${dialogType}?`}
          onYes={handleYes}
          onNo={() => setDialogOpen(false)}
        />
        <CustomerDialog open={isDialogOpen} handleClose={closeDialog} handleReject={handleReject}
        handleSubmit={handleSubmit} initialData={member} viewStats={true}/>
        <h1 className="text-xl font-medium leading-none text-gray-900 mb-7">Manage Member KYC</h1>
        <DataTable data={members} columns={columns} onUpdate={handleUpdate} onDelete={null}/>
      </div>
    </div>
  );
};

export default Kyc;
