/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import styles from "./financials.module.scss";
import TransactionItem from "../transaction-item";
import { BsSearch } from "react-icons/bs";
import { LuRefreshCcw } from "react-icons/lu";
import { useEffect, useRef, useState } from "react";

// ✅ Skeleton Loader
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>
  );
};

const ProjectFinancials = ({ project }: any) => {
  const dateInputRef = useRef<HTMLInputElement | null>(null);
  const [selectedDate, setSelectedDate] = useState<string>("");
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isFading, setIsFading] = useState<boolean>(false);
  const [filter, setFilter] = useState<string>("All");

  // ✅ Sample transactions data
  const transactions = [
    { id: 1, date: "2025-10-10", description: "Tithe Offering", category: "Regular", amount: 5000, type: "Credit" },
    { id: 2, date: "2025-10-11", description: "Church Maintenance", category: "Project", amount: 2000, type: "Debit" },
    { id: 3, date: "2025-10-12", description: "Thanksgiving Donation", category: "Regular", amount: 12000, type: "Credit" },
    { id: 4, date: "2025-10-13", description: "Media Equipment Purchase", category: "Project", amount: 8000, type: "Debit" },
    { id: 5, date: "2025-10-14", description: "Special Seed", category: "Regular", amount: 10000, type: "Credit" },
    { id: 6, date: "2025-10-15", description: "New Building Fund", category: "Project", amount: 15000, type: "Credit" },
    { id: 7, date: "2025-10-16", description: "Utility Bills", category: "Regular", amount: 3000, type: "Debit" },
    { id: 8, date: "2025-10-17", description: "Sound System Repair", category: "Project", amount: 4000, type: "Debit" },
    { id: 9, date: "2025-10-18", description: "Youth Fellowship Donation", category: "Regular", amount: 2500, type: "Credit" },
    { id: 10, date: "2025-10-19", description: "Children Dept. Furniture", category: "Project", amount: 7000, type: "Debit" },
  ];

  // ✅ Filter transactions
  const filteredTransactions = transactions.filter((t) => {
    if (filter === "All") return true;
    if (filter === "Credit" || filter === "Debit") return t.type === filter;
    if (filter === "Regular" || filter === "Project") return t.category === filter;
    return true;
  });

  // ✅ Simulate loading
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsFading(true);
      setTimeout(() => setIsLoading(false), 400);
    }, 3000);
    return () => clearTimeout(timer);
  }, []);

  const triggerReload = () => {
    setIsLoading(true);
    setIsFading(false);
    setTimeout(() => {
      setIsFading(true);
      setTimeout(() => setIsLoading(false), 400);
    }, 3000);
  };

  const handleRefresh = () => triggerReload();

  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["trans"]}>
      {/* Toolbar */}
      <div className={styles["trans__toolbar"]}>
        <form action="/transactions" method="GET">
          <div className={styles["trans__toolbar--search"]}>
            <BsSearch color="#040A17" />
            <input
              type="text"
              name="search"
              placeholder="Search transactions by description..."
            />
          </div>

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

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

            <span
              onClick={handleRefresh}
              className={styles["trans__toolbar--helpers--refresh"]}
            >
              <LuRefreshCcw />
              Refresh
            </span>

            {/* ✅ Filter Dropdown */}
            <select
              className={styles["trans__toolbar--helpers--filter"]}
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
            >
              <option value="All">All</option>
              <option value="Credit">Credit</option>
              <option value="Debit">Debit</option>
              <option value="Regular">Regular</option>
              <option value="Project">Project</option>
            </select>
          </div>
        </form>
      </div>

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

      {/* Table */}
      <div className={styles["trans__table"]}>
        <div className={styles["trans__table--header"]}>
          <span>Transaction Date</span>
          <span>Description</span>
          <span>Category</span>
          <span>Amount</span>
          <span>Type</span>
          <span>Action</span>
        </div>

        <div className={styles["trans__table--children"]}>
          {isLoading ? (
            <div
              className={`${styles["skeleton__container"]} ${
                isFading ? styles.fadeOut : ""
              }`}
            >
              <SkeletonLoader />
            </div>
          ) : (
            <div className={`${styles["data__container"]} ${styles.fadeIn}`}>
              {filteredTransactions.map((tx) => (
                <TransactionItem key={tx.id} transaction={tx} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ProjectFinancials;
