import { useEffect, useState } from 'react'
import {
  provisionChannels,
  updateContact,
  type Contact,
  type Org,
  type ProvisionResult,
} from '../api/client'
import ConfirmDialog from './ConfirmDialog'
import StatusBadge from './StatusBadge'

const FIELDS: { key: keyof Contact; label: string }[] = [
  { key: 'deptName', label: '부서명' },
  { key: 'managerName', label: '담당자명' },
  { key: 'managerTitle', label: '직급/직함' },
  { key: 'managerPhone', label: '연락처' },
  { key: 'managerEmail', label: '이메일' },
]

function emptyContact(org: Org): Contact {
  return {
    deptName: org.deptName ?? '',
    managerName: org.managerName ?? '',
    managerTitle: org.managerTitle ?? '',
    managerPhone: org.managerPhone ?? '',
    managerEmail: org.managerEmail ?? '',
  }
}

export default function OrgDetail({ org, onChanged }: { org: Org; onChanged: () => void }) {
  const [contact, setContact] = useState<Contact>(emptyContact(org))
  const [confirming, setConfirming] = useState(false)
  const [result, setResult] = useState<ProvisionResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    setContact(emptyContact(org))
    setResult(null)
    setError(null)
  }, [org])

  const displayMj = `${org.orgNo}_${org.orgName} (문정원)`
  const displayLaw = `${org.orgNo}_${org.orgName} (법률검토)`
  const canProvision = org.status !== 'INFO_PENDING'

  async function save() {
    setError(null)
    try {
      await updateContact(org.id, contact)
      onChanged()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  async function provision() {
    setConfirming(false)
    setError(null)
    try {
      setResult(await provisionChannels(org.id))
      onChanged()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  return (
    <div className="p-8">
      <div className="flex items-center gap-3">
        <h1 className="text-lg font-semibold">
          {org.orgNo} {org.orgName}
        </h1>
        <StatusBadge status={org.status} />
      </div>

      <section className="mt-6 max-w-xl rounded-lg border border-gray-200 p-5">
        <h2 className="text-sm font-medium">신청기관 담당자</h2>

        <div className="mt-4 space-y-3">
          {FIELDS.map((field) => (
            <div key={field.key} className="flex items-center gap-3">
              <label htmlFor={field.key} className="w-20 shrink-0 text-sm text-gray-500">
                {field.label}
              </label>
              <input
                id={field.key}
                className="flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm"
                value={contact[field.key]}
                onChange={(e) => setContact({ ...contact, [field.key]: e.target.value })}
              />
            </div>
          ))}
        </div>

        <div className="mt-5 flex gap-2">
          <button
            type="button"
            onClick={() => void save()}
            className="rounded-md border border-gray-300 px-3 py-1.5 text-sm"
          >
            정보 저장
          </button>
          <button
            type="button"
            disabled={!canProvision}
            onClick={() => setConfirming(true)}
            className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white disabled:bg-gray-300"
          >
            채널 생성
          </button>
        </div>
      </section>

      {error && <p className="mt-4 text-sm text-red-600">{error}</p>}

      {result && (
        <div className="mt-4 max-w-xl rounded-lg border border-gray-200 p-4 text-sm">
          <p>문정원 채널: {outcomeLabel(result.mj)}</p>
          <p>법률검토 채널: {outcomeLabel(result.law)}</p>

          {result.law === 'FAILED' && (
            <p className="mt-2 text-amber-700">
              법률검토 채널 생성에 실패했습니다. 문정원 채널은 그대로 남아 있으니
              [채널 생성]을 다시 눌러도 안전합니다. 없는 채널만 다시 만듭니다.
            </p>
          )}
          {result.mj === 'FAILED' && (
            <p className="mt-2 text-amber-700">
              문정원 채널 생성에 실패했습니다. [채널 생성]을 다시 눌러도 안전합니다.
            </p>
          )}
          {result.message && (
            <pre className="mt-2 whitespace-pre-wrap text-xs text-gray-500">{result.message}</pre>
          )}
        </div>
      )}

      {confirming && (
        <ConfirmDialog
          title="아래 채널 2개를 Mattermost에 생성합니다."
          lines={[displayMj, displayLaw]}
          confirmLabel="생성"
          onConfirm={() => void provision()}
          onCancel={() => setConfirming(false)}
        />
      )}
    </div>
  )
}

function outcomeLabel(outcome: ProvisionResult['mj']): string {
  switch (outcome) {
    case 'CACHED':
      return '이미 있음 (변경 없음)'
    case 'RECOVERED':
      return '기존 채널 연결됨'
    case 'CREATED':
      return '새로 생성됨'
    case 'FAILED':
      return '실패'
  }
}
