import { useEffect, useRef, useState } from "react";
import AddCustomer from "./AddCustomer";
import CustomerTable from "./CustomersTable";
import {
  LeftOutlined,
  PlusOutlined,
  RightOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { useCustomerData } from "../../Hooks/Customers";
//@ts-ignore
import addicon from "../../assets/addiconpng.png";
// @ts-ignore

import IconSearch from "../../assets/searchIcon.png";

import { Button, Input, Pagination, Select, Space, Typography } from "antd";
import { theme } from "antd";

const Customer = () => {
  const [open, setOpen] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(() => {
    const saved = localStorage.getItem("general_pageSize");
    return saved ? Number(saved) : 15;
  });
  const showModal = () => {
    setOpen(true);
  };

  const { token } = theme.useToken();

  const [search, setSearch] = useState("");
  const [searchChatId, setSearchChatId] = useState("");
  const { data, isLoading, refetch } = useCustomerData({
    name: search,
    is_active: undefined,
    page_size: pageSize,
    page: page,
    telegram_group_id: searchChatId,
  });

  const pageSizeOptions = [15, 20, 30, 40, 50];

  const handlePageSizeChange = (value: number) => {
    setPageSize(value);
    setPage(1);
  };

  useEffect(() => {
    localStorage.setItem("general_pageSize", String(pageSize));
  }, [pageSize]);

  const Next = () => {
    const a = Number(page) + 1;
    setPage(a);
  };
  const Previos = () => {
    Number(page);
    if (page > 1) {
      const a = Number(page) - 1;
      setPage(a);
    }
  };

  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    const searchText = e.target.value;
    timerRef.current = setTimeout(() => {
      setSearch(searchText);
    }, 1000);
  };
  const handleSearchChatId = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    const searchChatId = e.target.value;
    timerRef.current = setTimeout(() => {
      setSearchChatId(searchChatId);
    }, 1000);
  };
  const themes = localStorage.getItem("theme") === "true" ? true : false;

  return (
    <div>
      {open && <AddCustomer open={open} setOpen={setOpen} />}
      <div className="header d-flex">
        <Typography className="title">Drivers</Typography>

        <Button
          className="d-flex"
          onClick={showModal}
          icon={<PlusOutlined />}
          style={{
            backgroundColor: "#f99e2c",
            color: "white",
            padding: 18,
          }}
        >
          Add Driver
        </Button>
      </div>
      <div className="filter d-flex" style={{ gap: 5 }}>
        <div>
          <Input
            placeholder="Search"
            prefix={<SearchOutlined />}
            onChange={handleSearchChange}
          />
        </div>
        <div>
          <Input
            placeholder="Search Chat ID"
            prefix={<SearchOutlined />}
            onChange={handleSearchChatId}
          />
        </div>
      </div>
      <CustomerTable data={data?.data} isLoading={isLoading} />
      <Space style={{ width: "100%", marginTop: 40 }} direction="vertical">
        <Space
          style={{
            justifyContent: "end",
            position: "fixed",
            bottom: 0,
            left: 0,
            width: "100%",
            backgroundColor: token.colorBgContainer,
            boxShadow: "0 4px 8px rgba(0, 0, 0, 0.4)",
            padding: "10px 0",
            zIndex: 1000,
          }}
          wrap
        >
          <Select
            value={pageSize}
            onChange={handlePageSizeChange}
            style={{ width: 65, marginRight: 16 }}
            options={pageSizeOptions.map((size) => ({
              label: `${size}`,
              value: size,
            }))}
          />

          <Button
            type="primary"
            onClick={Previos}
            disabled={!data?.previous}
            style={{
              backgroundColor: token.colorBgContainer,
              color: token.colorText,
              border: "none",
            }}
          >
            <LeftOutlined />
          </Button>
          <Input
            disabled
            style={{
              width: 40,
              textAlign: "center",
              background: token.colorBgContainer,
              border: "1px solid",
              borderColor: token.colorText,
              color: token.colorText,
            }}
            value={page}
            onChange={(e) => {
              let num = e.target.value;
              if (Number(num) && num !== "0") {
                setPage(Number(num));
              }
            }}
          />
          <Button
            type="primary"
            onClick={Next}
            disabled={!data?.next}
            style={{
              backgroundColor: token.colorBgContainer,
              color: token.colorText,
              border: "none",
            }}
          >
            <RightOutlined />
          </Button>

          {/* <Pagination
            current={page}
            total={100}
            pageSize={data?.page_size}
            onChange={(page) => setPage(page)}
          /> */}
        </Space>
      </Space>
    </div>
  );
};

export default Customer;
