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

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 closeDialog = () => {
    setIsDialogOpen(false);
    setMember(initialMember);
  };
  const { getUser } = useAuthContext();

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

  async function fetchCustomers(): Promise<void> {
    try {
      let customers = await axios.get(`${BASE_URL}/customer/list`, {
        params: {
          limit: 20,
          page: 1,
          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);
      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 {
      setLoading(false);
      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 = () => {
    setIsReloading(true);
    fetchCustomers();
  };
  const handleYes = async () => {
    try {
      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/${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?.message);
      else toast.error(error.message);
    } finally {
      setDialogOpen(false);
      closeDialog();
      await fetchCustomers();
      setLoading(false);
    }
  };

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

  if (loading) return <LoaderTransparant />;

  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={fetchCustomers}
            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="w-full overflow-x-auto px-4"> */}

        <div className="grid gap-5 lg:gap-7.5 mt-5 relative">
          {isReloading && (
            <div className="fixed inset-0 bg-transparent flex items-center justify-center z-50 text-muted-foreground px-4 py-2">
              <div className="bg-card flex items-center border shadow-sm rounded-md">
                <div className="flex flex-col items-center">
                  <RefreshCw className="animate-spin h-8 w-8 text-slate-500 mb-2" />
                  <span className="text-slate-500 font-medium">Refreshing data...</span>
                </div>
              </div>
            </div>
          )}
          <DataGridProvider
            data={members}
            pagination={{ size: 25 }}
            columns={getColumns(handleUpdate)}
            layout={{ card: true }}
            serverSide={false}
            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;
