"use client";

import Image from "next/image";
import "./ProfileTable.scss";
import arrows from "@/shared/icons/arrows.svg";
import {
  REPORT_STATUS,
  REPORT_STATUS_COLORS,
} from "@/shared/variables/report-status";
import Link from "next/link";
import Pagination from "@/features/Pagination/Pagination";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { sliceDate } from "./helpers";
import { useProfileReportsStore } from "./profile-reports.store";
import { useRouter } from "next/navigation";

interface IProfileTableProps {
  searchParams: { ["страница-обращений"]: string };
}

const ProfileTable: React.FC<IProfileTableProps> = ({
  searchParams,
}: IProfileTableProps) => {
  const {
    getMyReports,
    data: reports,
    isLoading,
    error,
  } = useProfileReportsStore();
  const session = useSession();
  const router = useRouter();
  const [filter, setFilter] = useState({
    option: "date",
    toggle: true,
  });
  const [activePage, setActivePage] = useState<number>(
    +searchParams["страница-обращений"] || 1
  );
  const params = [
    {
      param: "Дата",
      handleClick() {
        if (filter.option !== "date") {
          return setFilter({ option: "date", toggle: false });
        }

        setFilter((prev) => {
          return { option: "date", toggle: !prev.toggle };
        });
        getMyReports(
          filter,
          activePage,
          session.data?.access_token as string
        );
      },
    },
    { param: "Адрес" },
    { param: "Статус" },
    {
      param: "Комментарии",
      handleClick() {
        if (filter.option !== "count_reviews") {
          return setFilter({
            option: "count_reviews",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return { option: "count_reviews", toggle: !prev.toggle };
        });
        getMyReports(
          filter,
          activePage,
          session.data?.access_token as string
        );
      },
    },
    {
      param: "Рейтинг",
      handleClick() {
        if (filter.option !== "total_likes") {
          return setFilter({ option: "total_likes", toggle: false });
        }

        setFilter((prev) => {
          return { option: "total_likes", toggle: !prev.toggle };
        });
        getMyReports(
          filter,
          activePage,
          session.data?.access_token as string
        );
      },
    },
  ];

  useEffect(() => {
    if (session.status === "loading") return;
    getMyReports(
      filter,
      activePage,
      session.data?.access_token as string
    );
  }, [session]);

  useEffect(() => {
    router.push(
      `/profile/my-reports?страница-обращений=${activePage}`,
      { scroll: false }
    );
    getMyReports(
      filter,
      activePage,
      session.data?.access_token as string
    );
  }, [activePage]);

  return (
    <div className="profile-table">
      <div
        className={`profile-table__wrapper ${
          reports.results.length ? "" : "no-reports-in-profile"
        }`}
      >
        {reports.results.length ? (
          <table>
            <thead>
              <tr>
                {params.map((p) => (
                  <td key={p.param}>
                    {p.handleClick ? (
                      <button onClick={p.handleClick}>
                        {p.param}{" "}
                        <Image src={arrows} alt="Arrows Icon" />
                      </button>
                    ) : (
                      p.param
                    )}
                  </td>
                ))}
              </tr>
            </thead>
            <tbody>
              {reports.results.map((report) => (
                <tr key={report.id}>
                  <td id="my-report-date">
                    {sliceDate(report.created_at)}
                  </td>
                  <td id="my-report-location">
                    {report.status === 2 ? (
                      <Link href={`/report/${report.id}`}>
                        {report.location[0].address}
                      </Link>
                    ) : (
                      report.location[0].address
                    )}
                  </td>
                  <td
                    id="my-report-status"
                    style={{
                      color: `${REPORT_STATUS_COLORS[report.status]}`,
                    }}
                  >
                    {REPORT_STATUS[report.status]}
                  </td>
                  <td id="my-report-reviews">
                    {report.count_reviews}
                  </td>
                  <td id="my-report-likes">{report.total_likes}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p className="profile-table__message">
            Вы пока не оставили ни одного обращения.
          </p>
        )}
      </div>
      <Pagination
        activePage={activePage}
        setActivePage={setActivePage}
        count={reports.count as number}
        prev={reports.previous}
        next={reports.next}
        current_count={reports.results.length}
        limit={8}
      />
      <Link id="my-reports-link" href="/create-report">
        Написать обращение
      </Link>
    </div>
  );
};

export default ProfileTable;
