import { DataTable } from '@/components/ui/DataTable';
import { apiConfig } from '@/config/api.config';
import { columns, Members, initialMember } from './Columns';
import { useState, useEffect } from 'react';
import axios from 'axios';
import CustomerDialog from './CustomerDetailModal';
import ConfirmDialog from '@/components/confirm';
import { useAuthContext } from '@/auth';
import { ScreenLoader } from '@/components';
const BASE_URL = apiConfig.service_customer;

const ManageMembers = () => {
  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(() => {
    setLoading(true)
    fetchGroups()
    setLoading(false)
  }, []);

  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',
        }
      });
      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) => {
    setDialogType('update');
    setMember(data)
    setIsDialogOpen(true)
  }

  function createMember() {
    setDialogType('create');
    setMember(initialMember);
    setIsDialogOpen(true);
  }

  async function handleSubmit(data: any) {
    setMember(data)
    setDialogOpen(true)
  }

  const handleYes = async () => {
    const userLogin: any = await getUser();
    const updateData: any = member;
    const 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.destinationGroup;
    delete updateData.statusApproval;
    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 === 'update') await axios.put(`${BASE_URL}/customer/update/${customerId}`, updateData)
      // if (dialogType === 'create') await axios.post(`${BASE_URL}/customers/create`, member)
      await fetchGroups();
      setDialogOpen(false)
      setIsDialogOpen(false)
    } catch (error: any) {
      alert(error.message)
      setDialogOpen(false)
      setIsDialogOpen(false)
    }
  }

  if (loading) return (<ScreenLoader/>)

  return (
    <div>
      <div className="container mx-auto p-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} handleSubmit={handleSubmit} initialData={member}/>
        <h1 className="text-xl font-medium leading-none text-gray-900">Manage Members</h1>
        <DataTable data={members} createData={createMember} columns={columns} onUpdate={handleUpdate} onDelete={null}/>
      </div>
    </div>
  );
};

export default ManageMembers;
