import { useEffect, useState } from "react";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { useModalStore } from "../context/zustand-store/appStore";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { formatJustDate } from "../utils/formatTime";
import { AddIncentivePlan } from "../partials/quota/AddIncentivePlan";
import AutoComplete from "../components/AutoComplete/AutoComplete";

export default function IncentivePlans() {
  const { openModal } = useModalStore();
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [tableData, setTableData] = useState([]);
  const [selectedGroup, setSelectedGroup] = useState<(number | string)[]>([]);

  const groupOptions = [
    { key: "", value: "همه" },
    { key: "rural", value: "روستایی" },
    { key: "industrial", value: "صنعتی" },
    { key: "nomadic", value: "عشایری" },
  ];

  const { data: apiData, refetch } = useApiRequest({
    api: `/product/web/api/v1/incentive_plan/active_plans/`,
    method: "get",
    params: {
      ...params,
      ...(selectedGroup.length > 0 && { group: selectedGroup[0] }),
    },
    queryKey: ["incentivePlans", params, selectedGroup],
  });

  useEffect(() => {
    if (apiData?.results) {
      const formattedData = apiData.results.map((item: any, i: number) => {
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.name,
          item?.description,
          item?.plan_type,
          item?.group === "rural"
            ? "روستایی"
            : item?.group === "nomadic"
            ? "عشایری"
            : "صنعتی",
          item?.is_time_unlimited ? "دارد" : "ندارد",
          formatJustDate(item?.start_date_limit),
          formatJustDate(item?.end_date_limit),
          <Popover key={i}>
            <Tooltip title="ویرایش طرح" position="right">
              <Button
                page="incentive_plans"
                access="Update-Incentive-Plan"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش طرح",
                    content: <AddIncentivePlan getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>

            <DeleteButtonForPopOver
              page="incentive_plans"
              access="Delete-Incentive-Plan"
              title="از حذف طرح تشویقی اطمینان دارید؟"
              api={`/product/web/api/v1/incentive_plan/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(formattedData);
    }
  }, [apiData, params]);

  const handleGroupChange = (keys: (number | string)[]) => {
    setSelectedGroup(keys);
    setParams({ ...params, page: 1 });
  };

  return (
    <>
      <Grid container className="items-center gap-2">
        <Grid>
          <Button
            size="small"
            page="incentive_plans"
            access="Post-Incentive-Plan"
            variant="submit"
            onClick={() =>
              openModal({
                title: "ایجاد طرح تشویقی",
                content: <AddIncentivePlan getData={refetch} />,
              })
            }
          >
            ایجاد طرح تشویقی
          </Button>
        </Grid>
        <Grid>
          <AutoComplete
            data={groupOptions}
            selectedKeys={selectedGroup}
            onChange={handleGroupChange}
            title="فیلتر بر اساس گروه"
            size="small"
          />
        </Grid>
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          excelInfo={{
            link: "product/excel/incentive_plan_excel",
          }}
          onChange={(e) => {
            setParams(e);
          }}
          title="طرح های تشویقی"
          isPaginated
          count={apiData?.count || 10}
          columns={[
            "ردیف",
            "نام",
            "توضیحات",
            "نوع طرح",
            "گروه",
            "محدودیت زمانی",
            "شروع محدودیت",
            "پایان طرح",
            "عملیات",
          ]}
          rows={tableData}
        />
      </Grid>
    </>
  );
}
