'use client'
import { useState } from 'react'
import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select'
import Button from '@/components/ui/Button'

interface BatchEditFormProps {
  onSubmit: (fields: Record<string, unknown>) => Promise<void>
  loading?: boolean
}

const UPDATABLE_FIELDS = [
  { key: 'device_type', label: '设备类型', type: 'select', options: ['服务器', '交换机', '路由器', '防火墙', '存储设备', 'GPU服务器', '其他'] },
  { key: 'device_purpose', label: '设备用途', type: 'text' },
  { key: 'room', label: '机房', type: 'text' },
  { key: 'rack_position', label: '机架位置', type: 'text' },
  { key: 'status', label: '状态', type: 'select', options: ['腾讯使用', '图灵使用', '闲置', '备用', '维修中', '已下线'] },
  { key: 'manufacturer', label: '厂商', type: 'text' },
  { key: 'device_model', label: '设备型号', type: 'text' },
  { key: 'warranty_date', label: '保修到期日', type: 'date' },
]

export default function BatchEditForm({ onSubmit, loading }: BatchEditFormProps) {
  const [enabled, setEnabled] = useState<Set<string>>(new Set())
  const [values, setValues] = useState<Record<string, string>>({})

  function toggleField(key: string) {
    setEnabled(prev => {
      const next = new Set(prev)
      if (next.has(key)) next.delete(key)
      else next.add(key)
      return next
    })
  }

  function setValue(key: string, value: string) {
    setValues(prev => ({ ...prev, [key]: value }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const fields: Record<string, unknown> = {}
    for (const key of enabled) {
      fields[key] = values[key] ?? ''
    }
    await onSubmit(fields)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <p className="text-sm text-slate-500 dark:text-slate-400">勾选需要修改的字段，填入新值后提交。</p>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {UPDATABLE_FIELDS.map(f => (
          <div key={f.key} className="flex items-start gap-3">
            <input type="checkbox" checked={enabled.has(f.key)} onChange={() => toggleField(f.key)} className="mt-2.5 rounded border-slate-300 dark:border-slate-600" />
            <div className="flex-1">
              {f.type === 'select' ? (
                <Select label={f.label} value={values[f.key] || ''} onChange={e => setValue(f.key, e.target.value)} options={f.options!.map(o => ({ value: o, label: o }))} />
              ) : (
                <Input label={f.label} type={f.type === 'date' ? 'date' : 'text'} value={values[f.key] || ''} onChange={e => setValue(f.key, e.target.value)} />
              )}
            </div>
          </div>
        ))}
      </div>
      <div className="flex justify-end">
        <Button type="submit" loading={loading} disabled={enabled.size === 0}>应用修改</Button>
      </div>
    </form>
  )
}
