import { useState, useEffect } from 'react'
import { api } from '../../api/client'
import { Button } from '../ui/Button'

interface StepConfig {
  step: string
  label: string
  category: string
  provider: string
  model: string
  is_default: boolean
}

interface ModelInfo {
  id: string
  label: string
  tier: string
  context: string
}

interface LLMConfigData {
  steps: StepConfig[]
  available_models: {
    openai: ModelInfo[]
    gemini: ModelInfo[]
  }
}

interface Props {
  projectId: string
}

export function LLMConfigPanel({ projectId }: Props) {
  const [data, setData] = useState<LLMConfigData | null>(null)
  const [configs, setConfigs] = useState<Record<string, { provider: string; model: string }>>({})
  const [saving, setSaving] = useState(false)
  const [dirty, setDirty] = useState(false)

  useEffect(() => {
    api<LLMConfigData>(`/api/v1/projects/${projectId}/llm-config`).then(d => {
      setData(d)
      const initial: Record<string, { provider: string; model: string }> = {}
      d.steps.forEach(s => { initial[s.step] = { provider: s.provider, model: s.model } })
      setConfigs(initial)
    }).catch(() => {})
  }, [projectId])

  if (!data) return null

  const handleChange = (step: string, provider: string, model: string) => {
    setConfigs(prev => ({ ...prev, [step]: { provider, model } }))
    setDirty(true)
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      await api(`/api/v1/projects/${projectId}/llm-config`, {
        method: 'PUT',
        body: JSON.stringify({ config: configs }),
      })
      setDirty(false)
    } catch (err: any) {
      alert(err?.message || 'LLM 설정 저장 실패')
    } finally {
      setSaving(false)
    }
  }

  const categories = [
    { key: 'analysis', label: '분석 단계' },
    { key: 'image', label: '이미지 생성 단계' },
  ]

  return (
    <div style={{
      padding: '16px', background: 'var(--bg-raised)',
      borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: '12px',
      }}>
        <span style={{ fontSize: '13px', fontWeight: 700, color: 'var(--text)' }}>
          LLM 모델 설정
        </span>
        {dirty && (
          <Button size="sm" onClick={handleSave} disabled={saving}>
            {saving ? '저장 중...' : '저장'}
          </Button>
        )}
      </div>

      {categories.map(cat => (
        <div key={cat.key} style={{ marginBottom: '16px' }}>
          <div style={{
            fontSize: '11px', fontWeight: 700, color: 'var(--text-dim)',
            textTransform: 'uppercase', letterSpacing: '0.04em',
            marginBottom: '8px', paddingBottom: '4px',
            borderBottom: '1px solid var(--border)',
          }}>
            {cat.label}
          </div>

          <table style={{ width: '100%', fontSize: '12px', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ color: 'var(--text-muted)', fontSize: '10px', textTransform: 'uppercase' }}>
                <th style={{ textAlign: 'left', padding: '4px 8px', width: '35%' }}>단계</th>
                <th style={{ textAlign: 'left', padding: '4px 8px', width: '25%' }}>Provider</th>
                <th style={{ textAlign: 'left', padding: '4px 8px', width: '40%' }}>모델</th>
              </tr>
            </thead>
            <tbody>
              {data.steps.filter(s => s.category === cat.key).map(step => {
                const cfg = configs[step.step] || { provider: step.provider, model: step.model }
                const models = data.available_models[cfg.provider as keyof typeof data.available_models] || []

                return (
                  <tr key={step.step} style={{ borderBottom: '1px solid var(--border)' }}>
                    <td style={{ padding: '6px 8px', color: 'var(--text)' }}>
                      {step.label}
                    </td>
                    <td style={{ padding: '6px 8px' }}>
                      <select
                        value={cfg.provider}
                        onChange={(e) => {
                          const newProvider = e.target.value
                          const newModels = data.available_models[newProvider as keyof typeof data.available_models] || []
                          handleChange(step.step, newProvider, newModels[0]?.id || '')
                        }}
                        style={{
                          fontSize: '11px', padding: '3px 6px',
                          background: 'var(--bg-input)', border: '1px solid var(--border)',
                          borderRadius: '4px', color: 'var(--text)',
                          width: '100%',
                        }}
                      >
                        <option value="gemini">Gemini</option>
                        <option value="openai">OpenAI</option>
                      </select>
                    </td>
                    <td style={{ padding: '6px 8px' }}>
                      <select
                        value={cfg.model}
                        onChange={(e) => handleChange(step.step, cfg.provider, e.target.value)}
                        style={{
                          fontSize: '11px', padding: '3px 6px',
                          background: 'var(--bg-input)', border: '1px solid var(--border)',
                          borderRadius: '4px', color: 'var(--text)',
                          width: '100%',
                        }}
                      >
                        {models.map(m => (
                          <option key={m.id} value={m.id}>
                            {m.label} ({m.tier}, {m.context})
                          </option>
                        ))}
                      </select>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  )
}
