import React, { useState } from 'react';
import { Server, Square } from 'lucide-react';
import { Modal } from './ui/Modal';
import { SpawnInstanceForm } from './forms/SpawnInstanceForm';

interface InstancesPanelProps {
  api: any;
  instances: any[];
  onRefresh: () => void;
  onSpawnSuccess: (msg: string) => void;
  onSpawnError: (msg: string) => void;
  onStopSuccess: (msg: string) => void;
  onStopError: (msg: string) => void;
}

export function InstancesPanel({
  api,
  instances,
  onRefresh,
  onSpawnSuccess,
  onSpawnError,
  onStopSuccess,
  onStopError,
}: InstancesPanelProps) {
  const [showSpawnModal, setShowSpawnModal] = useState(false);

  const handleStopInstance = async (id: string) => {
    try {
      await api.post(`/instances/${id}/stop`);
      onStopSuccess(`School process ${id} terminated`);
      onRefresh();
    } catch (err: any) {
      onStopError(err.message || 'Failed to stop instance');
    }
  };

  return (
    <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-xl p-6 space-y-6">
      <div className="flex items-center justify-between border-b border-border pb-4">
        <div>
          <h2 className="text-lg font-bold text-foreground flex items-center gap-2">
            <Server className="w-5 h-5 text-amber-500" />
            Spawned Multi-School Server Instances
          </h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            Isolated server & client process orchestrator per subscribing school
          </p>
        </div>
        <button
          onClick={() => setShowSpawnModal(true)}
          className="px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-xl text-xs font-bold transition-all shadow-sm"
        >
          + Spawn New School Instance
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {instances.length > 0 ? (
          instances.map(inst => (
            <div key={inst.id} className="p-5 rounded-2xl bg-muted/40 border border-border flex flex-col justify-between space-y-3">
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="font-bold text-foreground text-sm">{inst.name}</h4>
                  <p className="text-xs font-mono text-muted-foreground">{inst.code} | ID: {inst.id}</p>
                </div>
                <span className={`px-2.5 py-0.5 rounded-full text-[0.65rem] font-black uppercase border ${inst.status === 'RUNNING' ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20' : 'bg-rose-500/10 text-rose-500 border-rose-500/20'}`}>
                  {inst.status}
                </span>
              </div>

              <div className="grid grid-cols-2 gap-2 text-xs font-mono bg-background p-3 rounded-xl border border-border">
                <div><span className="text-muted-foreground">Server Port:</span> <span className="font-bold text-primary">{inst.server_port}</span></div>
                <div><span className="text-muted-foreground">Client Port:</span> <span className="font-bold text-amber-500">{inst.client_port}</span></div>
                <div><span className="text-muted-foreground">PID:</span> {inst.pid || 'N/A'}</div>
                <div className="truncate"><span className="text-muted-foreground">DB:</span> {inst.db_path}</div>
              </div>

              <div className="flex items-center justify-end gap-2 pt-2">
                {inst.status === 'RUNNING' && (
                  <button
                    onClick={() => handleStopInstance(inst.id)}
                    className="px-3 py-1.5 bg-rose-500/10 hover:bg-rose-500 text-rose-500 hover:text-white rounded-lg text-xs font-bold transition-all border border-rose-500/20 flex items-center gap-1"
                  >
                    <Square size={12} /> Stop Process
                  </button>
                )}
              </div>
            </div>
          ))
        ) : (
          <div className="col-span-2 py-12 text-center text-muted-foreground font-mono">
            No active spawned school instances. Click "Spawn New School Instance" to launch one.
          </div>
        )}
      </div>

      <Modal
        open={showSpawnModal}
        onClose={() => setShowSpawnModal(false)}
        title="Spawn School Instance"
        subtitle="Provision Isolated Server & Client Child Process"
        icon={Server}
        watermarkIcon={Server}
        maxWidth="max-w-md"
      >
        <SpawnInstanceForm
          api={api}
          onSuccess={(port) => {
            setShowSpawnModal(false);
            onSpawnSuccess(`Spawned server process on port ${port}`);
            onRefresh();
          }}
          onError={(msg) => onSpawnError(msg)}
        />
      </Modal>
    </div>
  );
}

export default InstancesPanel;
