'use client';

import { createObjectifConvention, deleteObjectifConvention, getObjectifsConvention, updateObjectifConvention } from "../../../api/acc_convention";
import { useEffect, useState } from "react";

export default function ObjectifList({ selectedConvention }: any) {
  const [objectifsConvention, setObjectifsConvention] = useState([]);
  const [selectedObjectifConvention, setSelectedObjectifConvention] = useState<any>(null);
  const [isEditingObjectifConvention, setIsEditingObjectifConvention] = useState(false);

  const [objectifForm, setObjectifForm] = useState({
    id: null,
    description_objectif: ""
  });

  const fetchObjectifsConvention = async () => {
    try {
      const conventionsData =
        await getObjectifsConvention(
          selectedConvention.id
        );

      setObjectifsConvention(conventionsData);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    if (!selectedConvention) return;

    fetchObjectifsConvention();
  }, [selectedConvention]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;

    setObjectifForm((prev: any) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleDeleteObjectif = async (id: string) => {
    try {
      await deleteObjectifConvention(id);

      if (selectedObjectifConvention?.id === id) {
        setSelectedObjectifConvention(null);

        setObjectifForm({
          id: null,
          description_objectif: ""
        });

        setIsEditingObjectifConvention(false);
      }

      await fetchObjectifsConvention();
    } catch (error) {
      console.error(error);
    }
  };

  const handleSaveObjectif = async () => {
    const payload = {
      description_objectif: objectifForm.description_objectif,
      id_reference_convention: selectedConvention.id
    };

    try {
      if (objectifForm?.id) {
        await updateObjectifConvention(objectifForm.id, payload);
      } else {
        await createObjectifConvention(payload);
      }
      await fetchObjectifsConvention();
      setIsEditingObjectifConvention(false);
    } catch (error) {
      console.error(error);
    }
  };

  if (!selectedConvention) {
    return (
      <div className="border rounded-xl p-4 flex items-center justify-center text-gray-400">
        Sélectionnez une convention
      </div>
    );
  }

  return (
    <div className="bg-white border border-[#dce8e2] rounded-xl p-3 overflow-y-auto">
      <div className="flex justify-between mb-1">
        <h3 className="font-semibold text-[#1f5f4a]">Objectifs</h3>
        <button
          className="inline-flex items-center gap-2
      px-1 py-1
      rounded-xl
      bg-gradient-to-r from-[#2f7d5f] to-[#3f9b74]
      text-white font-semibold
      shadow-md
      transition-all
      hover:-translate-y-0.5
      hover:shadow-lg
      cursor-pointer"
          onClick={() => {
            setIsEditingObjectifConvention(true);

            setObjectifForm({
              id: null,
              description_objectif: ""
            });
          }}
        >
          + Ajouter
        </button>

      </div>

      {isEditingObjectifConvention && (
        <div className="space-y-1 mb-3">
          <input
            className="text-xs font-medium p-2 h-6 rounded-lg border
        focus:outline-none focus:ring-2 focus:ring-[#2f7d5f]/20"
            placeholder="Description objectif"
            name="description_objectif"
            value={objectifForm.description_objectif}
            onChange={handleChange}
          />
          <button
            onClick={handleSaveObjectif}
            className="inline-flex items-center gap-2
      px-1 py-1
      rounded-xl
      bg-gradient-to-r from-[#2f7d5f] to-[#3f9b74]
      text-white font-semibold
      shadow-md
      transition-all
      hover:-translate-y-0.5
      hover:shadow-lg
      cursor-pointer">
            Enregistrer
          </button>

        </div>
      )}

      {objectifsConvention.length < 1 && (
        <div className="border rounded-xl p-4 flex items-center justify-center text-gray-400">
          Aucun objectif renseigné
        </div>
      )}

      <div className="space-y-2">
        {objectifsConvention.map((o: any) => (
          <div
            key={o.id}
            onClick={() => {
              setSelectedObjectifConvention(o);
              setObjectifForm({
                id: o.id,
                description_objectif: o.description_objectif,
              });
              setIsEditingObjectifConvention(true);
            }}
            className={`p-2 rounded-lg cursor-pointer ${selectedObjectifConvention?.id === o.id
              ? "bg-green-100 border border-green-600"
              : "bg-gray-50"}`}
          >
            <div className="flex items-center justify-between gap-2">
              <span className="font-medium text-sm">
                {o.description_objectif}
              </span>

              <button
                onClick={(e) => {
                  e.stopPropagation();
                  handleDeleteObjectif(o.id);
                }}
                className="px-1 py-1
    text-xs font-semibold
    rounded-lg
    text-red-600
    bg-white
    border border-red-200
    hover:bg-red-50
    hover:border-red-300
    hover:shadow-sm
    active:scale-[0.98]
    transition
    cursor-pointer"              >
                🗑️
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}