"use client";

import "./ReviewSection.scss";
import { apiInstance } from "@/shared/config/apiConfig";
import { IReviewList } from "@/shared/types/review-type";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import calendar from "./icons/calendar.svg";
import Image from "next/image";

interface IReviewsSectionProps {
  endpoint: string;
  id: number;
}

const ReviewSection: React.FC<IReviewsSectionProps> = ({
  endpoint,
  id,
}: IReviewsSectionProps) => {
  const [reviews, setReviews] = useState<IReviewList>();
  const session = useSession();
  const handleSubmit: React.MouseEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();
    const Authorization = `Bearer ${session.data?.access_token}`;

    const formData = new FormData(e.currentTarget);

    const config = {
      headers: {
        Authorization,
      },
    };

    if (!formData.get("review")) {
      return;
    }

    formData.append("news", id.toString());

    try {
      const res = await apiInstance.post(
        `/${endpoint}/${id}/reviews/`,
        formData,
        config
      );
      getReviews();
    } catch (error) {
      console.log(error);
    }
  };

  const getReviews = async () => {
    const response = await apiInstance.get<IReviewList>(
      `/${endpoint}/${id}/reviews/`
    );

    setReviews(response.data);
  };

  useEffect(() => {
    getReviews();
  }, []);

  const months: Record<string, string> = {
    "01": "Январь",
    "02": "Февраль",
    "03": "Март",
    "04": "Апрель",
    "05": "Май",
    "06": "Июнь",
    "07": "Июль",
    "08": "Август",
    "09": "Сентябрь",
    "10": "Октябрь",
    "11": "Ноябрь",
    "12": "Декабрь",
  };
  return (
    <section className="review-section">
      <h3>
        <span id="blue-point" /> Написать комментарий
      </h3>

      <form onSubmit={handleSubmit}>
        <textarea name="review" />
        <button type="submit">Отправить</button>
      </form>

      <div className="review-section__list">
        <h3>
          <span id="blue-point" /> Комментарии
        </h3>

        <ul>
          {reviews?.results.map((review) => (
            <li key={review.id} className="review">
              <div className="review__author">
                <img
                  id="author-img"
                  src={review.author.image}
                  alt="Author Image"
                />
                <div className="review__header">
                  <h5 className="review__author-name">
                    {review.author.first_name}
                    {review.author.last_name}
                  </h5>
                  <div className="review__date">
                    <Image src={calendar} alt="Calendar Icon" />
                    <p>
                      {months[review.created_at.slice(5, 7)]}{" "}
                      {review.created_at.slice(5, 7).slice(0, 1) ===
                      "0"
                        ? review.created_at.slice(6, 7)
                        : review.created_at.slice(5, 7)}
                      , {review.created_at.slice(0, 4)}
                    </p>
                  </div>
                </div>
              </div>
              <p className="review__description">{review.review}</p>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
};

export default ReviewSection;
