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

interface MunicipiosProps {
  id: number;
  name: string;
}

interface ContextProps {
  municipios: MunicipiosProps[];
  showSearchDialog: boolean;
  handleSearchDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_user: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_user: string | null) => void;
  selectedMunicipios: string | null;
  getMunicipiosLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: MunicipiosProps[]; totalCount: number } | undefined>;
}

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

// interface MunicipiosContext {
//   municipios: MunicipiosProps[];
//   getMunicipiosLists: (
//     limit: number,
//     page: number,
//     with_deleted: boolean,
//     order_field: any,
//     order_direction: any
//   ) => Promise<void>;
//   getMunicipiosByName: (name: string) => Promise<void>;
//   createMunicipios: (data: Partial<MunicipiosProps>) => Promise<void>;
//   updateMunicipios: (id: number, data: Partial<MunicipiosProps>) => Promise<void>;
//   deleteMunicipios: (id: number, hardDelete?: boolean) => Promise<void>;
//   restoreMunicipios: (id: number) => Promise<void>;
// }

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

const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) => {
  const [showSearchDialog, setShowSearchDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedMunicipios, setSelectedMunicipios] = useState<string | null>(null);
  const [municipios, setMunicipios] = useState<MunicipiosProps[]>([]);
  const { GetData } = useCallApi();

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

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        // accessorFn: (row) => row.name,
        // id: 'name',
        accessorKey: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Municipio 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 getMunicipiosLists = 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}/municipios/list`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
        filter: JSON.stringify(filter)
      });
      setMunicipios(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching municipios', error);
    }
  };

  return (
    <ManageMunicipiosContext.Provider
      value={{
        municipios,
        showSearchDialog,
        handleSearchDialog,
        showAddDialog,
        handleAddDialog,
        showDeleteDialog,
        handleDeleteDialog,
        showEditDialog,
        handleEditDialog,
        selectedMunicipios,
        getMunicipiosLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

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

export { ManageMunicipiosProvider, ManageMunicipiosContext };
export type { MunicipiosProps };
