'use client';

import { useEffect, useState } from "react";

interface Props {
  open: boolean;
  columns: any[];
  initialData?: any;
  onClose: () => void;
  onSave: (data: any) => void;
  emptyForm: Record<string,string>;
}

export function ReferentielModal({
  open,
  columns,
  initialData,
  onClose,
  onSave,
  emptyForm
}: Props) {
  const [form, setForm] = useState(emptyForm);

  useEffect(() => {
    setForm(initialData || {});
  }, [initialData]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" />
      <div className="relative w-[720px] max-h-[85vh] overflow-hidden bg-white rounded-3xl shadow-2xl border border-[#e6efe9] flex flex-col">
        <div className="px-4 py-3 border-b border-[#edf2ef] bg-gradient-to-r from-[#f4fbf7] to-white">
          <h2 className="text-xl font-semibold text-[#1f5f4a]">
            Référentiel
          </h2>

          <div className="p-4 overflow-y-auto">
            <div className="grid md:grid-cols-2 gap-2">
              {columns.map((column) => (
                <div key={column.key} className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-[#2f5d4b]">
                    {column.label}
                  </label>

                  <input
                    className="w-full rounded-xl border border-[#d8e6df] px-2 py-2
                         focus:outline-none focus:ring-2 focus:ring-[#2f7d5f]/30
                         focus:border-[#2f7d5f]
                         transition"
                    value={form[column.key] || ""}
                    onChange={(e) =>
                      setForm({
                        ...form,
                        [column.key]: e.target.value
                      })
                    }
                  />
                </div>
              ))}
            </div>
          </div>

          <div className="px-1 py-1 border-t border-[#edf2ef] bg-[#fafdfb] flex justify-end gap-1">
            <button
              onClick={onClose}
              className="px-1 py-1 rounded-xl border border-[#d8e6df] text-[#2f5d4b]
                   hover:bg-[#f3faf7] transition cursor-pointer"
            >
              Annuler
            </button>

            <button
              onClick={() => {
                onSave(form);
                setForm(emptyForm);
              }
              }
              className="
        px-1 py-1
        rounded-xl
        bg-[#2f7d5f]
        text-white text-sm font-medium
        hover:bg-[#256b52]
        transition
        cursor-pointer
      "
            >
              Enregistrer
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}