"use client";

import { useState, useTransition } from "react";
import ConfirmationModal from "./ConfirmationModalComponent";
import Modal from "./Modal";
import ArticleEditionFormComponent from "./ArticleEditionForm";
import Image from "next/image";
import Link from "next/link";

type Article = {
  id: number;
  title: string;
  description: string;
  content: string;
  date_creation: string | Date;
  publication_state: boolean;
  tags: { id: number; name: string }[];
  image?: { path: string };
  author?: { id: number; name: string };
};

type ArticleComponentProps = {
  article: Article;
};

export default function AdminArticleComponent({
  article,
}: ArticleComponentProps) {
  const [isConfirmOpen, setIsConfirmOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [, startTransition] = useTransition();

  const handlePublicationChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const newState = e.target.checked;
    startTransition(() => {
      fetch(
        `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"}/api/articles/${article.id}/publication`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({ publication_state: newState }),
        }
      );
    });
  };

  const confirmDelete = async (id: number) => {
    await fetch(
      `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"}/api/articles/${id}`,
      {
        method: "DELETE",
        credentials: "include",
      }
    );
  };

  const openDeleteConfirmation = async () => {
    setIsConfirmOpen(true);
  };

  return (
    <tr>
      <td className="px-6 py-4 text-sm text-gray-900">{article.title}</td>
      <td className="px-6 py-4 text-sm text-gray-900">
        {(() => {
          const date =
            typeof article.date_creation === "string"
              ? new Date(article.date_creation)
              : article.date_creation;
          if (date instanceof Date && !isNaN(date.getTime())) {
            const day = String(date.getDate()).padStart(2, "0");
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
          }
          return "";
        })()}
      </td>
      <td className="px-6 py-4 text-sm text-gray-900">{article.description}</td>
      <td className="px-6 py-4 text-sm text-gray-900">
        {article.tags.map((tag: { id: number; name: string }) => (
          <span key={tag.id} className="mr-1 text-gray-700">
            #{tag.name}
          </span>
        ))}
      </td>
      <td className="px-6 py-4 text-sm text-gray-900 flex items-center justify-end gap-2">
        <Link
          href={`${process.env.NEXT_PUBLIC_LINKEDIN_SHARE_URL}${article.id}`}
          target="_blank"
          rel="noopener noreferrer"
        >
          <Image
            className="invert mr-2"
            src={"/images/icons/LinkedIn_icon.svg"}
            alt="LinkedIn icon"
            width={20}
            height={20}
          />
        </Link>

        <label className="text-sm text-gray-700">
          Publier l&apos;article :
        </label>
        <input
          type="checkbox"
          name="publicationState"
          onChange={handlePublicationChange}
          defaultChecked={article.publication_state}
          className="h-4 w-4 text-blue-600 border-gray-300 rounded"
        />
        <button
          type="button"
          className="bg-[#100D2B] text-white px-4 py-2 rounded"
          onClick={() => setIsModalOpen(true)}
        >
          Modifier
        </button>

        <button
          type="button"
          className="bg-red-600 text-white px-4 py-2 rounded"
          onClick={openDeleteConfirmation}
        >
          Supprimer
        </button>

        <ConfirmationModal
          isOpen={isConfirmOpen}
          title="Confirmer la suppression"
          message="Es-tu sûr de vouloir supprimer cet article ?"
          confirmText="Oui, supprimer"
          cancelText="Annuler"
          onConfirm={() => confirmDelete(article.id)}
          onCancel={() => setIsConfirmOpen(false)}
        />

        <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
          <ArticleEditionFormComponent
            editionTitle="Modifier un article"
            editionSubmitButton="Modifier l'article"
            action="edit"
            article={article}
            onSuccess={() => setIsModalOpen(false)}
          />
        </Modal>
      </td>
    </tr>
  );
}
