import { DataTable } from '@/components/ui/DataTable';
import { apiConfig } from '@/config/api.config';
import { getColumns, Members, initialMember } from './Columns';
import { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import DetailMember from './blocks/DetailMember';
import ConfirmDialog from '@/components/confirm';
import { useAuthContext } from '@/auth';
import { Container, DataGridInner, DataGridLoader, LoaderTransparant } from '@/components';
import { DataGridProvider } from '@/components';
import { toast } from 'sonner';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
import ListToolbar from './blocks/ListToolBar';
import { RefreshCw } from 'lucide-react';
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
const BASE_URL_CUSTOMER = apiConfig.service_customer;
const BASE_URL = apiConfig.service_customer;

const ManageMembers = () => {
  // const [loading, setLoading] = useState(false);
  const [members, setMembers] = useState([]);
  const [selectedMember, setSelectedMember] = 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 [groups, setGroups] = useState([]);
  const [isReloading, setIsReloading] = useState(false);
  const [currentPage, setCurrentPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  
  const closeDialog = () => {
    setIsDialogOpen(false);
    setMember(initialMember);
  };
  const { getUser } = useAuthContext();

  useEffect(() => {
    // fetchCustomers();
    fetchMasters();
  }, []);
  
  // async function fetchCustomers(): Promise<any> {
  //   setIsReloading(true);
  //   try {
  //     let customers = await axios.get(`${BASE_URL}/customer/list`, {
  //       params: {
  //         limit: pageSize,
  //         page: 1 + currentPage,
  //         with_deleted: false,
  //         order_field: 'created_at',
  //         order_direction: 'DESC'
  //       }
  //     });
  //     let temp = 1;
  //     let resMembers = customers.data.data.list.map((el: any) => {
  //       el.no = temp++;
  //       if (el.date_birth) {
  //         const d = new Date(el.date_birth);
  //         el.date_birth = d.toLocaleString('sv-SE');
  //       }
  //       el.name = el.fullname;
  //       return el;
  //     });
  //     setMembers(resMembers);
  //     return {
  //       data: resMembers,
  //       totalCount: customers.data.data.total_count,
  //     }
  //   } catch (error: any) {
  //     toast.error(error.message);
  //     console.log(error);
  //   } finally {
  //     setIsReloading(false);
  //   }
  // }

  // const fetchCustomers = useCallback(
  //   async ({ pageIndex, pageSize }:any) => {
  //     setIsReloading(true);
  //     try {
  //       const res = await axios.get(`${BASE_URL}/customer/list`, {
  //         params: {
  //           limit: pageSize,
  //           page: pageIndex + 1, // +1 because your API uses 1-based pages
  //           with_deleted: false,
  //           order_field: 'created_at',
  //           order_direction: 'DESC',
  //         },
  //       });

  //       const customers = res.data.data.list.map((el: any, index: number) => ({
  //         ...el,
  //         no: pageIndex * pageSize + index + 1,
  //         date_birth: el.date_birth
  //           ? new Date(el.date_birth).toLocaleString('sv-SE')
  //           : null,
  //         name: el.fullname,
  //       }));

  //       return {
  //         data: customers,
  //         totalCount: res.data.data.total_count,
  //       };
  //     } catch (error: any) {
  //       toast.error(error.message);
  //       console.error(error);
  //       return { data: [], totalCount: 0 };
  //     } finally {
  //       setIsReloading(false);
  //     }
  //   },
  //   []
  // );

  const fetchCustomers = async (
    page: number,
    limit: number,
    sorting: any,
    filter: any
  ) => {
    // [ SAMPLE
    //     {
    //         "id": "username",
    //         "value": "d"
    //     },
    //     {
    //         "id": "group_name",
    //         "value": "Bank"
    //     },
    //     {
    //         "id": "msisdn",
    //         "value": "88"
    //     }
    // ]
    sorting = sorting.length == 0 ? [{ id: 'name', desc: true }] : sorting;
    // filter = filter.length ? { any: filter[0].value?.toLowerCase() } : {};
    filter = filter.length ? filter : {};
    
    const res = await axios.get(`${BASE_URL}/customer/list`, {
      params: {
        limit: limit,
        page: page + 1, // +1 because your API uses 1-based pages
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'DESC',
        filter: JSON.stringify(filter),
        specialFilter: true
      },
    });

    const customers = res.data.data.list.map((el: any, index: number) => ({
      ...el,
      no: page * pageSize + index + 1,
      date_birth: el.date_birth
        ? new Date(el.date_birth).toLocaleString('sv-SE')
        : null,
      name: el.fullname,
    }));
    return { data: customers, totalCount: res?.data.data.total_count };
  };

  async function fetchMasters(): Promise<void> {
    setIsReloading(true);
    try {
      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);
      let getGroups = await axios.get(`${BASE_URL_CUSTOMER}/groups/list`, {
        params: {
          limit: 50,
          page: 1,
          with_deleted: false,
          order_field: 'name',
          order_direction: 'ASC'
        }
      });
      setGroups(getGroups.data.data.list);
    } catch (error: any) {
      toast.error(error.message);
      console.log(error);
    } finally {
      setIsReloading(false);
    }
  }

  const handleUpdate = (data: any) => {
    setDialogType('update');
    setSelectedMember(data.id);
    setMember(data);
    setIsDialogOpen(true);
  };

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

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

  const handleReload = async () => {
    setIsReloading(true);
    await fetchCustomers(currentPage, pageSize, '','');
    setIsReloading(false);
  };

  const handleYes = async () => {
    try {
      setIsReloading(true);
      // setLoading(true);
      const userLogin: any = await getUser();
      const updateData: any = member;
      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;
      const formUpdate = new FormData();
      for (const property in updateData) {
        if (updateData[property]) formUpdate.append(property, updateData[property]);
      }

      if (dialogType === 'update') {
        await axios.put(`${BASE_URL}/customer/update-dashboard/${selectedMember}`, formUpdate, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        toast.success('Success Edit Member');
      }
      if (dialogType === 'create') {
        const createMember: any = member;
        createMember.pin = 'admin';
        delete createMember.password;
        delete createMember.try_pin;
        delete createMember.isneedapproval;
        delete createMember.isapproved;
        delete createMember.approveddate;
        delete createMember.approvedby;
        delete createMember.updated_by;
        delete createMember.deleted_by;
        delete createMember.deleted_at;
        delete createMember.group;
        delete createMember.point_tier;
        delete createMember.approval_description_premium;
        delete createMember.approval_description_agent;
        delete createMember.language;
        const formCreate = new FormData();
        for (const property in createMember) {
          if (createMember[property]) formCreate.append(property, createMember[property]);
        }
        await axios.post(`${BASE_URL}/customers/create`, formCreate);
        toast.success('Success Create Member. PIN sent to email');
      }
    } catch (error: any) {
      if (error?.response?.data?.message) {
        toast.error(`${error?.response?.data?.error}.\n${error?.response?.data?.message}`);
      } else toast.error(error.message);
    } finally {
      setDialogOpen(false);
      closeDialog();
      // setLoading(false);
      setIsReloading(false);
    }
  };

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

  return (
    <>
      <Helmet>
        <title>TPAY | Manage Members</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 !== '' || dialogType === 'create' ? (
          <DetailMember
            showAddDialog={isDialogOpen}
            setShowAddDialog={setShowAddDialog}
            handleClose={closeDialog}
            handleSubmit={handleSubmit}
            initialData={member}
            fetchCustomers={handleReload}
            profession={profession}
            dialogType={dialogType}
          />
        ) : (
          ''
        )}
        <h1 className="text-xl font-medium leading-none text-gray-900 mb-5">Manage 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">Manage Members</span>
          </Link>
        </Breadcrumbs>

        <div className="grid gap-5 lg:gap-7.5 mt-5 relative">
          {isReloading && (
            <DataGridLoader />
          )}
          {!isReloading && (
            <DataGridProvider
            // data={members}
            pagination={{ size: pageSize }}
            columns={getColumns(handleUpdate)}
            layout={{ card: true }}
            serverSide={true}
            // onFetchData={fetchCustomers}
            onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
              fetchCustomers(pageIndex, pageSize, sorting, columnFilters)
            }
            toolbar={
              <ListToolbar
                createMember={createMember}
                onReload={handleReload}
                isReloading={isReloading}
                groups={groups}
              />
            }
            onRowSelectionChange={(selected, table: any) => {
              const selectedRow = table.getSelectedRowModel().rows[0];
              if (selectedRow) handleUpdate(selectedRow.original);
            }}
          ></DataGridProvider>
          )}
        </div>
        {/* </div> */}
      </Container>
    </>
  );
};

export default ManageMembers;
