import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { POLLING } from '../../lib/constants.js';
import { usePictureInPicture } from '../../lib/usePictureInPicture.js';
import { PipButton } from './PipButton.js';

const BASE = '/api/local/browser/sessions';

interface SessionInfo {
  id: string;
  userId?: string;
  state: string;
  novncPath: string;
  lockedByJobId: string | null;
  createdAt: string;
}

async function fetchSessions(): Promise<SessionInfo[]> {
  const res = await fetch(BASE);
  const data = await res.json();
  return data.sessions ?? [];
}

async function createSession(): Promise<SessionInfo> {
  const res = await fetch(BASE, { method: 'POST', headers: { 'Content-Type': 'application/json' } });
  return res.json();
}

async function deleteSession(id: string): Promise<void> {
  await fetch(`${BASE}/${id}`, { method: 'DELETE' });
}

async function releaseSession(id: string): Promise<void> {
  await fetch(`${BASE}/${id}/release`, { method: 'POST' });
}

export function BrowserSessionPanel() {
  const queryClient = useQueryClient();
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);

  const sessionsQuery = useQuery({
    queryKey: ['browserSessions'],
    queryFn: fetchSessions,
    refetchInterval: POLLING.FAST,
  });

  const createMutation = useMutation({
    mutationFn: createSession,
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['browserSessions'] });
      setActiveSessionId(data.id);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: deleteSession,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['browserSessions'] });
      setActiveSessionId(null);
    },
  });

  const releaseMutation = useMutation({
    mutationFn: releaseSession,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['browserSessions'] });
    },
  });

  const sessions = sessionsQuery.data ?? [];
  const activeSession = sessions.find(s => s.id === activeSessionId);
  const pip = usePictureInPicture(
    activeSession?.novncPath ?? null,
    activeSession ? `noVNC — Session ${activeSession.id.slice(0, 8)}` : undefined,
  );

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold">Browser Sessions</h3>
        <button
          onClick={() => createMutation.mutate()}
          disabled={createMutation.isPending}
          className="px-3 py-1 text-xs bg-accent text-accent-fg rounded hover:bg-accent-deep disabled:opacity-50"
        >
          New Session
        </button>
      </div>

      {sessions.length === 0 && (
        <p className="text-xs text-gray-400">No active sessions</p>
      )}

      {sessions.map(session => (
        <div key={session.id} className="border rounded-lg p-3 text-sm">
          <div className="flex items-center justify-between mb-2">
            <span className="font-mono text-xs">{session.id.slice(0, 8)}...</span>
            <span className={`px-2 py-0.5 rounded text-xs ${
              session.state === 'user_interactive' ? 'bg-yellow-100 text-yellow-700' :
              session.state === 'agent_controlled' ? 'bg-blue-100 text-blue-700' :
              'bg-gray-100 text-gray-700'
            }`}>
              {session.state}
            </span>
          </div>

          <div className="flex gap-2">
            <button
              onClick={() => setActiveSessionId(session.id)}
              className="px-2 py-1 text-xs bg-slate-100 rounded hover:bg-slate-200"
            >
              View
            </button>
            {session.state === 'user_interactive' && (
              <button
                onClick={() => releaseMutation.mutate(session.id)}
                className="px-2 py-1 text-xs bg-green-600 text-white rounded hover:bg-green-700"
              >
                Done
              </button>
            )}
            <button
              onClick={() => deleteMutation.mutate(session.id)}
              className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200"
            >
              Destroy
            </button>
          </div>
        </div>
      ))}

      {activeSession && (
        <div className="border rounded-lg overflow-hidden">
          <div className="bg-slate-100 px-3 py-1.5 text-xs flex items-center gap-2">
            <span>noVNC</span>
            <div className="ml-auto flex items-center gap-2">
              <PipButton pip={pip} />
              <button onClick={() => setActiveSessionId(null)} className="text-slate-400 hover:text-slate-600 px-1">
                &times;
              </button>
            </div>
          </div>
          {pip.isOpen ? (
            <div className="w-full h-[500px] flex items-center justify-center bg-slate-50 text-xs text-slate-500">
              PiP ウィンドウで表示中。閉じるとここに戻ります。
            </div>
          ) : (
            <iframe
              src={activeSession.novncPath}
              className="w-full h-[500px] border-0"
              title="Browser Session"
              allow="clipboard-read; clipboard-write"
            />
          )}
        </div>
      )}
    </div>
  );
}
