import { useCallback, useEffect, useState } from 'react';
import { PageContainer } from '../../StyledForPage';
import { HeaderSwitch } from '../../../components/HeaderMenu/HeaderSwitch.jsx';
import { SwitchUserSsp } from '../../../components/AdminPanel/SwitchUserSsp';
import { ROLES_NAME_ID } from '../../../constants/constants';
import { useAuth } from '../../../app/context/AuthProvider';
import { Box } from '@mui/material';
import { toast } from 'react-toastify';
import { AuditLogsApi } from '../../../api/audit-logs';
import { SspApi } from '../../../api/ssp';
import { UsersApi } from '../../../api/users';
import AuditLogsFilters from './components/AuditLogsFilters';
import AuditLogsTable from './components/AuditLogsTable';
import { DEFAULT_ACTIONS } from './constants/auditLogs.jsx';

const AuditLogsPage = () => {
  const { user } = useAuth();
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(20);
  const [taskIdSearch, setTaskId] = useState('');
  const [formIdSearch, setFormId] = useState('');
  const [selectedUser, setSelectedUser] = useState(null);
  const [selectedSsp, setSelectedSsp] = useState(null);
  const [selectedEventType, setSelectedEventType] = useState(null);
  const [dateFrom, setDateFrom] = useState(null);
  const [dateTo, setDateTo] = useState(null);

  // Options for filters
  const [users, setUsers] = useState([]);
  const [ssps, setSsps] = useState([]);
  const [eventTypes, setEventTypes] = useState([]);

  // Fetch filter options
  useEffect(() => {
    UsersApi.getAll().then((data) => {
      if (data.success) {
        setUsers(data.result);
      } else {
        toast.error('Ошибка получения пользователей');
      }
    });

    SspApi.getAll().then((data) => {
      if (data.success) {
        const activeSsps = data.result.filter((v) => v.is_active);
        setSsps(activeSsps);
      } else {
        toast.error('Ошибка получения ССП');
      }
    });

    const eventTypesList = Object.keys(DEFAULT_ACTIONS).map((key) => ({
      id: key,
      name: DEFAULT_ACTIONS[key],
    }));
    setEventTypes(eventTypesList);
  }, []);

  // Fetch audit logs
  const fetchAuditLogs = async () => {
    setLoading(true);
    try {
      const taskId = taskIdSearch.replace('#', '');
      const formId = formIdSearch.replace('#', '');
      const params = {
        page: page + 1,
        limit: rowsPerPage,
        user_id: selectedUser?.id,
        org_unit_id: selectedSsp?.id,
        event: selectedEventType?.id,
        date_from: dateFrom ? dateFrom.toISOString().slice(0, 10) : undefined,
        date_to: dateTo ? dateTo.toISOString().slice(0, 10) : undefined,
        task_id: taskId ? taskId : undefined,
        form_id: formId ? formId : undefined,
      };

      const data = await AuditLogsApi.getAll(params);
      setLogs(data.result ?? []);
      setTotalCount(data.count ?? 0);
    } catch (error) {
      toast.error('Ошибка получения журнала аудита');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAuditLogs();
  }, [
    page,
    rowsPerPage,
    selectedUser,
    selectedSsp,
    selectedEventType,
    dateFrom,
    dateTo,
    taskIdSearch,
    formIdSearch,
  ]);

  const handlePageChange = (newPage) => {
    setPage(newPage);
  };

  const handleRowsPerPageChange = (newRowsPerPage) => {
    setRowsPerPage(newRowsPerPage);
    setPage(0);
  };

  const handleTaskIdChange = useCallback((value) => {
    setTaskId(value);
    setPage(0);
  }, []);

  const handleFormIdChange = useCallback((value) => {
    setFormId(value);
    setPage(0);
  }, []);

  const handleResetFilters = () => {
    setSelectedUser(null);
    setSelectedSsp(null);
    setSelectedEventType(null);
    setDateFrom(null);
    setDateTo(null);
    setTaskId('');
    setFormId('');
    setPage(0);
  };

  if (!user || user.role_id !== ROLES_NAME_ID.admin) return null;

  return (
    <PageContainer>
      <HeaderSwitch />
      <Box sx={{
        display: "flex", justifyContent: "space-between"
      }} >
        <SwitchUserSsp />
      </Box>

      <AuditLogsFilters
        users={users}
        ssps={ssps}
        eventTypes={eventTypes}
        selectedUser={selectedUser}
        selectedSsp={selectedSsp}
        selectedEventType={selectedEventType}
        dateFrom={dateFrom}
        dateTo={dateTo}
        taskId={taskIdSearch}
        formId={formIdSearch}
        onUserChange={setSelectedUser}
        onSspChange={setSelectedSsp}
        onEventTypeChange={setSelectedEventType}
        onDateFromChange={setDateFrom}
        onDateToChange={setDateTo}
        onResetFilters={handleResetFilters}
        onTaskIdChange={handleTaskIdChange}
        onFormIdChange={handleFormIdChange}
      />

      <AuditLogsTable
        logs={logs}
        loading={loading}
        totalCount={totalCount}
        page={page}
        rowsPerPage={rowsPerPage}
        onPageChange={handlePageChange}
        onRowsPerPageChange={handleRowsPerPageChange}
      />
    </PageContainer>
  );
};

export default AuditLogsPage;
