import { useMemo, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Button, Field, TextInput, Select, Badge } from '../components/ui'
import { Icon } from '../lib/icons'
import {
  getSignImages, createSignImage, updateSignImage, deleteSignImage,
  getTemplates, aiGenerateSignText,
} from '../api/client'

// 간판 이미지 에디터 — Template/Font/Image Code 편집 + 실시간 미리보기.
//   좌: 이미지 목록  중: 편집 폼  우: 미리보기 캔버스.
//   폰트(글꼴/크기/색/정렬/배경)는 프리뷰 스타일. bizName/phone/message/templateCode/imageCode/width/height 는 저장.

const FONTS = [
  { value: "'Noto Sans KR', sans-serif", label: '노토 산스' },
  { value: "'Nanum Gothic', sans-serif", label: '나눔 고딕' },
  { value: "'Malgun Gothic', sans-serif", label: '맑은 고딕' },
  { value: 'serif', label: '명조(Serif)' },
  { value: 'monospace', label: '고정폭' },
]
const ALIGNS = ['left', 'center', 'right']
const blank = () => ({
  id: undefined as number | undefined,
  tenantCode: 'ZIOINFO', storeCode: '', imageCode: '', templateCode: '',
  bizName: '', phone: '', message: '', width: 400, height: 300, status: 'DRAFT',
})

