import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, X } from 'lucide-react'
import { getStores, createStore, updateStore, deleteStore } from '../api/client'

export default function StoreList() {
  const qc = useQueryClient()
  const [modal, setModal] = useState<any>(null)
  const [keyword, setKeyword] = useState('')

  const { data: stores = [], isLoading } = useQuery({
    queryKey: ['stores', keyword],
    queryFn:  () => getStores({ keyword: keyword || undefined }),
  })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateStore(d.id, d) : createStore(d),
    onSuccess:  () => { qc.invalidateQueries({ queryKey: ['stores'] }); setModal(null) },
  })

  const deleteMut = useMutation({
    mutationFn: deleteStore,
    onSuccess:  () => qc.invalidateQueries({ queryKey: ['stores'] }),
  })

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-white">매장 관리</h1>
        <div className="flex gap-2">
          <input value={keyword} onChange={e => setKeyword(e.target.value)}
            placeholder="매장명·코드 검색"
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300 w-48" />
          <button onClick={() => setModal({})}
            className="flex items-center gap-1.5 bg-brand hover:bg-brand2 text-white px-3 py-1.5 rounded text-sm">
            <Plus size={14} /> 매장 추가
          </button>
        </div>
      </div>

      <div className="bg-card border border-edge rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-panel border-b border-edge">
            <tr>
              {['테넌트','코드','매장명','주소','담당자','상태','액션'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(stores as any[]).map((s: any) => (
              <tr key={s.id} className="border-b border-edge hover:bg-edge/30">
                <td className="px-4 py-3 text-brand text-xs">{s.tenantCode}</td>
                <td className="px-4 py-3 text-gray-300 font-mono text-xs">{s.storeCode}</td>
                <td className="px-4 py-3 text-white">{s.storeName}</td>
                <td className="px-4 py-3 text-gray-400 text-xs truncate max-w-xs">{s.address}</td>
                <td className="px-4 py-3 text-gray-400">{s.managerName}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${s.active ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'}`}>
                    {s.active ? '운영' : '중지'}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    <button onClick={() => setModal(s)} className="text-brand hover:text-blue-300"><Edit size={14} /></button>
                    <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(s.id) }} className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
            {(stores as any[]).length === 0 && (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-500">매장이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {modal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-card border border-edge rounded-lg p-6 w-full max-w-md">
            <div className="flex justify-between mb-4">
              <h2 className="font-semibold">{modal.id ? '매장 수정' : '매장 추가'}</h2>
              <button onClick={() => setModal(null)}><X size={16} /></button>
            </div>
            <StoreForm initial={modal} onSave={(d: any) => saveMut.mutate(d)} />
          </div>
        </div>
      )}
    </div>
  )
}

function StoreForm({ initial, onSave }: { initial: any; onSave: (d: any) => void }) {
  const [f, setF] = useState({
    tenantCode: initial.tenantCode || '',
    storeCode:  initial.storeCode  || '',
    storeName:  initial.storeName  || '',
    address:    initial.address    || '',
    phone:      initial.phone      || '',
    managerName: initial.managerName || '',
    active:     initial.active !== false,
    id:         initial.id,
  })
  const set = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
    setF(p => ({ ...p, [k]: e.target.value }))

  return (
    <form onSubmit={e => { e.preventDefault(); onSave(f) }} className="space-y-3">
      {[
        { label: '테넌트', key: 'tenantCode', type: 'select',
          opts: ['TENANT_A','TENANT_B','EMART','ZIOINFO'] },
        { label: '매장코드', key: 'storeCode' },
        { label: '매장명',   key: 'storeName' },
        { label: '주소',     key: 'address' },
        { label: '전화',     key: 'phone' },
        { label: '담당자',   key: 'managerName' },
      ].map(({ label, key, type, opts }) => (
        <div key={key}>
          <label className="block text-xs text-gray-400 mb-1">{label}</label>
          {type === 'select' ? (
            <select value={(f as any)[key]} onChange={set(key)}
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white">
              {(opts || []).map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          ) : (
            <input value={(f as any)[key]} onChange={set(key)}
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white" />
          )}
        </div>
      ))}
      <button type="submit" className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm">
        저장
      </button>
    </form>
  )
}
