"use client";

import { Reveal } from "@/components/landing-page/Reveal";
import { error, loading, successCallback } from "@/config/swal";
import { getFeedback, postUserFeedback } from "@/service/landing/landing";
import React, { useEffect, useState } from "react";
import { any } from "zod";

interface RatingProps {
  label: string;
  onRate: (rating: number) => void;
}

const Rating: React.FC<RatingProps> = ({ label, onRate }) => {
  const [selected, setSelected] = useState<number>(0);

  const handleClick = (rating: number) => {
    setSelected(rating);
    onRate(rating);
  };

  return (
    <div className="flex justify-between items-center mb-4">
      <span className="text-gray-800">{label}</span>
      <div className="flex space-x-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <button key={star} onClick={() => handleClick(star)} className={`text-2xl ${star <= selected ? "text-yellow-500" : "text-gray-300"}`}>
            ★
          </button>
        ))}
      </div>
    </div>
  );
};

const FeedbackForm: React.FC = () => {
  const [ratings, setRatings] = useState({
    accessibility: 0,
    appearance: 0,
    content: 0,
  });

  useEffect(() => {
    async function initState() {
      const response = await getFeedback();
      console.log(response?.data?.data);
      setRatings(response?.data?.data);
    }

    initState();
  }, []);

  type Feedback = {
    feedbackId: any;
    score: any;
  };
  
  const [userFeedbacks, setUserFeedbacks] = useState<Feedback[]>([]);
  const [hasMounted, setHasMounted] = useState(false);

  const handleRatingChange = (id: any, score: any) => {
    const listData = [...userFeedbacks];
    const dataIdx = userFeedbacks.findIndex((o) => o.feedbackId === id);
    

    console.log("idx :", dataIdx);
    console.log("Before :", listData);
  
    if (dataIdx !== -1) {
      console.log("update");
      listData[dataIdx].score = score;
    } else {
      const data = {
        feedbackId: id,
        score,
      };
  
      listData.push(data);
    }
  
    setUserFeedbacks(listData);
    console.log("After :", userFeedbacks);
  };
  const handleSubmit = async () => {
    loading();
    console.log("Save Feedback :", userFeedbacks);
    const response = await postUserFeedback();
    close();
    if (response?.error) {
      error(response?.message);
      return false;
    }

    successCallback("Terima kasih, feedback Anda telah terkirim");
  };
  async function onSubmit() {
    //     loading();
    //     let finalData = {
    //       name: data.name,
    //       email: data.email,
    //       title : data.title,
    //       message: data.title
    //     }
    //     console.log(finalData);
    //     const response = await sendMessage(finalData);
    //     close();
    //     successCallback();
  }

  // Hooks
  useEffect(() => {
    setHasMounted(true);
  }, []);

  // Render
  if (!hasMounted) return null;

  return (
    <Reveal>
      <div className="max-w-6xl flex flex-col mx-auto p-4 lg:p-40 gap-5">
        <div className="flex items-center justify-center mb-6">
          <img src="/assets/icons-feedback.png" alt="Feedback" />
          <h2 className="ml-4 text-[15px] lg:text-[32px] font-bold text-gray-800">Feedback Pengguna</h2>
        </div>
        <Rating label="Silakan berikan rating Anda terkait dengan kemudahan akses website MediaHUB Polri" onRate={(rating) => handleRatingChange("accessibility", rating)} />
        <Rating label="Silakan berikan rating Anda terkait dengan tampilan website MediaHUB Polri" onRate={(rating) => handleRatingChange("appearance", rating)} />
        <Rating label="Silakan berikan rating Anda terkait dengan konten MediaHUB Polri" onRate={(rating) => handleRatingChange("content", rating)} />
        <div className="flex justify-center">
          <button onClick={handleSubmit} className="w-fit lg:w-32 bg-[#2F80ED] text-white py-2 px-4 gap-4 rounded-md hover:bg-blue-600 transition">
            Kirim
          </button>
        </div>
      </div>
    </Reveal>
  );
};

export default FeedbackForm;
