import { useState } from "react";
import { X, Plus, Trash2, Save } from "lucide-react";
import { motion } from "motion/react";

export function SettingsModal({
  chapters,
  logoUrl,
  candidateName,
  setChapters,
  onClose,
}: {
  chapters: any[];
  logoUrl: string;
  candidateName: string;
  setChapters: any;
  onClose: () => void;
}) {
  const [localChapters, setLocalChapters] = useState([...chapters]);
  const [localLogo, setLocalLogo] = useState(logoUrl);
  const [localCandidateName, setLocalCandidateName] = useState(candidateName);
  const [localApiKey, setLocalApiKey] = useState(
    typeof window !== "undefined"
      ? localStorage.getItem("rms_gemini_api_key") || ""
      : "",
  );

  const updateChapter = (index: number, field: string, value: string) => {
    const updated = [...localChapters];
    updated[index] = { ...updated[index], [field]: value };
    setLocalChapters(updated);
  };

  const addChapter = () => {
    const nextId =
      localChapters.length > 0
        ? `C${parseInt(localChapters[localChapters.length - 1].id.replace("C", "")) + 1}`
        : "C1";
    setLocalChapters([...localChapters, { id: nextId, title: "", desc: "" }]);
  };

  const removeChapter = (index: number) => {
    const updated = [...localChapters];
    updated.splice(index, 1);
    setLocalChapters(updated);
  };

  const handleSave = () => {
    localStorage.setItem("rms_gemini_api_key", localApiKey);
    setChapters(localChapters, localLogo, localCandidateName);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-[200] bg-slate-50/90 backdrop-blur-md flex items-center justify-center p-4 sm:p-8 animate-in fade-in duration-300">
      <div className="w-full max-w-4xl max-h-[90vh] bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.15)] rounded flex flex-col relative overflow-hidden animate-in slide-in-from-bottom-4 duration-300">
        <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.1)_2px,rgba(4,79,84,0.1)_4px)]"></div>

        <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center relative z-10 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-[#044f54] flex items-center justify-center text-white font-black uppercase text-xs tracking-widest rounded-sm shadow-[0_0_15px_rgba(4,79,84,0.5)]">
              ADM
            </div>
            <div className="flex flex-col">
              <span className="text-[#044f54] font-bold text-sm tracking-widest uppercase">
                System Settings
              </span>
              <span className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-widest">
                Admin Authorization Confirmed
              </span>
            </div>
          </div>
          <button
            onClick={onClose}
            className="text-[#044f54]/60 hover:text-[#044f54] transition-colors bg-[#044f54]/10 hover:bg-[#044f54]/20 p-1.5 rounded"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 relative z-10 overflow-y-auto flex-1 bg-slate-50 text-[#044f54]">
          <div className="mb-6 space-y-4">
            <div className="space-y-1">
              <h3 className="text-lg font-serif italic tracking-wider">
                General Settings
              </h3>
              <p className="text-[#044f54]/60 text-xs font-mono tracking-widest uppercase">
                Configure global application variables.
              </p>
            </div>
            <div className="flex flex-col gap-1 p-4 border border-[#044f54]/20 rounded relative group focus-within:border-[#044f54]/50 transition-colors bg-white">
              <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                Candidate Name
              </label>
              <input
                value={localCandidateName}
                onChange={(e) => setLocalCandidateName(e.target.value)}
                className="bg-transparent border-b border-[#044f54]/20 focus:border-[#044f54] outline-none text-sm font-medium pb-1 text-[#044f54] w-full"
                placeholder="e.g. Agent Trainee"
              />
            </div>
            <div className="flex flex-col gap-1 p-4 border border-[#044f54]/20 rounded relative group focus-within:border-[#044f54]/50 transition-colors bg-white">
              <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                Header Logo Image URL
              </label>
              <input
                value={localLogo}
                onChange={(e) => setLocalLogo(e.target.value)}
                className="bg-transparent border-b border-[#044f54]/20 focus:border-[#044f54] outline-none text-sm font-medium pb-1 text-[#044f54] w-full"
                placeholder="e.g. https://example.com/logo.png"
              />
            </div>

            <div className="flex flex-col gap-1 rounded bg-[#044f54]/5 p-4 border border-[#044f54]/10">
              <span className="text-[10px] font-mono font-bold text-[#044f54] uppercase tracking-wider">
                Current AI Core Agent Model
              </span>
              <span className="text-sm font-mono text-[#044f54]/80 mt-1">
                gemini-3.1-flash-live-preview
              </span>
              <span className="text-[10px] text-[#044f54]/60 italic mt-1">
                This is the latest multi-lingual, multimodal live agent model.
              </span>
            </div>

            <div className="flex flex-col gap-1 p-4 border border-[#044f54]/20 rounded relative group focus-within:border-[#044f54]/50 transition-colors bg-white">
              <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                Custom Gemini API Key (Optional)
              </label>
              <input
                type="password"
                value={localApiKey}
                onChange={(e) => setLocalApiKey(e.target.value)}
                className="bg-transparent border-b border-[#044f54]/20 focus:border-[#044f54] outline-none text-sm font-medium pb-1 text-[#044f54] w-full"
                placeholder="Leave blank to use default application key"
              />
            </div>
          </div>
          <div className="mb-6 space-y-1 mt-8">
            <h3 className="text-lg font-serif italic tracking-wider">
              Chapter Knowledge Base
            </h3>
            <p className="text-[#044f54]/60 text-xs font-mono tracking-widest uppercase">
              Configure the knowledge and rubrics passed to the AI.
            </p>
          </div>

          <div className="space-y-4">
            {localChapters.map((chapter, i) => (
              <div
                key={i}
                className="p-4 border border-[#044f54]/20 rounded relative group focus-within:border-[#044f54]/50 transition-colors bg-white"
              >
                <div className="grid grid-cols-[100px_1fr] sm:grid-cols-[100px_1fr_auto] gap-4">
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                      ID
                    </label>
                    <input
                      value={chapter.id}
                      onChange={(e) => updateChapter(i, "id", e.target.value)}
                      className="bg-transparent border-b border-[#044f54]/20 focus:border-[#044f54] outline-none text-sm font-mono pb-1 text-[#044f54]"
                    />
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                      Title
                    </label>
                    <input
                      value={chapter.title}
                      onChange={(e) =>
                        updateChapter(i, "title", e.target.value)
                      }
                      className="bg-transparent border-b border-[#044f54]/20 focus:border-[#044f54] outline-none text-sm font-medium pb-1 text-[#044f54]"
                      placeholder="e.g. The Core Belief"
                    />
                  </div>
                  <div className="flex items-center justify-end col-span-2 sm:col-span-1">
                    <button
                      onClick={() => removeChapter(i)}
                      className="p-1.5 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                      title="Remove Chapter"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
                <div className="mt-4 flex flex-col gap-1">
                  <label className="text-[10px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                    Evaluation Rubric / Description
                  </label>
                  <textarea
                    value={chapter.desc}
                    onChange={(e) => updateChapter(i, "desc", e.target.value)}
                    className="bg-transparent border border-[#044f54]/20 focus:border-[#044f54] outline-none rounded p-2 text-sm text-[#044f54] w-full min-h-[60px] resize-y"
                    placeholder="Describe what the AI should evaluate in this chapter..."
                  />
                </div>
              </div>
            ))}
          </div>

          <button
            onClick={addChapter}
            className="mt-6 flex items-center gap-2 px-4 py-2 border border-[#044f54]/30 text-[#044f54] hover:bg-[#044f54]/10 rounded transition-colors text-xs font-mono uppercase tracking-widest"
          >
            <Plus className="w-4 h-4" /> Add Chapter
          </button>
        </div>

        <div className="p-4 border-t border-[#044f54]/30 bg-[#044f54]/5 relative z-10 shrink-0 flex justify-end">
          <button
            onClick={handleSave}
            className="flex items-center gap-2 px-6 py-2 bg-[#044f54] text-white hover:bg-[#044f54]/90 rounded transition-colors text-xs font-bold uppercase tracking-widest"
          >
            <Save className="w-4 h-4" /> Save Configuration
          </button>
        </div>
      </div>
    </div>
  );
}
