import { useEffect, useState } from 'react'
import { Share2, Plus, Trash2, Edit3, Globe, Smartphone, AppWindow, Tv } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getChannels, createChannel, updateChannel, deleteChannel } from '../api/client'

const CHANNEL_TYPES = ['WEB', 'MOBILE', 'APP', 'KIOSK']
const ICONS: Record<string, any> = { WEB: Globe, MOBILE: Smartphone, APP: AppWindow, KIOSK: Tv }
const emptyForm = { name: '', channelType: 'WEB', endpoint: '', active: true }

export default function Channels() {
  const [list, setList] = useState<any[]>([])
  const [form, setForm] = useState<any>(null)
  const writable = canWrite()

  const load = () => getChannels().then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [])

  const save = async () => { if (form.id) await updateChannel(form.id, form); else await createChannel(form); setForm(null); load() }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteChannel(id); load() }

  return (
    <div>
      <PageHeader title="채널" subtitle="다채널 배포 타겟 — 웹 · 모바일 · 앱 · 키오스크"
        actions={writable && <Btn onClick={() => setForm({ ...emptyForm })}><Plus size={16} /> 채널 추가</Btn>} />

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {list.map(c => {
          const Icon = ICONS[c.channelType] || Share2
          return (
            <div key={c.id} className="bg-card border border-edge rounded-xl p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="font-medium flex items-center gap-2"><Icon size={16} className="text-brand" /> {c.name}</span>
                <StatusBadge status={c.active ? 'ACTIVE' : 'INACTIVE'} />
              </div>
              <div className="text-xs text-slate-400">{c.channelType}</div>
              <div className="text-[11px] text-slate-500 font-mono truncate mt-1">{c.endpoint}</div>
              {writable && (
                <div className="flex items-center gap-3 mt-3">
                  <button onClick={() => setForm({ ...c })} className="text-slate-400 hover:text-brand"><Edit3 size={14} /></button>
                  <button onClick={() => remove(c.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                </div>
              )}
            </div>
          )
        })}
        {list.length === 0 && <div className="col-span-3"><Empty msg="채널이 없습니다." /></div>}
      </div>

      {form && (
        <Modal title={form.id ? '채널 편집' : '채널 추가'} onClose={() => setForm(null)}>
          <div className="space-y-3">
            <Field label="이름"><input className="inp" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            <Field label="유형">
              <select className="inp" value={form.channelType} onChange={e => setForm({ ...form, channelType: e.target.value })}>
                {CHANNEL_TYPES.map(t => <option key={t}>{t}</option>)}
              </select>
            </Field>
            <Field label="엔드포인트"><input className="inp" value={form.endpoint} onChange={e => setForm({ ...form, endpoint: e.target.value })} placeholder="https://..." /></Field>
            <Field label="활성">
              <select className="inp" value={String(form.active)} onChange={e => setForm({ ...form, active: e.target.value === 'true' })}>
                <option value="true">활성</option><option value="false">비활성</option>
              </select>
            </Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setForm(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
