import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Trash2 } from 'lucide-react'
import { getTemplates, createTemplate, deleteTemplate } from '../api/client'

export default function TemplateList() {
  const qc = useQueryClient()
  const { data: templates = [], isLoading } = useQuery({
    queryKey: ['templates'],
    queryFn:  () => getTemplates(),
  })

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

  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">ESL 템플릿</h1>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {(templates as any[]).map((t: any) => (
          <div key={t.id} className="bg-card border border-edge rounded-lg p-4">
            <div className="flex justify-between items-start mb-2">
              <div>
                <p className="text-sm font-medium text-white">{t.templateName}</p>
                <p className="text-xs text-brand mt-0.5">{t.tenantCode} · {t.templateType}</p>
              </div>
              <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(t.id) }}
                className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
            </div>
            <div className="bg-panel border border-edge rounded p-3 flex items-center justify-center"
              style={{ height: Math.min((t.height || 76) / 2 + 40, 120) }}>
              <div className="text-center">
                <p className="text-xs text-gray-400">{t.width}×{t.height}px</p>
                <p className="text-xs text-gray-500 mt-1">{t.description}</p>
              </div>
            </div>
            <p className="text-xs text-gray-500 mt-2">코드: {t.templateCode}</p>
          </div>
        ))}
        {(templates as any[]).length === 0 && (
          <div className="col-span-3 text-center text-gray-500 py-8">템플릿이 없습니다</div>
        )}
      </div>
    </div>
  )
}
