import { useState, useEffect } from 'react'
import { useSettingsStore, type EditorOption } from '@/stores/useSettingsStore'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { Check, Loader2 } from 'lucide-react'
import { isMac } from '@/lib/platform'
import { useI18n } from '@/i18n/useI18n'

interface DetectedEditor {
  id: string
  name: string
  command: string
  available: boolean
}

interface EditorGroup {
  title: string
  options: Array<{ id: EditorOption; label: string }>
}

export function SettingsEditor(): React.JSX.Element {
  const { defaultEditor, customEditorCommand, updateSetting } = useSettingsStore()
  const [detectedEditors, setDetectedEditors] = useState<DetectedEditor[]>([])
  const [isDetecting, setIsDetecting] = useState(true)
  const { t } = useI18n()

  const editorGroups: EditorGroup[] = [
    {
      title: t('settings.editor.groups.ai'),
      options: [
        { id: 'cursor', label: 'Cursor' },
        { id: 'trae', label: 'Trae' },
        { id: 'windsurf', label: 'Windsurf' },
        { id: 'antigravity', label: 'Antigravity' }
      ]
    },
    {
      title: t('settings.editor.groups.jetbrains'),
      options: [
        { id: 'idea', label: 'IntelliJ IDEA' },
        { id: 'webstorm', label: 'WebStorm' },
        { id: 'pycharm', label: 'PyCharm' },
        { id: 'goland', label: 'GoLand' }
      ]
    },
    {
      title: t('settings.editor.groups.general'),
      options: [
        { id: 'vscode', label: 'Visual Studio Code' },
        { id: 'sublime', label: 'Sublime Text' },
        { id: 'zed', label: 'Zed' },
        { id: 'custom', label: t('settings.editor.customCommand.optionLabel') }
      ]
    }
  ]

  useEffect(() => {
    let cancelled = false
    async function detect(): Promise<void> {
      try {
        if (window.settingsOps?.detectEditors) {
          const editors = await window.settingsOps.detectEditors()
          if (!cancelled) {
            setDetectedEditors(editors)
          }
        }
      } catch {
        // Detection failed, show all options
      } finally {
        if (!cancelled) setIsDetecting(false)
      }
    }
    detect()
    return () => {
      cancelled = true
    }
  }, [])

  const isAvailable = (id: string): boolean => {
    if (id === 'custom') return true
    const editor = detectedEditors.find((e) => e.id === id)
    return editor?.available ?? false
  }

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-base font-medium mb-1">{t('settings.editor.title')}</h3>
        <p className="text-sm text-muted-foreground">{t('settings.editor.description')}</p>
      </div>

      {isDetecting ? (
        <div className="flex items-center gap-2 text-sm text-muted-foreground py-4">
          <Loader2 className="h-4 w-4 animate-spin" />
          {t('settings.editor.detecting')}
        </div>
      ) : (
        <div className="space-y-4">
          {editorGroups.map((group) => (
            <div key={group.title} className="space-y-1.5">
              <div className="px-1 text-[12px] font-semibold uppercase tracking-[0.12em] text-foreground/50">
                {group.title}
              </div>
              <div className="space-y-1">
                {group.options.map((opt) => {
                  const available = isAvailable(opt.id)
                  return (
                    <button
                      key={opt.id}
                      onClick={() => updateSetting('defaultEditor', opt.id)}
                      disabled={!available && opt.id !== 'custom'}
                      className={cn(
                        'w-full flex items-center justify-between px-3 py-2.5 rounded-md text-sm transition-colors text-left',
                        defaultEditor === opt.id
                          ? 'bg-primary/10 border border-primary/30'
                          : 'hover:bg-accent/50 border border-transparent',
                        !available && opt.id !== 'custom' && 'opacity-50 cursor-not-allowed'
                      )}
                      data-testid={`editor-${opt.id}`}
                    >
                      <div className="flex items-center gap-2">
                        <span>{opt.label}</span>
                        {!available && opt.id !== 'custom' && (
                          <span className="text-xs text-muted-foreground">
                            {t('settings.editor.notFound')}
                          </span>
                        )}
                      </div>
                      {defaultEditor === opt.id && <Check className="h-4 w-4 text-primary" />}
                    </button>
                  )
                })}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Custom command input */}
      {defaultEditor === 'custom' && (
        <div className="space-y-2">
          <label className="text-sm font-medium">{t('settings.editor.customCommand.label')}</label>
          <Input
            value={customEditorCommand}
            onChange={(e) => updateSetting('customEditorCommand', e.target.value)}
            placeholder={
              isMac()
                ? 'e.g., /usr/local/bin/code'
                : 'e.g., C:\\Program Files\\Microsoft VS Code\\code.exe'
            }
            className="font-mono text-sm"
            data-testid="custom-editor-command"
          />
          <p className="text-xs text-muted-foreground">
            {t('settings.editor.customCommand.description')}
          </p>
        </div>
      )}
    </div>
  )
}
