import { useState } from "react";
import type { Instance } from "../types";
import { sendDeleteInstanceRequest, sendModifyInstanceRequest } from "../api";
import InstanceConsole from "./InstanceConsole";

type Props = {
  instance: Instance;
  onClose: () => void;
  onDeleted: () => void;
  onSaved: () => void;
};


export default function InstanceDetail({ instance, onClose, onDeleted, onSaved }: Props) {
  const [activeTab, setActiveTab] = useState<"general" | "config" | "console" | "danger">("general");
  
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [purgeFiles, setPurgeFiles] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  
  const [form, setForm] = useState({ name: instance.name, port: String(instance.port) });
  const [modifyLoading, setModifyLoading] = useState(false);
  const [modifyError, setModifyError] = useState<string | null>(null);

  const isRunning = instance.status === "RUNNING";

  async function handleDelete() {
    setDeleteLoading(true);
    setDeleteError(null);
    try {
      await sendDeleteInstanceRequest(instance.name, purgeFiles);
      onDeleted();
    } catch (e: any) {
      setDeleteError(e.message ?? String(e));
    } finally {
      setDeleteLoading(false);
    }
  }

  async function handleModify() {
    setModifyLoading(true);
    setModifyError(null);
    try {
      await sendModifyInstanceRequest(instance.name, form.name, parseInt(form.port));
      onSaved();
    } catch (e: any) {
      setModifyError(e.message ?? String(e));
    } finally {
      setModifyLoading(false);
    }
  }

  return (
    <div className="instanceDetail">
      <button onClick={onClose}>← Back</button>
      <h2>{instance.name}</h2>

      <div className="tabBar">
        <button onClick={() => setActiveTab("general")}>General</button>
        <button onClick={() => setActiveTab("config")}>Configuration</button>
        <button onClick={() => setActiveTab("console")}>Console</button>
        <button onClick={() => setActiveTab("danger")}>Danger Zone</button>
      </div>

      <div className="tabContent">
        {activeTab === "general" && 
          <div className="tabContent">
            <p><b>Version:</b> {instance.version}</p>
            <label>Name
              <input type="text" name="name" value={form.name} onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))} disabled={isRunning} />
            </label>
            <label>Port
              <input type="text" name="port" value={form.port} onChange={e => setForm(prev => ({ ...prev, port: e.target.value }))} disabled={isRunning} />
            </label>
            {isRunning && <p className="warningText">Stop the server to edit these fields.</p>}

            {modifyError && <div className="error">Error: {modifyError}</div>}
            <button disabled={isRunning || modifyLoading} onClick={handleModify}>
              {modifyLoading ? "Saving..." : "Save"}
            </button>
            
          </div>
        }

        {activeTab === "config" && <p>Config (coming soon)</p>}

        {activeTab === "console" && <InstanceConsole instance={instance} />}

        {activeTab === "danger" && 
          <div className="dangerZone">
            <h3>Danger Zone</h3>


            {!showDeleteConfirm && (
              <button className="deleteButton" onClick={() => setShowDeleteConfirm(true)}
                disabled={instance.status === "RUNNING"}>
                Delete Instance
              </button>
            )}
            {instance.status === "RUNNING" && <p className="warningText">Stop the server before deleting.</p>}

            {showDeleteConfirm && (
              <div className="dangerConfirm">
                <p>Are you sure you want to delete <b>{instance.name}</b>?</p>
                <p><b>THIS ACTION CANNOT BE UNDONE</b></p>
                <label>
                  <input type="checkbox" checked={purgeFiles} onChange={e => setPurgeFiles(e.target.checked)} />
                  Also delete all instance files from disk
                </label>
                {deleteError && <div className="error">Error: {deleteError}</div>}
                <div className="flexboxHorizontal">
                  <button className="deleteButton" onClick={handleDelete} disabled={deleteLoading}>
                    {deleteLoading ? "Deleting..." : "Confirm Delete"}
                  </button>
                  <button className="normalButton" onClick={() => setShowDeleteConfirm(false)}>Cancel</button>
                </div>
              </div>
            )}
          </div>
        }
      </div>
    </div>
  );
}