import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Toolbar, Table, Modal, Button, Field, TextInput, Select, Badge, TENANTS } from '../components/ui'
import { Icon } from '../lib/icons'
import {
  getTemplateGroups, createTemplateGroup, updateTemplateGroup, deleteTemplateGroup,
  getStores, createSignDeploy,
} from '../api/client'

// 템플릿 그룹 관리 + 일괄배포(ALL/매장별) — sign-deploys 로 배포 작업 생성.
export default function TemplateGroupList() {
  const qc = useQueryClient()
  const [modal, setModal] = useState<any | null>(null)
  const [deployTarget, setDeployTarget] = useState<any | null>(null)

  const { data: groups = [], isLoading } = useQuery({ queryKey: ['template-groups'], queryFn: () => getTemplateGroups() })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateTemplateGroup(d.id, d) : createTemplateGroup(d),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['template-groups'] }); setModal(null) },
  })
  const delMut = useMutation({ mutationFn: deleteTemplateGroup, onSuccess: () => qc.invalidateQueries({ queryKey: ['template-groups'] }) })

  return (
    <div>
      <PageHeader title="템플릿 그룹 · 일괄배포" subtitle="템플릿 묶음을 전체(ALL) 또는 매장별로 일괄배포합니다"
        actions={<Button icon="plus" onClick={() => setModal({ tenantCode: 'ZIOINFO', active: true })}>그룹 추가</Button>} />

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <Table
          rowKey={(r: any) => r.id}
          rows={groups as any[]}
          columns={[
            { key: 'tenantCode', header: '테넌트', render: r => <span className="text-brand text-xs">{r.tenantCode}</span> },
            { key: 'groupCode', header: '그룹코드', render: r => <span className="font-mono text-xs text-white">{r.groupCode}</span> },
            { key: 'groupName', header: '그룹명' },
            { key: 'description', header: '설명' },
            { key: 'active', header: '상태', render: r => <Badge tone={r.active ? 'green' : 'gray'}>{r.active ? '사용' : '중지'}</Badge> },
            { key: '__act', header: '', align: 'right', render: (r: any) => (
              <div className="flex gap-2 justify-end items-center">
                <Button variant="ghost" icon="deploy" onClick={() => setDeployTarget(r)}>배포</Button>
                <button onClick={() => setModal(r)} className="text-brand hover:text-blue-300"><Icon name="edit" size={15} /></button>
                <button onClick={() => { if (confirm('삭제?')) delMut.mutate(r.id) }} className="text-red-400 hover:text-red-300"><Icon name="trash" size={15} /></button>
              </div>
            ) },
          ]}
        />
      )}

      {modal && (
        <Modal title={modal.id ? '그룹 수정' : '그룹 추가'} onClose={() => setModal(null)}>
          <GroupForm initial={modal} onSave={d => saveMut.mutate(d)} saving={saveMut.isPending} />
        </Modal>
      )}

      {deployTarget && (
        <DeployModal group={deployTarget} onClose={() => setDeployTarget(null)} />
      )}
    </div>
  )
}

function GroupForm({ initial, onSave, saving }: { initial: any; onSave: (d: any) => void; saving: boolean }) {
  const [f, setF] = useState<any>({
    id: initial.id, tenantCode: initial.tenantCode || 'ZIOINFO',
    groupCode: initial.groupCode || '', groupName: initial.groupName || '',
    description: initial.description || '', active: initial.active !== false,
  })
  const set = (k: string, v: any) => setF((p: any) => ({ ...p, [k]: v }))
  return (
    <form onSubmit={e => { e.preventDefault(); onSave(f) }}>
      <Field label="테넌트">
        <Select className="w-full" value={f.tenantCode} onChange={v => set('tenantCode', v)}>
          {TENANTS.map(t => <option key={t} value={t}>{t}</option>)}
        </Select>
      </Field>
      <Field label="그룹코드"><TextInput className="w-full" value={f.groupCode} onChange={v => set('groupCode', v)} /></Field>
      <Field label="그룹명"><TextInput className="w-full" value={f.groupName} onChange={v => set('groupName', v)} /></Field>
      <Field label="설명"><TextInput className="w-full" value={f.description} onChange={v => set('description', v)} /></Field>
      <label className="flex items-center gap-2 text-sm text-gray-300 mb-3">
        <input type="checkbox" checked={f.active} onChange={e => set('active', e.target.checked)} /> 사용
      </label>
      <button type="submit" disabled={saving} className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm font-medium disabled:opacity-50">
        {saving ? '저장 중...' : '저장'}
      </button>
    </form>
  )
}

function DeployModal({ group, onClose }: { group: any; onClose: () => void }) {
  const [scope, setScope] = useState<'ALL' | 'STORE'>('ALL')
  const [storeCode, setStoreCode] = useState('')
  const { data: stores = [] } = useQuery({ queryKey: ['stores'], queryFn: () => getStores() })
  const deployMut = useMutation({
    mutationFn: () => createSignDeploy({
      tenantCode: group.tenantCode,
      storeCode: scope === 'ALL' ? 'ALL' : storeCode,
      deployType: 'TEMPLATE_GROUP',
      code: group.groupCode,
      status: 'PENDING',
      pollIntervalSec: 30,
    }),
    onSuccess: onClose,
  })

  return (
    <Modal title={`일괄배포 — ${group.groupName}`} onClose={onClose}>
      <p className="text-sm text-gray-400 mb-4">템플릿 그룹 <span className="text-brand font-mono">{group.groupCode}</span> 을(를) 배포합니다. 대상 매장은 30초 폴링으로 수신합니다.</p>
      <Field label="배포 범위">
        <div className="flex gap-2">
          <button type="button" onClick={() => setScope('ALL')}
            className={`flex-1 px-3 py-2 rounded text-sm border ${scope === 'ALL' ? 'bg-brand/15 border-brand text-brand' : 'bg-ink border-edge text-gray-300'}`}>전체 매장 (ALL)</button>
          <button type="button" onClick={() => setScope('STORE')}
            className={`flex-1 px-3 py-2 rounded text-sm border ${scope === 'STORE' ? 'bg-brand/15 border-brand text-brand' : 'bg-ink border-edge text-gray-300'}`}>특정 매장</button>
        </div>
      </Field>
      {scope === 'STORE' && (
        <Field label="매장 선택">
          <Select className="w-full" value={storeCode} onChange={setStoreCode}>
            <option value="">매장 선택</option>
            {(stores as any[]).map(s => <option key={s.id} value={s.storeCode}>{s.storeName} ({s.storeCode})</option>)}
          </Select>
        </Field>
      )}
      <Button icon="deploy" onClick={() => deployMut.mutate()} disabled={deployMut.isPending || (scope === 'STORE' && !storeCode)}>
        {deployMut.isPending ? '배포 요청 중...' : '배포 실행'}
      </Button>
    </Modal>
  )
}
