import { useState, useEffect } from "react";
import { getLanguageName } from "./melodyUtils";

export default function TranslationModal({
  open,
  onClose,
  field,
  value,
  onChange,
  languages,
  multiline = false,
}) {
  const [draft, setDraft] = useState({});

  useEffect(() => {
    if (open) {
      setDraft({ ...value });
    }
  }, [open, value]);

  if (!open) return null;

  const updateDraft = (lang, text) => {
    setDraft((prev) => ({ ...prev, [lang]: text }));
  };

  const handleSave = () => {
    onChange(draft);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="fixed inset-0 bg-black/60" onClick={onClose} />
      <div
        className="relative rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[80vh] overflow-y-auto border"
        style={{
          backgroundColor: "var(--bg-card)",
          borderColor: "var(--border-primary)",
        }}
      >
        <div className="p-6">
          <h3 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
            Translations — {field}
          </h3>
          <div className="space-y-3">
            {languages.map((lang) => (
              <div key={lang}>
                <label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
                  {getLanguageName(lang)}{" "}
                  <span className="font-mono text-xs uppercase" style={{ color: "var(--text-muted)" }}>
                    ({lang})
                  </span>
                </label>
                {multiline ? (
                  <textarea
                    value={draft[lang] || ""}
                    onChange={(e) => updateDraft(lang, e.target.value)}
                    rows={2}
                    className="w-full px-3 py-2 rounded-md text-sm border"
                  />
                ) : (
                  <input
                    type="text"
                    value={draft[lang] || ""}
                    onChange={(e) => updateDraft(lang, e.target.value)}
                    className="w-full px-3 py-2 rounded-md text-sm border"
                  />
                )}
              </div>
            ))}
          </div>
          <div className="flex justify-end gap-3 mt-6">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm rounded-md transition-colors"
              style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleSave}
              className="px-4 py-2 text-sm rounded-md transition-colors"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              Save Translations
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
