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

interface SucosProps {
  sucos_id: number;
  sucos_name: string;
}

interface ContextProps {
  sucos: SucosProps[];
  showSearchDialog: boolean;
  handleSearchDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_sucos: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_sucos: string | null) => void;
  selectedSucos: string | null;
  getSucosLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: SucosProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  sucos: [],
  showSearchDialog: false,
  handleSearchDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_sucos: string | null) => {},
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_sucos: string | null) => {},
  selectedSucos: null,
  getSucosLists: async () => ({ data: [], totalCount: 0 })
};

const ManageSucosContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_master_data;

const ManageSucosContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [sucos, setSucos] = useState<SucosProps[]>([]);
  const [showSearchDialog, setShowSearchDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedSucos, setSelectedSucos] = useState<string | null>(null);
  const { GetData } = useCallApi();
  const navigate = useNavigate();

  const handleSearchDialog = useCallback((show: boolean) => {
    setShowSearchDialog(show);
  }, []);

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

  const handleEditDialog = useCallback((show: boolean, selected_sucos: string | null) => {
    setSelectedSucos(show ? selected_sucos : null);
    setShowEditDialog(show);
  }, []);

  const handleDeleteDialog = useCallback((show: boolean, selected_sucos: string | null) => {
    setSelectedSucos(show ? selected_sucos : null);
    setShowDeleteDialog(show);
  }, []);

  const handleNavigate = (path: string) => {
    const url = navigate(`${API_URL}/sucos/aldeias/${path}`);
  };

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.sucos_id,
        id: 'id',
        header: ({ column }) => <DataGridColumnHeader title="ID" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.sucos_name,
        id: 'sucos_name',
        header: ({ column }) => <DataGridColumnHeader title="Sucos Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.posto_name,
        id: 'posto_name',
        header: ({ column }) => <DataGridColumnHeader title="Posto Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        id: 'actions',
        header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: (data) => {
          const row = data.row.original;
          return (
            <>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleEditDialog(true, row.id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getSucosLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
      const response = await GetData(`${API_URL}/sucos/list`, {
        limit: limit,
        page: page + 1,
        with_deleted: true,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
        filter: JSON.stringify(filter)
      });
      console.log('Sucos List Response:', response?.data);
      setSucos(response?.data.list || []); // Pastikan default value adalah array kosong
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Sucos', error);
    }
  };

  const getAldeiasBySucos = async (name: string) => {
    try {
      const response = await axios.get(`${API_URL}/sucos/aldeias/${name}`);
      const data = response.data;
      console.log(data);
    } catch (error) {
      console.log(`Error fetching sucos by ${name}`, error);
    }
  };

  const createSucos = async (data: Partial<SucosProps>) => {
    try {
      await axios.post(`${API_URL}/sucos/create`, data);
      // getMunicipiosLists(10, 1, false, 'name', 'ASC');
    } catch (error) {
      console.error('Error creating municipios', error);
    }
  };

  const updateSucos = async (id: number, data: Partial<SucosProps>) => {
    try {
      await axios.put(`${API_URL}/sucos/update/${id}`, data);
      // getSucosLists(10, 1, false, 'name', 'ASC');
    } catch (error) {
      console.error('Error updating sucos', error);
    }
  };

  const deleteSucos = async (id: number, hardDelete?: boolean) => {
    try {
      await axios.delete(`${API_URL}/sucos/delete/${id}/${hardDelete}`);
      // getSucosLists(10, 1, false, 'name', 'ASC');
    } catch (error) {
      console.error('Error deleting sucos', error);
    }
  };

  const restoreSucos = async (id: number) => {
    try {
      await axios.put(`${API_URL}/sucos/restore/${id}`);
      // getSucosLists(10, 1, false, 'name', 'ASC');
    } catch (error) {
      console.error('Error restoring sucos', error);
    }
  };

  return (
    <ManageSucosContext.Provider
      value={{
        sucos,
        showSearchDialog,
        handleSearchDialog,
        showEditDialog,
        handleEditDialog,
        showAddDialog,
        handleAddDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedSucos,
        getSucosLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

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

export { ManageSucosContextProvider, ManageSucosContext };
export type { SucosProps };
