import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Table, Modal, Button, Field, TextInput, Select, Badge, TENANTS } from '../components/ui'
import { Icon } from '../lib/icons'
import { getBackups, createBackup, updateBackup, deleteBackup } from '../api/client'

// 백업/복구 — 매장코드별 일일 백업 이력 및 복구.
const TYPES = ['DAILY', 'MANUAL', 'FULL']
const STATUS = ['COMPLETED', 'RESTORED', 'FAILED', 'IN_PROGRESS']
const fmtSize = (n: number) => n == null ? '-' : n < 1048576 ? `${(n / 1024).toFixed(1)}KB` : `${(n / 1048576).toFixed(1)}MB`
const stTone = (s: string) => s === 'COMPLETED' ? 'green' : s === 'RESTORED' ? 'blue' : s === 'FAILED' ? 'red' : 'yellow'

export default function BackupList() {
  const qc = useQueryClient()
  const [modal, setModal] = useState<any | null>(null)
  const { data: backups = [], isLoading } = useQuery({ queryKey: ['backups'], queryFn: () => getBackups() })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateBackup(d.id, d) : createBackup(d),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['backups'] }); setModal(null) },
  })
  const restoreMut = useMutation({
    mutationFn: (r: any) => updateBackup(r.id, { ...r, status: 'RESTORED', restoredAt: new Date().toISOString() }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['backups'] }),
  })
  const delMut = useMutation({ mutationFn: deleteBackup, onSuccess: () => qc.invalidateQueries({ queryKey: ['backups'] }) })

  return (
    <div>
      <PageHeader title="백업 / 복구" subtitle="매장코드별 일일 백업 이력 관리 및 복구"
        actions={<Button icon="plus" onClick={() => setModal({ tenantCode: 'ZIOINFO', backupType: 'MANUAL', status: 'COMPLETED' })}>백업 등록</Button>} />

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <Table
          rowKey={(r: any) => r.id}
          rows={backups as any[]}
          columns={[
            { key: 'storeCode', header: '매장', render: r => <span className="font-mono text-xs text-white">{r.storeCode}</span> },
            { key: 'backupType', header: '유형', render: r => <Badge tone="blue">{r.backupType}</Badge> },
            { 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: 'backupAt', header: '백업시각', render: r => <span className="text-xs text-gray-400">{(r.backupAt || '').replace('T', ' ').slice(0, 16)}</span> },
            { key: 'status', header: '상태', render: r => <Badge tone={stTone(r.status)}>{r.status}</Badge> },
            { key: '__act', header: '', align: 'right', render: (r: any) => (
              <div className="flex gap-2 justify-end items-center">
                {r.status === 'COMPLETED' && (
                  <Button variant="ghost" icon="refresh" onClick={() => { if (confirm('이 백업으로 복구하시겠습니까?')) restoreMut.mutate(r) }}>복구</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="백업 등록" onClose={() => setModal(null)}>
          <BackupForm initial={modal} onSave={d => saveMut.mutate(d)} saving={saveMut.isPending} />
        </Modal>
      )}
    </div>
  )
}

function BackupForm({ initial, onSave, saving }: { initial: any; onSave: (d: any) => void; saving: boolean }) {
  const [f, setF] = useState<any>({
    id: initial.id, tenantCode: initial.tenantCode || 'ZIOINFO', storeCode: initial.storeCode || '',
    backupType: initial.backupType || 'MANUAL', fileName: initial.fileName || '', status: initial.status || 'COMPLETED',
  })
  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.storeCode} onChange={v => set('storeCode', v)} /></Field>
      <Field label="백업 유형">
        <Select className="w-full" value={f.backupType} onChange={v => set('backupType', v)}>{TYPES.map(t => <option key={t} value={t}>{t}</option>)}</Select>
      </Field>
      <Field label="파일명"><TextInput className="w-full" value={f.fileName} onChange={v => set('fileName', v)} placeholder="STORE001_20260704.bak" /></Field>
      <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>
  )
}
