import { useState } from 'react'
import { CrudPage } from '../components/Crud'
import { Badge, Select, TENANTS } from '../components/ui'
import { getSignDeploys, createSignDeploy, updateSignDeploy, deleteSignDeploy } from '../api/client'

// 간판정보 배포 — CSV/파일을 매장코드(또는 ALL)로 중앙배포. 단말은 30초 폴링으로 수신.
const TYPES = ['SIGN_INFO', 'TEMPLATE', 'TEMPLATE_GROUP', 'FIRMWARE', 'BACKUP']
const STATUS = ['PENDING', 'SENDING', 'DEPLOYED', 'CONFIRMED', 'FAILED']
const fmtSize = (n: number) => n == null ? '-' : n < 1024 ? `${n}B` : n < 1048576 ? `${(n / 1024).toFixed(1)}KB` : `${(n / 1048576).toFixed(1)}MB`
const stTone = (s: string) => s === 'DEPLOYED' || s === 'CONFIRMED' ? 'green' : s === 'FAILED' ? 'red' : s === 'SENDING' ? 'yellow' : 'gray'

export default function SignDeployList() {
  const [status, setStatus] = useState('')
  return (
    <CrudPage
      title="간판정보 배포"
      subtitle="간판정보(CSV)·템플릿·펌웨어를 매장코드(또는 ALL)로 중앙배포 · 단말 30초 폴링 수신"
      addLabel="배포 등록"
      queryKey={['sign-deploys', status]}
      fetcher={() => getSignDeploys(status ? { status } : {})}
      onCreate={createSignDeploy} onUpdate={updateSignDeploy} onDelete={deleteSignDeploy}
      defaults={{ tenantCode: 'ZIOINFO', storeCode: 'ALL', deployType: 'SIGN_INFO', status: 'PENDING', pollIntervalSec: 30 }}
      toolbarExtra={
        <>
          <span className="text-xs text-gray-400">상태</span>
          <Select value={status} onChange={setStatus}>
            <option value="">전체</option>{STATUS.map(s => <option key={s} value={s}>{s}</option>)}
          </Select>
        </>
      }
      columns={[
        { key: 'deployType', header: '유형', render: r => <Badge tone="blue">{r.deployType}</Badge> },
        { key: 'storeCode', header: '대상', render: r => <span className="font-mono text-xs text-white">{r.storeCode}</span> },
        { key: 'code', header: '코드', render: r => <span className="font-mono text-xs text-gray-400">{r.code || '-'}</span> },
        { key: 'fileName', header: '파일', render: r => <span className="text-xs text-gray-300">{r.fileName || '-'}</span> },
        { key: 'fileSize', header: '크기', render: r => <span className="text-xs text-gray-400">{fmtSize(r.fileSize)}</span> },
        { key: 'pollIntervalSec', header: '폴링', align: 'center', render: r => <span className="text-xs">{r.pollIntervalSec || 30}s</span> },
        { key: 'status', header: '상태', render: r => <Badge tone={stTone(r.status)}>{r.status}</Badge> },
      ]}
      form={[
        { key: 'tenantCode', label: '테넌트', type: 'select', opts: TENANTS },
        { key: 'storeCode', label: '대상 매장코드 (ALL=전체)', placeholder: 'ALL 또는 STORE001' },
        { key: 'deployType', label: '배포 유형', type: 'select', opts: TYPES },
        { key: 'subType', label: '서브타입', placeholder: '예: PRICE / eESB' },
        { key: 'code', label: '코드', placeholder: '템플릿/그룹 코드' },
        { key: 'fileName', label: '파일명', placeholder: 'signinfo_20260704.csv' },
        { key: 'filePath', label: '파일 경로' },
        { key: 'md5', label: 'MD5 체크섬' },
        { key: 'pollIntervalSec', label: '폴링 주기(초)', type: 'number' },
        { key: 'status', label: '상태', type: 'select', opts: STATUS },
      ]}
    />
  )
}
