import React, { useState, useEffect } from "react";
import { Author, User } from "../types/auth.ts";


interface AuthorModalProps {
  open: boolean;
  onClose: () => void;
  onSave: (author: Partial<Author>) => void;
  author?: Author | null;
  users: User[];
}

const AuthorModal: React.FC<AuthorModalProps> = ({ open, onClose, onSave, author, users }) => {
  const [displayName, setDisplayName] = useState("");
  const [bio, setBio] = useState("");
  const [userId, setUserId] = useState<string | undefined>(undefined);

  useEffect(() => {
    if (author) {
      setDisplayName(author.displayName || "");
      setBio(author.bio || "");
      setUserId(author.userId);
    } else {
      setDisplayName("");
      setBio("");
      setUserId(undefined);
    }
  }, [author, open]);

  const handleSubmit = () => {
    onSave({
      id: author?.id,
      displayName,
      bio,
      userId: userId || undefined,
    });
    onClose();
  };

  if (!open) return null;

  return (
      <div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
        <div className="bg-white rounded p-4 w-[400px] shadow-xl">
          <h2 className="text-lg font-bold mb-2">{author ? "Редактировать" : "Создать"} автора</h2>

          <label className="block text-sm mb-1">Имя</label>
          <input
              className="w-full border rounded px-2 py-1 mb-3"
              value={displayName}
              onChange={(e) => setDisplayName(e.target.value)}
          />

          <label className="block text-sm mb-1">Биография</label>
          <textarea
              className="w-full border rounded px-2 py-1 mb-3"
              value={bio}
              onChange={(e) => setBio(e.target.value)}
          />

          <label className="block text-sm mb-1">Пользователь</label>
          <select
              className="w-full border rounded px-2 py-1 mb-4"
              value={userId || ""}
              onChange={(e) => setUserId(e.target.value || undefined)}
          >
            <option value="">— не связан —</option>
            {users.map((user) => (
                <option key={user.id} value={user.id}>
                  {user.displayName}
                </option>
            ))}
          </select>

          <div className="flex justify-end gap-2">
            <button className="px-3 py-1 border rounded" onClick={onClose}>Отмена</button>
            <button className="px-3 py-1 bg-blue-600 text-white rounded" onClick={handleSubmit}>
              Сохранить
            </button>
          </div>
        </div>
      </div>
  );
};

export default AuthorModal;
