import { Table } from "../Table";
import { columns } from "../InitialTable/columns";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getPoints } from "../../../api";
import { useCallback, useState } from "react";
import { PAGE_SIZE } from "../constants";
import { STATUSES } from "../../../config";
import { useMergeTableData } from "../useMergeTableData";
import { Button, Select } from "antd";
import { useUpdateStatus } from "../../../hooks/useUpdateStatus";
import { HeaderWrapper } from "../HeaderWrapper";
import { useExportApproveAndWorkingData } from "./useExportApproveAndWorkingData";
import { useFilters } from "../../../stores/useFilters";
import { usePopup } from "../../../stores/usePopup";

const statusOptions = [
  { label: STATUSES.approve, value: STATUSES.approve },
  { label: STATUSES.working, value: STATUSES.working },
  { label: STATUSES.initial, value: STATUSES.initial },
];

export const StatusSelect = ({ value, onChange, disabled }) => {
  const handleClick = (e) => e.stopPropagation();

  const handleChange = (value) => {
    onChange(value);
  };

  return (
    <Select
      style={{
        width: 250,
      }}
      value={value}
      onChange={handleChange}
      options={statusOptions}
      disabled={disabled}
      placeholder="Выберите статус"
      onClick={handleClick}
    />
  );
};

const ChangeStatusButton = ({ selectedIds, selectedStatus }) => {
  const queryClient = useQueryClient();
  const { setPopup } = usePopup();

  const { mutate: updateStatus } = useUpdateStatus({
    onSuccess: () => {
      queryClient.invalidateQueries(["approve-working-points"]);
      setPopup(null);
    },
  });

  const handleClick = (e) => {
    e.stopPropagation();

    const params = new URLSearchParams({
      status: selectedStatus,
      "location_ids[]": selectedIds,
    });

    updateStatus(params);
  };

  return (
    <Button type="primary" onClick={handleClick}>
      Обновить статус
    </Button>
  );
};

const Header = ({ selectedIds, onClearSelected }) => {
  const [status, setStatus] = useState(STATUSES.approve);

  const handleClear = (e) => {
    e.stopPropagation();
    onClearSelected();
  };

  return (
    <HeaderWrapper
      leftColumn={
        selectedIds.length > 0 && (
          <>
            <StatusSelect value={status} onChange={setStatus} />
            <ChangeStatusButton
              selectedIds={selectedIds}
              selectedStatus={status}
            />
          </>
        )
      }
      rightColumn={
        selectedIds.length > 0 && (
          <Button onClick={handleClear}>Очистить все</Button>
        )
      }
      classes={{
        leftColumn: "flex items-center gap-x-4",
        rightColumn: "flex item-center gap-x-4",
      }}
      exportProvider={useExportApproveAndWorkingData}
    />
  );
};

export const ApproveAndWorkingTable = ({ fullWidth }) => {
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [page, setPage] = useState(1);
  const [selectedIds, setSelectedIds] = useState([]);
  const {
    filters: { region },
  } = useFilters();

  const clearSelected = () => setSelectedIds([]);

  const { data, isInitialLoading } = useQuery(
    ["approve-working-points", page, region],
    async () => {
      const params = new URLSearchParams({
        page,
        page_size: pageSize,
        "status[]": [STATUSES.approve, STATUSES.working],
      });

      return await getPoints(params, region);
    },
    { keepPreviousData: true }
  );

  const { data: mergedData, isClickedPointLoading } = useMergeTableData(
    data,
    setPageSize
  );

  const handlePageChange = useCallback((page) => setPage(page), []);

  const rowSelection = {
    selectedRowKeys: selectedIds,
    onChange: (selectedRowKeys) => setSelectedIds(selectedRowKeys),
    hideSelectAll: true,
  };

  return (
    <Table
      header={
        <Header selectedIds={selectedIds} onClearSelected={clearSelected} />
      }
      rowSelection={rowSelection}
      data={mergedData}
      onPageChange={handlePageChange}
      page={page}
      pageSize={pageSize}
      isClickedPointLoading={isClickedPointLoading}
      columns={columns}
      fullWidth={fullWidth}
      loading={isInitialLoading}
    />
  );
};
