"use client";

import React, { useEffect, useState } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import Sidebar from "../../components/sidebar";

const BASE_URL = "https://app.modstagram.ir/api/v1";

const LicensesPage = () => {
  const [licenses, setLicenses] = useState([]);
  const [loading, setLoading] = useState(true);

  // گرفتن لایسنس‌ها
  const fetchLicenses = async () => {
    try {
      setLoading(true);
      const token = Cookies.get("token");
      if (!token) {
      }

      const response = await axios.get(`${BASE_URL}/users/License`, {
        headers: { Authorization: `Bearer ${token}` },
      });

      setLicenses(response.data.licenses || []);
    } catch (error) {
      console.error("Error fetching licenses:", error);
      //   toast.error("خطا در دریافت لایسنس‌ها");
    } finally {
      setLoading(false);
    }
  };

  // تغییر وضعیت تایید
  const toggleConfirmation = async (userId, currentStatus) => {
    try {
      const token = Cookies.get("token");
      const newStatus = !currentStatus;

      const response = await axios.put(
        `${BASE_URL}/users/License/${userId}`,
        { Confirmation: newStatus },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );

      if (response.status === 200) {
        // toast.success(`وضعیت به ${newStatus ? "تأیید" : "عدم تأیید"} تغییر یافت`);
        fetchLicenses();
      }
    } catch (error) {
      console.error("Error updating confirmation:", error);
      //   toast.error("خطا در تغییر وضعیت تایید");
    }
  };

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

  return (
    <div className="min-h-screen w-full bg-gray-900 flex text-gray-100 ">
      <div className="  w-64">
        <Sidebar />
      </div>
      <div className="w-full h-full p-4 mb-11 mx-auto  text-white">
        <h1 className="text-3xl font-bold mb-8 text-center pt-6">
          📜 لیست لایسنس کاربران
        </h1>

        {loading ? (
          <div className="text-center text-gray-400">در حال بارگذاری...</div>
        ) : licenses.length === 0 ? (
          <div className="text-center text-gray-400">هیچ لایسنسی یافت نشد</div>
        ) : (
          <div className="flex justify-center flex-row flex-wrap px-24 items-center gap-6 ">
            {licenses
              .map((item) => (
                <div
                  key={item._id}
                  className="bg-gray-800 max-w-96 min-w-96 rounded-2xl shadow-lg p-4 flex flex-col items-center transition-all hover:shadow-xl"
                >
                  {item.licenseImg ? (
                    <img
                      src={item.licenseImg}
                      alt="license"
                      className="w-40 h-40 object-cover rounded-xl border border-gray-700 mb-4"
                    />
                  ) : (
                    <div className="w-40 h-40 flex items-center justify-center bg-gray-700 rounded-xl mb-4 text-sm text-gray-400">
                      بدون تصویر
                    </div>
                  )}

                  <div className="w-full text-center space-y-1">
                    <p className="text-lg font-semibold">
                      {item.user?.first_name || ""} {item.user?.last_name || ""}
                    </p>
                    <p className="text-sm text-gray-400">
                      @{item.user?.user_name}
                    </p>
                    <p
                      className={`text-sm font-medium ${
                        item.user?.is_verified === "true"
                          ? "text-green-400"
                          : "text-red-400"
                      }`}
                    >
                      {item.user?.is_verified === "true"
                        ? "تأیید شده"
                        : "تأیید نشده"}
                    </p>
                    <p className="text-xs text-gray-500">
                      {item.createdAt} | {item.updatedAt}
                    </p>
                  </div>

                  <button
                    onClick={() =>
                      toggleConfirmation(item.userId?._id, item.Confirmation)
                    }
                    className={`mt-4 px-4 py-2 rounded-lg font-medium ${
                      item.Confirmation
                        ? "bg-red-600 hover:bg-red-700"
                        : "bg-green-600 hover:bg-green-700"
                    }`}
                  >
                    {item.Confirmation ? "لغو تأیید" : "تأیید کاربر"}
                  </button>
                </div>
              ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default LicensesPage;
