import { useEffect, useState } from 'react';
import { useVoiceStore } from '../stores/voice.ts';
import { saveDevicePref } from '../stores/voice.ts';

interface Props {
  onClose: () => void;
}

export function DeviceSettingsModal({ onClose }: Props) {
  const room = useVoiceStore((s) => s._room);
  const bgMode = useVoiceStore((s) => s.bgMode);
  const [audioInputs, setAudioInputs] = useState<MediaDeviceInfo[]>([]);
  const [audioOutputs, setAudioOutputs] = useState<MediaDeviceInfo[]>([]);
  const [videoInputs, setVideoInputs] = useState<MediaDeviceInfo[]>([]);

  const [activeAudioInput, setActiveAudioInput] = useState<string>('');
  const [activeAudioOutput, setActiveAudioOutput] = useState<string>('');
  const [activeVideoInput, setActiveVideoInput] = useState<string>('');

  useEffect(() => {
    async function loadDevices() {
      if (!room) return;
      try {
        // Request permissions first to ensure we get labels
        await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
      } catch (e) {
        // Ignore if denied or no devices
      }

      const devices = await navigator.mediaDevices.enumerateDevices();
      setAudioInputs(devices.filter((d) => d.kind === 'audioinput'));
      setAudioOutputs(devices.filter((d) => d.kind === 'audiooutput'));
      setVideoInputs(devices.filter((d) => d.kind === 'videoinput'));

      // If room exposes getActiveDevice(kind)
      if (typeof room.getActiveDevice === 'function') {
        const ai = room.getActiveDevice('audioinput');
        const ao = room.getActiveDevice('audiooutput');
        const vi = room.getActiveDevice('videoinput');
        if (ai) setActiveAudioInput(ai);
        if (ao) setActiveAudioOutput(ao);
        if (vi) setActiveVideoInput(vi);
      }
    }
    loadDevices();
  }, [room]);

  const handleDeviceChange = async (kind: MediaDeviceKind, deviceId: string) => {
    if (!room) return;
    try {
      await room.switchActiveDevice(kind, deviceId);
      saveDevicePref(kind, deviceId);
      if (kind === 'audioinput') setActiveAudioInput(deviceId);
      if (kind === 'audiooutput') setActiveAudioOutput(deviceId);
      if (kind === 'videoinput') setActiveVideoInput(deviceId);
    } catch (e) {
      console.error('Failed to switch device', e);
    }
  };

  return (
    <div className="fixed inset-0 bg-gb-bg/80 z-50 flex items-center justify-center p-4">
      <div className="bg-gb-bg border border-gb-bg-t rounded-sm shadow-xl p-4 w-full max-w-md">
        <h3 className="text-sm font-bold text-gb-fg-f mb-4">Device Settings</h3>
        
        <div className="space-y-4">
          <div>
            <label className="block text-xxs text-gb-fg-s mb-1">Microphone</label>
            <select 
              value={activeAudioInput}
              onChange={(e) => handleDeviceChange('audioinput', e.target.value)}
              className="w-full bg-gb-bg-s text-gb-fg border border-gb-bg-t rounded-sm px-2 py-1 text-sm outline-none focus:border-gb-orange"
            >
              <option value="">Default Microphone</option>
              {audioInputs.map(d => (
                <option key={d.deviceId} value={d.deviceId}>{d.label || `Microphone (${d.deviceId.slice(0, 5)}...)`}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xxs text-gb-fg-s mb-1">Speaker</label>
            <select 
              value={activeAudioOutput}
              onChange={(e) => handleDeviceChange('audiooutput', e.target.value)}
              className="w-full bg-gb-bg-s text-gb-fg border border-gb-bg-t rounded-sm px-2 py-1 text-sm outline-none focus:border-gb-orange"
            >
              <option value="">Default Speaker</option>
              {audioOutputs.map(d => (
                <option key={d.deviceId} value={d.deviceId}>{d.label || `Speaker (${d.deviceId.slice(0, 5)}...)`}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xxs text-gb-fg-s mb-1">Camera</label>
            <select 
              value={activeVideoInput}
              onChange={(e) => handleDeviceChange('videoinput', e.target.value)}
              className="w-full bg-gb-bg-s text-gb-fg border border-gb-bg-t rounded-sm px-2 py-1 text-sm outline-none focus:border-gb-orange"
            >
              <option value="">Default Camera</option>
              {videoInputs.map(d => (
                <option key={d.deviceId} value={d.deviceId}>{d.label || `Camera (${d.deviceId.slice(0, 5)}...)`}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xxs text-gb-fg-s mb-1">Background Effect</label>
            <select 
              value={bgMode}
              onChange={(e) => {
                const mode = e.target.value as 'disabled' | 'background-blur' | 'virtual-background';
                if (mode === 'virtual-background') {
                  const url = prompt('Enter image URL for virtual background:', 'https://images.unsplash.com/photo-1579546929518-9e396f3cc809');
                  if (url !== null) {
                    useVoiceStore.getState().setBgMode(mode, url);
                  }
                } else {
                  useVoiceStore.getState().setBgMode(mode);
                }
              }}
              className="w-full bg-gb-bg-s text-gb-fg border border-gb-bg-t rounded-sm px-2 py-1 text-sm outline-none focus:border-gb-orange"
            >
              <option value="disabled">None</option>
              <option value="background-blur">Blur Background</option>
              <option value="virtual-background">Virtual Background (Image URL)</option>
            </select>
          </div>
        </div>

        <div className="mt-6 flex justify-end">
          <button
            onClick={onClose}
            className="px-3 py-1 bg-gb-bg-s hover:bg-gb-bg-t text-gb-fg-f text-sm rounded-sm transition-colors border border-gb-bg-t"
          >
            [close]
          </button>
        </div>
      </div>
    </div>
  );
}
