import { useState, useEffect } from 'react'
import {
  fetchRegistrationSettings,
  updateRegistrationSettingsApi,
  fetchOAuthSettings,
  updateOAuthSettingsApi,
  type RegistrationSettings,
  type OAuthSettings,
} from '@common/services/authApi'

// ─── 시스템 설정 패널 ────────────────────────────────────────
function SettingsPanel() {
  const [settings, setSettings] = useState<RegistrationSettings | null>(null)
  const [oauthSettings, setOauthSettings] = useState<OAuthSettings | null>(null)
  const [oauthDomainInput, setOauthDomainInput] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [savingOAuth, setSavingOAuth] = useState(false)

  useEffect(() => {
    loadSettings()
  }, [])

  const loadSettings = async () => {
    setLoading(true)
    try {
      const [regData, oauthData] = await Promise.all([
        fetchRegistrationSettings(),
        fetchOAuthSettings(),
      ])
      setSettings(regData)
      setOauthSettings(oauthData)
      setOauthDomainInput(oauthData.autoApproveDomains)
    } catch (err) {
      console.error('설정 조회 실패:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleToggle = async (key: keyof RegistrationSettings) => {
    if (!settings) return
    const newValue = !settings[key]
    setSaving(true)
    try {
      const updated = await updateRegistrationSettingsApi({ [key]: newValue })
      setSettings(updated)
    } catch (err) {
      console.error('설정 변경 실패:', err)
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return <div className="flex items-center justify-center h-32 text-fg-disabled text-sm font-korean">불러오는 중...</div>
  }

  return (
    <div className="flex flex-col h-full">
      <div className="px-6 py-4 border-b border-stroke">
        <h1 className="text-lg font-bold text-fg font-korean">시스템 설정</h1>
        <p className="text-xs text-fg-disabled mt-1 font-korean">사용자 등록 및 권한 관련 시스템 설정을 관리합니다</p>
      </div>

      <div className="flex-1 overflow-auto px-6 py-6">
        <div className="max-w-[640px] flex flex-col gap-6">
          {/* 사용자 등록 설정 */}
          <div className="rounded-lg border border-stroke bg-bg-surface overflow-hidden">
            <div className="px-5 py-3 border-b border-stroke">
              <h2 className="text-sm font-bold text-fg font-korean">사용자 등록 설정</h2>
              <p className="text-[11px] text-fg-disabled mt-0.5 font-korean">신규 사용자 등록 시 적용되는 정책을 설정합니다</p>
            </div>

            <div className="divide-y divide-border">
              {/* 자동 승인 */}
              <div className="px-5 py-4 flex items-center justify-between">
                <div className="flex-1 mr-4">
                  <div className="text-[13px] font-semibold text-fg font-korean">자동 승인</div>
                  <p className="text-[11px] text-fg-disabled mt-1 font-korean leading-relaxed">
                    활성화하면 신규 사용자가 등록 즉시 <span className="text-green-400 font-semibold">ACTIVE</span> 상태가 됩니다.
                    비활성화하면 관리자 승인 전까지 <span className="text-yellow-400 font-semibold">PENDING</span> 상태로 대기합니다.
                  </p>
                </div>
                <button
                  onClick={() => handleToggle('autoApprove')}
                  disabled={saving}
                  className={`relative w-12 h-6 rounded-full transition-all flex-shrink-0 ${
                    settings?.autoApprove ? 'bg-color-accent' : 'bg-bg-card border border-stroke'
                  } ${saving ? 'opacity-50' : ''}`}
                >
                  <span
                    className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-all ${
                      settings?.autoApprove ? 'left-[26px]' : 'left-0.5'
                    }`}
                  />
                </button>
              </div>

              {/* 기본 역할 자동 할당 */}
              <div className="px-5 py-4 flex items-center justify-between">
                <div className="flex-1 mr-4">
                  <div className="text-[13px] font-semibold text-fg font-korean">기본 역할 자동 할당</div>
                  <p className="text-[11px] text-fg-disabled mt-1 font-korean leading-relaxed">
                    활성화하면 신규 사용자에게 <span className="text-color-accent font-semibold">기본 역할</span>이 자동으로 할당됩니다.
                    기본 역할은 권한 관리 탭에서 설정할 수 있습니다.
                  </p>
                </div>
                <button
                  onClick={() => handleToggle('defaultRole')}
                  disabled={saving}
                  className={`relative w-12 h-6 rounded-full transition-all flex-shrink-0 ${
                    settings?.defaultRole ? 'bg-color-accent' : 'bg-bg-card border border-stroke'
                  } ${saving ? 'opacity-50' : ''}`}
                >
                  <span
                    className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-all ${
                      settings?.defaultRole ? 'left-[26px]' : 'left-0.5'
                    }`}
                  />
                </button>
              </div>
            </div>
          </div>

          {/* OAuth 설정 */}
          <div className="rounded-lg border border-stroke bg-bg-surface overflow-hidden">
            <div className="px-5 py-3 border-b border-stroke">
              <h2 className="text-sm font-bold text-fg font-korean">Google OAuth 설정</h2>
              <p className="text-[11px] text-fg-disabled mt-0.5 font-korean">Google 계정 로그인 시 자동 승인할 이메일 도메인을 설정합니다</p>
            </div>
            <div className="px-5 py-4">
              <div className="flex-1 mr-4 mb-3">
                <div className="text-[13px] font-semibold text-fg font-korean mb-1">자동 승인 도메인</div>
                <p className="text-[11px] text-fg-disabled font-korean leading-relaxed mb-3">
                  지정된 도메인의 Google 계정은 가입 즉시 <span className="text-green-400 font-semibold">ACTIVE</span> 상태가 됩니다.
                  미지정 도메인은 <span className="text-yellow-400 font-semibold">PENDING</span> 상태로 관리자 승인이 필요합니다.
                  여러 도메인은 쉼표(,)로 구분합니다.
                </p>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={oauthDomainInput}
                    onChange={(e) => setOauthDomainInput(e.target.value)}
                    placeholder="gcsc.co.kr, example.com"
                    className="flex-1 px-3 py-2 text-xs bg-bg-elevated border border-stroke rounded-md text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none font-mono"
                  />
                  <button
                    onClick={async () => {
                      setSavingOAuth(true)
                      try {
                        const updated = await updateOAuthSettingsApi({ autoApproveDomains: oauthDomainInput.trim() })
                        setOauthSettings(updated)
                        setOauthDomainInput(updated.autoApproveDomains)
                      } catch (err) {
                        console.error('OAuth 설정 변경 실패:', err)
                      } finally {
                        setSavingOAuth(false)
                      }
                    }}
                    disabled={savingOAuth || oauthDomainInput.trim() === (oauthSettings?.autoApproveDomains || '')}
                    className={`px-4 py-2 text-xs font-semibold rounded-md transition-all font-korean whitespace-nowrap ${
                      oauthDomainInput.trim() !== (oauthSettings?.autoApproveDomains || '')
                        ? 'bg-color-accent text-bg-0 hover:shadow-[0_0_12px_rgba(6,182,212,0.3)]'
                        : 'bg-bg-card text-fg-disabled cursor-not-allowed'
                    }`}
                  >
                    {savingOAuth ? '저장 중...' : '저장'}
                  </button>
                </div>
              </div>
              {oauthSettings?.autoApproveDomains && (
                <div className="flex flex-wrap gap-1.5 mt-3">
                  {oauthSettings.autoApproveDomains.split(',').map(d => d.trim()).filter(Boolean).map(domain => (
                    <span
                      key={domain}
                      className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-mono rounded-md"
                      style={{ background: 'rgba(6,182,212,0.1)', color: 'var(--color-accent)', border: '1px solid rgba(6,182,212,0.25)' }}
                    >
                      @{domain}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* 현재 설정 상태 요약 */}
          <div className="rounded-lg border border-stroke bg-bg-surface overflow-hidden">
            <div className="px-5 py-3 border-b border-stroke">
              <h2 className="text-sm font-bold text-fg font-korean">설정 상태 요약</h2>
            </div>
            <div className="px-5 py-4">
              <div className="flex flex-col gap-3 text-[12px] font-korean">
                <div className="flex items-center gap-2">
                  <span className={`w-2 h-2 rounded-full ${settings?.autoApprove ? 'bg-green-400' : 'bg-yellow-400'}`} />
                  <span className="text-fg-sub">
                    신규 사용자 등록 시{' '}
                    {settings?.autoApprove ? (
                      <span className="text-green-400 font-semibold">즉시 활성화</span>
                    ) : (
                      <span className="text-yellow-400 font-semibold">관리자 승인 필요</span>
                    )}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`w-2 h-2 rounded-full ${settings?.defaultRole ? 'bg-green-400' : 'bg-fg-disabled'}`} />
                  <span className="text-fg-sub">
                    기본 역할 자동 할당{' '}
                    {settings?.defaultRole ? (
                      <span className="text-green-400 font-semibold">활성</span>
                    ) : (
                      <span className="text-fg-disabled font-semibold">비활성</span>
                    )}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`w-2 h-2 rounded-full ${oauthSettings?.autoApproveDomains ? 'bg-blue-400' : 'bg-fg-disabled'}`} />
                  <span className="text-fg-sub">
                    Google OAuth 자동 승인 도메인{' '}
                    {oauthSettings?.autoApproveDomains ? (
                      <span className="text-blue-400 font-semibold font-mono">{oauthSettings.autoApproveDomains}</span>
                    ) : (
                      <span className="text-fg-disabled font-semibold">미설정</span>
                    )}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default SettingsPanel
