import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { toast } from 'sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
import { createContext, useCallback, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolbar';
import { useCallApi } from '@/hooks';
import moment from 'moment';
import DetailDialog from '../blocks/DetailDialog';

interface ManageKycDeletionProps {
  id: string;
  customers_id: string;
  group_id: string;
  username: string;
  fullname: string;
  email: string;
  status: string;
  created_at: Date;
}

interface ContextProps {
  getKycDeletionList: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any,
    filter: any
  ) => Promise<{ data: ManageKycDeletionProps[]; totalCount: number } | undefined>;
  showDetailDialog: boolean;
  setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
  handleDetailDialog: (show: boolean, selected_user: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  selectedIdCustomer: string | null;
  detailKyc: any | null;
  setDetailKyc: React.Dispatch<React.SetStateAction<any>>;
  handleApproveReject: (customerDeletionId: string, status_approve: string) => Promise<any>;
}

const initialProps: ContextProps = {
  getKycDeletionList: async () => ({ data: [], totalCount: 0 }),
  showDetailDialog: false,
  handleDetailDialog: () => {},
  showAddDialog: false,
  handleAddDialog: () => {},
  selectedIdCustomer: null,
  setShowDetailDialog: () => { },
  detailKyc: async () => {},
  setDetailKyc: () => { },
  handleApproveReject: async () => ({customerDeletionId: '0', status_approve: 'Y'}),
};

const ManageKycDeletionContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_customer;

type StatusCode = 'W' | 'Y' | 'N' | 'T';

interface StatusInfo {
  label: string;
  bg: string;
  text: string;
}

const statusMap: Record<StatusCode, StatusInfo> = {
  W: { label: 'Waiting Approval', bg: 'bg-yellow-100', text: 'text-yellow-600' },
  T: { label: 'No Need', bg: 'bg-blue-100', text: 'text-blue-600' },
  N: { label: 'Reject', bg: 'bg-red-100', text: 'text-red-600' },
  Y: { label: 'Approve', bg: 'bg-green-100', text: 'text-green-600' },
};

export const renderStatusBadge = (statusRaw: string | null | undefined) => {
	const status = statusRaw as StatusCode;
	const { label, bg, text } = statusMap[status] ?? {
		label: 'Unknown',
		bg: 'bg-gray-100',
		text: 'text-gray-600',
	};

	return (
		<span className={`px-2 py-1 text-xs font-semibold rounded-full ${bg} ${text}`}>
			{label}
		</span>
	);
};

// const { reload } = useDataGrid();

const ManageKycDeletionContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [selectedIdCustomer, setSelectedIdCustomer] = useState<string | null>(null);
  const [detailKyc, setDetailKyc] = useState<any>();
  const [manageKyc, setManageKyc] = useState<ManageKycDeletionProps[]>([]);
  const { GetData, PostData } = useCallApi();

  const getKycDeletionList = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      let startdate;
      let enddate;
      let formattedFilter;
  
      if (filter == undefined || filter.length == 0) {
        const today = new Date();
        const nextWeek = new Date();
        nextWeek.setDate(today.getDate() + 7);
  
        startdate = today.toISOString().split('T')[0];
        enddate = nextWeek.toISOString().split('T')[0];
      } else if (filter != undefined || filter.length != 0) {
        startdate = filter[0].value.from;
        enddate = filter[0].value.to;
      }
  
      formattedFilter = {
        
      };
  
      const response = await GetData(`${API_URL}/customer_deletion/list`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: "id",
        order_direction: 'DESC',
        filter: JSON.stringify(formattedFilter)
      });
  
      setManageKyc(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching transaction', error);
    }
  };

  const handleDetailDialog = useCallback(async (show: boolean, selected_id_customer: string | null) => {
    if (show == true) {
      setSelectedIdCustomer(show ? selected_id_customer : null);
      let detailCustomer = await GetData(`${API_URL}/customer_deletion/detail/${selected_id_customer}`, {})
      setDetailKyc(detailCustomer?.data)
    }
    setShowDetailDialog(show);
  }, []);

  const handleAddDialog = useCallback((show: boolean) => {
    setShowAddDialog(show);
  }, []);

  const handleApproveReject = useCallback(async (customerDeletionId: string, status_approve: string) => {
    console.log(customerDeletionId, status_approve)
    try {
      let approveReject = await PostData(`${API_URL}/customer_deletion/update_status/${customerDeletionId}`, {
        status_approve
      })

      if (approveReject?.status == true) {
        toast.success('Success update status approval')
        handleDetailDialog(false, null)
      } else {
        toast.warning(`${approveReject?.message}`)
        handleDetailDialog(false, null)
      }
    } catch (error) {
      toast.warning('Failed to approve/reject')
      handleDetailDialog(false, null)
    }
  }, [])

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.id,
        id: 'id',
        header: ({ column }) => <DataGridColumnHeader title="ID" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        },
      },
      {
        accessorFn: (row) => row.created_at,
        id: 'created_at',
        header: ({ column }) => <DataGridColumnHeader title="Created Date" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
        cell: ({ row }) => moment(row.original.created_at).format('DD/MM/YYYY HH:mm:ss')
      },
      {
        accessorFn: (row) => row.username,
        id: 'username',
        header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[350px]'
        }
      },
      {
        accessorFn: (row) => row.fullname,
        id: 'fullname',
        header: ({ column }) => <DataGridColumnHeader title="Fullname" column={column} />,
        enableSorting: true,
        meta: {
          headerClassName: 'w-[350px]'
        }
      },
      {
        accessorFn: (row) => row.registered_email,
        id: 'email',
        header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
        enableSorting: true,
        meta: {
          headerClassName: 'w-[350px]'
        }
      },
      {
        accessorFn: (row) => row.status_approve,
        id: 'status_approve',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: true,
        meta: {
          headerClassName: 'w-[350px]'
        },
        cell: ({row}) => renderStatusBadge(row.original.status_approve)
      },
      {
        id: 'actions',
        enableSorting: false,
        header: ({ column }) => <DataGridColumnHeader title="Action" column={column} />,
        cell: (data: any) => {
          const row = data.row.original;

          return (
            <>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDetailDialog(true, row.id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleDetailDialog]
  );

  return (
    <ManageKycDeletionContext.Provider
      value={{
        getKycDeletionList,
        showDetailDialog,
        handleDetailDialog,
        showAddDialog,
        handleAddDialog,
        selectedIdCustomer,
        setShowDetailDialog,
        setDetailKyc,
        detailKyc,
        handleApproveReject,
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

      <DataGridProvider
        columns={columns}
        pagination={{ size: 10 }}
        toolbar={<ListToolbar />}
        layout={{ card: true }}
        sorting={[{ id: 'name', desc: false }]}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          getKycDeletionList(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
        <DetailDialog />
      </DataGridProvider>
    </ManageKycDeletionContext.Provider>
  );
};

export { ManageKycDeletionContextProvider, ManageKycDeletionContext };
export type { ManageKycDeletionProps };
