/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from "react";
import styles from "./projects.module.scss";
import ProjectItem from "../project-item";
import { BsSearch } from "react-icons/bs";
import { LuRefreshCcw } from "react-icons/lu";
import NoResults from "../no-results";
import Pagination from "../pagination";
import ResultsPerPage from "../results-per-page";
import { usePaginatedData } from "@/hooks/usePaginatedData";

const SkeletonLoader = () => {
  const rows = Array.from({ length: 10 });
  return (
    <div className={styles["skeleton__wrapper"]}>
      {rows.map((_, i) => (
        <div key={i} className={styles["skeleton__row"]}>
          <div className={styles["skeleton__cell"]}></div>
          <div className={styles["skeleton__cell"]}></div>
          <div className={styles["skeleton__cell"]}></div>
          <div className={styles["skeleton__cell"]}></div>
          <div className={styles["skeleton__cell"]}></div>
        </div>
      ))}
    </div>
  );
};

interface projectsProps {
  projects: any[];
  links: any[];
  perPage?: number;
}

const ProjectsComponent: React.FC<projectsProps> = ({
  projects,
  links,
  perPage: initialPerPage = 10,
}) => {
  const dateInputRef = useRef<HTMLInputElement | null>(null);
  const [selectedDate, setSelectedDate] = useState<string>("");
  const [isFading, setIsFading] = useState<boolean>(false);

  // console.log("Received projects component", links)

  const {
    perPage,
    loading: isLoading,
    setLoading,
    handlePageChange,
    handlePerPageChange,
  } = usePaginatedData(initialPerPage);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsFading(true);
      setTimeout(() => setLoading(false), 400);
    }, 1500);
    return () => clearTimeout(timer);
  }, [setLoading]);

  const triggerReload = () => {
    setLoading(true);
    setIsFading(false);
    setTimeout(() => {
      setIsFading(true);
      setTimeout(() => setLoading(false), 400);
    }, 1500);
  };

  const openDatePicker = () => {
    requestAnimationFrame(() => {
      if (!dateInputRef.current) return;
      const anyRef: any = dateInputRef.current;
      if (typeof anyRef.showPicker === "function") {
        try {
          anyRef.showPicker();
        } catch {
          dateInputRef.current.focus();
        }
      } else {
        dateInputRef.current.focus();
      }
    });
  };

  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newDate = e.target.value;
    setSelectedDate(newDate);
    triggerReload();
  };

  return (
    <div className={styles["attend"]}>
      <div className={styles["attend__toolbar"]}>
        <h1>Manage All Church Projects</h1>
        <p>Seamlessly sync and manage all church projects all in one dashboard</p>
        <form action="/projects" method="GET">
          <div className={styles["attend__toolbar--search"]}>
            <div className={styles["attend__toolbar--search--input"]}>
                <BsSearch color="#040A17" />
              <input type="text" name="query" placeholder="Search projects by name..." />
            </div>
             <div className={styles["attend__results"]}>
              <ResultsPerPage
                current={perPage}
                options={[1, 5, 10, 25, 50]}
                onChange={handlePerPageChange}
              />
        </div>
          </div>

          <div className={styles["attend__toolbar--helpers"]}>
            <input
              ref={dateInputRef}
              type="date"
              name="date"
              onChange={handleDateChange}
              style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
            />

            <span onClick={openDatePicker} className={styles["attend__toolbar--helpers--date"]}>
              <LuRefreshCcw />
              Select Date
            </span>

            <span onClick={triggerReload} className={styles["attend__toolbar--helpers--refresh"]}>
              <LuRefreshCcw />
              Refresh
            </span>
          </div>
        </form>
      </div>

      {selectedDate && (
        <p style={{ marginTop: "0.5rem", fontWeight: 500 }}>
          Showing records for: <strong>{selectedDate}</strong>
        </p>
      )}

      <div className={styles["attend__table"]}>
        <div className={styles["attend__table--children"]}>
          {isLoading ? (
            <div
              className={`${styles["skeleton__container"]} ${
                isFading ? styles.fadeOut : ""
              }`}
            >
              <SkeletonLoader />
            </div>
          ) : (
            <div className={`${styles["data__container"]} ${styles.fadeIn}`}>
              {projects.map((project: any) => (
                <ProjectItem key={project.id} project={project} />
              ))}
            </div>
          )}

          {!isLoading && projects?.length === 0 && (
            <NoResults
              title="No Project(s) Found"
              remark="Oops! It seems you are yet to create any project(s). Please use the button above to add one."
            />
          )}
        </div>

        {/* Pagination */}
        <div className={styles["attend__pagination"]}>
          {projects?.length > 0 && links?.length > 0 && (
            <Pagination links={links} onChange={handlePageChange} />
          )}
        </div>
      </div>
    </div>
  );
};

export default ProjectsComponent;