export default function SignImageEditor() {
  const qc = useQueryClient()
  const [sel, setSel] = useState<any>(blank())
  // 폰트 스타일(프리뷰 전용)
  const [font, setFont] = useState(FONTS[0].value)
  const [titleSize, setTitleSize] = useState(28)
  const [bodySize, setBodySize] = useState(18)
  const [fg, setFg] = useState('#0b0f17')
  const [bg, setBg] = useState('#ffffff')
  const [align, setAlign] = useState<'left' | 'center' | 'right'>('center')

  const { data: images = [] } = useQuery({ queryKey: ['sign-images'], queryFn: () => getSignImages() })
  const { data: templates = [] } = useQuery({ queryKey: ['templates'], queryFn: () => getTemplates() })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateSignImage(d.id, d) : createSignImage(d),
    onSuccess: (saved: any) => { qc.invalidateQueries({ queryKey: ['sign-images'] }); if (saved) setSel(saved) },
  })
  const delMut = useMutation({
    mutationFn: deleteSignImage,
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['sign-images'] }); setSel(blank()) },
  })
  const aiMut = useMutation({
    mutationFn: () => aiGenerateSignText({ bizName: sel.bizName, message: sel.message, storeCode: sel.storeCode }),
    onSuccess: (r: any) => { if (r?.text) setSel((p: any) => ({ ...p, message: r.text })) },
  })

  const set = (k: string, v: any) => setSel((p: any) => ({ ...p, [k]: v }))

  // 미리보기 스케일(최대 420px 폭)
  const scale = useMemo(() => Math.min(1, 420 / (sel.width || 400)), [sel.width])

  return (
    <div>
      <PageHeader title="간판 이미지 에디터" subtitle="템플릿·글꼴·이미지 코드를 편집하고 실시간 미리보기로 확인합니다"
        actions={<Button icon="plus" variant="ghost" onClick={() => setSel(blank())}>새 이미지</Button>} />

      <div className="grid grid-cols-1 lg:grid-cols-[240px_1fr_460px] gap-4">
        {/* 목록 */}
        <div className="bg-card border border-edge rounded-lg p-2 max-h-[70vh] overflow-auto">
          <div className="text-xs text-gray-500 px-2 py-1.5">이미지 목록 ({(images as any[]).length})</div>
          {(images as any[]).map(im => (
            <button key={im.id} onClick={() => setSel(im)}
              className={`w-full text-left px-3 py-2 rounded text-sm mb-1 ${sel.id === im.id ? 'bg-brand/15 text-brand' : 'text-gray-300 hover:bg-edge/40'}`}>
              <div className="flex items-center gap-2">
                <Icon name="editor" size={13} />
                <span className="font-mono text-xs truncate">{im.imageCode || '(코드없음)'}</span>
              </div>
              <div className="text-[11px] text-gray-500 truncate">{im.bizName || im.storeCode}</div>
            </button>
          ))}
          {(images as any[]).length === 0 && <div className="text-xs text-gray-600 px-3 py-4">이미지가 없습니다</div>}
        </div>

        {/* 편집 폼 */}
        <div className="bg-card border border-edge rounded-lg p-4">
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-medium text-white">{sel.id ? '이미지 편집' : '새 이미지'}</h2>
            {sel.status && <Badge tone={sel.status === 'DEPLOYED' ? 'green' : sel.status === 'DRAFT' ? 'gray' : 'yellow'}>{sel.status}</Badge>}
          </div>

          <div className="grid grid-cols-2 gap-x-3">
            <Field label="테넌트">
              <Select className="w-full" value={sel.tenantCode} onChange={v => set('tenantCode', v)}>
                {['ZIOINFO', 'TENANT_A', 'TENANT_B', 'EMART'].map(t => <option key={t} value={t}>{t}</option>)}
              </Select>
            </Field>
            <Field label="매장코드"><TextInput className="w-full" value={sel.storeCode} onChange={v => set('storeCode', v)} placeholder="STORE001" /></Field>
            <Field label="이미지 코드"><TextInput className="w-full" value={sel.imageCode} onChange={v => set('imageCode', v)} placeholder="IMG-0001" /></Field>
            <Field label="템플릿 코드">
              <Select className="w-full" value={sel.templateCode} onChange={v => {
                set('templateCode', v)
                const t = (templates as any[]).find(x => x.templateCode === v)
                if (t) setSel((p: any) => ({ ...p, templateCode: v, width: t.width || p.width, height: t.height || p.height }))
              }}>
                <option value="">템플릿 선택</option>
                {(templates as any[]).map(t => <option key={t.id} value={t.templateCode}>{t.templateName} ({t.width}×{t.height})</option>)}
              </Select>
            </Field>
            <Field label="폭(px)"><TextInput className="w-full" type="number" value={String(sel.width)} onChange={v => set('width', Number(v) || 0)} /></Field>
            <Field label="높이(px)"><TextInput className="w-full" type="number" value={String(sel.height)} onChange={v => set('height', Number(v) || 0)} /></Field>
          </div>

          <Field label="상호명(제목)"><TextInput className="w-full" value={sel.bizName} onChange={v => set('bizName', v)} /></Field>
          <Field label="전화번호"><TextInput className="w-full" value={sel.phone} onChange={v => set('phone', v)} /></Field>
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-gray-400">문구(본문)</span>
              <button onClick={() => aiMut.mutate()} disabled={aiMut.isPending}
                className="text-xs text-brand hover:text-blue-300 inline-flex items-center gap-1 disabled:opacity-50">
                <Icon name="ai" size={12} /> {aiMut.isPending ? '생성 중...' : 'AI 문구 생성'}
              </button>
            </div>
            <textarea value={sel.message} onChange={e => set('message', e.target.value)} rows={3}
              className="w-full bg-ink border border-edge rounded px-3 py-2 text-sm text-white outline-none focus:border-brand" />
          </div>

          {/* 글꼴(폰트) 스타일 — 미리보기 전용 */}
          <div className="mt-4 border-t border-edge pt-3">
            <div className="text-xs text-gray-500 mb-2">글꼴 · 스타일 (미리보기)</div>
            <div className="grid grid-cols-2 gap-x-3">
              <Field label="글꼴">
                <Select className="w-full" value={font} onChange={setFont}>
                  {FONTS.map(f => <option key={f.value} value={f.value}>{f.label}</option>)}
                </Select>
              </Field>
              <Field label="정렬">
                <Select className="w-full" value={align} onChange={v => setAlign(v as any)}>
                  {ALIGNS.map(a => <option key={a} value={a}>{a}</option>)}
                </Select>
              </Field>
              <Field label={`제목 크기 (${titleSize}px)`}>
                <input type="range" min={14} max={60} value={titleSize} onChange={e => setTitleSize(Number(e.target.value))} className="w-full accent-brand" />
              </Field>
              <Field label={`본문 크기 (${bodySize}px)`}>
                <input type="range" min={10} max={40} value={bodySize} onChange={e => setBodySize(Number(e.target.value))} className="w-full accent-brand" />
              </Field>
              <Field label="글자색">
                <input type="color" value={fg} onChange={e => setFg(e.target.value)} className="w-full h-9 bg-ink border border-edge rounded" />
              </Field>
              <Field label="배경색">
                <input type="color" value={bg} onChange={e => setBg(e.target.value)} className="w-full h-9 bg-ink border border-edge rounded" />
              </Field>
            </div>
          </div>

          <div className="flex gap-2 mt-4">
            <Button icon="save" onClick={() => saveMut.mutate(sel)} disabled={saveMut.isPending}>
              {saveMut.isPending ? '저장 중...' : '저장'}
            </Button>
            {sel.id && <Button variant="danger" icon="trash" onClick={() => { if (confirm('삭제?')) delMut.mutate(sel.id) }}>삭제</Button>}
          </div>
        </div>

        {/* 미리보기 */}
        <div className="bg-card border border-edge rounded-lg p-4">
          <div className="flex items-center gap-2 mb-3">
            <Icon name="preview" size={15} className="text-brand" />
            <h2 className="text-sm font-medium text-white">실시간 미리보기</h2>
            <span className="text-xs text-gray-500 ml-auto">{sel.width}×{sel.height}px · {Math.round(scale * 100)}%</span>
          </div>
          <div className="flex justify-center bg-ink rounded-lg p-4 overflow-auto">
            <div style={{
              width: sel.width * scale, height: sel.height * scale,
              background: bg, color: fg, fontFamily: font,
              display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              padding: 16 * scale, boxShadow: '0 4px 20px rgba(0,0,0,0.4)', borderRadius: 4,
              textAlign: align, overflow: 'hidden',
            }}>
              <div style={{ fontSize: titleSize * scale, fontWeight: 800, lineHeight: 1.15 }}>{sel.bizName || '상호명'}</div>
              <div style={{ fontSize: bodySize * scale, whiteSpace: 'pre-wrap', lineHeight: 1.35, flex: 1, display: 'flex', alignItems: 'center', justifyContent: align === 'center' ? 'center' : align === 'right' ? 'flex-end' : 'flex-start' }}>
                {sel.message || '간판 문구를 입력하세요'}
              </div>
              <div style={{ fontSize: bodySize * 0.8 * scale, opacity: 0.85 }}>{sel.phone || '☎ 000-0000-0000'}</div>
            </div>
          </div>
          <p className="text-[11px] text-gray-500 mt-3">
            미리보기는 실제 패널 렌더링 근사치입니다. 저장 후 <span className="text-brand">템플릿 그룹·배포</span>에서 매장/전체로 일괄배포하세요.
          </p>
        </div>
      </div>
    </div>
  )
}
