import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../../../api/client'

function Toggle({ checked, onChange, disabled }) {
  return (
    <button
      role="switch"
      aria-checked={checked}
      onClick={() => !disabled && onChange(!checked)}
      disabled={disabled}
      className={`relative w-11 h-6 rounded-full transition-colors duration-200 flex-shrink-0 disabled:opacity-50 ${
        checked ? 'bg-sky-500' : 'bg-slate-200'
      }`}
    >
      <span className={`absolute top-1 w-4 h-4 rounded-full bg-white shadow transition-all duration-200 ${
        checked ? 'left-6' : 'left-1'
      }`} />
    </button>
  )
}

function SectionCard({ title, description, children, action }) {
  return (
    <div className="card divide-y divide-gray-100">
      <div className="flex items-center justify-between px-5 py-4">
        <div>
          <h2 className="font-semibold text-gray-700">{title}</h2>
          {description && <p className="text-xs text-gray-400 mt-0.5">{description}</p>}
        </div>
        {action}
      </div>
      {children}
    </div>
  )
}

function OptionRow({ label, description, children }) {
  return (
    <div className="flex items-center justify-between gap-4 px-5 py-4">
      <div className="min-w-0">
        <p className="text-sm font-medium text-gray-800">{label}</p>
        {description && <p className="text-xs text-gray-500 mt-0.5">{description}</p>}
      </div>
      <div className="flex-shrink-0">{children}</div>
    </div>
  )
}

function ShiftSettingsSection() {
  const qc = useQueryClient()
  const { data: settings, isLoading } = useQuery({
    queryKey: ['pos-settings'],
    queryFn: () => client.get('/api/settings/').then(r => r.data),
    staleTime: 30_000,
  })
  const updateMut = useMutation({
    mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }),
    onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })
  function toggle(key, current) {
    updateMut.mutate({ key, value: current === 'true' ? 'false' : 'true' })
  }
  const selfStart = settings?.['shifts.waiter_self_start']?.value ?? 'true'
  const selfEnd   = settings?.['shifts.waiter_self_end']?.value   ?? 'true'
  return (
    <SectionCard title="Ρυθμίσεις Βάρδιας" description="Έλεγχος του τι επιτρέπεται να κάνουν οι σερβιτόροι μόνοι τους">
      {isLoading && <p className="px-5 py-4 text-sm text-gray-400">Φόρτωση…</p>}
      {!isLoading && (
        <>
          <OptionRow label="Αυτόματη Έναρξη Βάρδιας" description="Οι σερβιτόροι μπορούν να ξεκινούν μόνοι τους τη βάρδια τους">
            <Toggle checked={selfStart === 'true'} onChange={() => toggle('shifts.waiter_self_start', selfStart)} disabled={updateMut.isPending} />
          </OptionRow>
          <OptionRow label="Αυτόματο Κλείσιμο Βάρδιας" description="Οι σερβιτόροι μπορούν να κλείνουν μόνοι τους τη βάρδια τους">
            <Toggle checked={selfEnd === 'true'} onChange={() => toggle('shifts.waiter_self_end', selfEnd)} disabled={updateMut.isPending} />
          </OptionRow>
        </>
      )}
    </SectionCard>
  )
}

// ─── Flag definitions ─────────────────────────────────────────────────────────

const FLAG_COLORS = [
  '#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6',
  '#8b5cf6', '#ec4899', '#06b6d4', '#6b7280', '#dc2626',
]
const RESTAURANT_EMOJIS = [
  '🧹', '⭐', '📝', '🛎️', '💎',
  '🤵🏻', '🔒', '🛒', '🗣️', '⛔',
  '🥳', '🎂', '🎉', '🍰', '🤩',
  '☕', '🥂', '🍾', '🍹', '💦',
  '🍖', '🥩', '🍽️', '🥓', '🍳',
  '♿', '👶', '🤬', '🐶', '🐱',
  '🚧', '🔥', '❄️', '⏳', '⚠️',
]

function EmojiPicker({ value, onChange }) {
  const [open, setOpen] = useState(false)
  return (
    <div style={{ position: 'relative' }}>
      <button type="button" onClick={() => setOpen(o => !o)} style={{
        width: 60, height: 36, borderRadius: 8, border: '1px solid #dfe2e6',
        background: 'white', fontSize: 20, textAlign: 'center', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{value || '＋'}</button>
      {open && (
        <div style={{
          position: 'absolute', top: '110%', left: 0, zIndex: 200,
          background: 'white', border: '1px solid #e2e8f0', borderRadius: 12,
          boxShadow: '0 8px 24px rgba(0,0,0,0.12)', padding: 8,
          display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 2, width: 180,
        }}>
          {RESTAURANT_EMOJIS.map(e => (
            <button key={e} type="button" onClick={() => { onChange(e); setOpen(false) }} style={{
              fontSize: 20, background: value === e ? '#eff3ff' : 'none',
              border: 'none', borderRadius: 6, padding: '4px 0', cursor: 'pointer',
            }}>{e}</button>
          ))}
          <button type="button" onClick={() => { onChange(''); setOpen(false) }} style={{
            fontSize: 11, color: '#9ca3af', background: 'none', border: 'none', cursor: 'pointer', padding: '4px 0', borderRadius: 6,
          }}>✕ clear</button>
        </div>
      )}
    </div>
  )
}

function FlagDefsSection() {
  const qc = useQueryClient()
  const [editingId, setEditingId] = useState(null)
  const [editForm, setEditForm] = useState({})
  const [newForm, setNewForm] = useState({ name: '', emoji: '', color: '#6b7280', text_color: null })
  const [showNew, setShowNew] = useState(false)
  const { data: flags = [], isLoading } = useQuery({
    queryKey: ['flag-defs'],
    queryFn: () => client.get('/api/flags/defs?include_inactive=true').then(r => r.data),
    staleTime: 30_000,
  })
  const createMut = useMutation({
    mutationFn: (body) => client.post('/api/flags/defs', body),
    onSuccess: () => { toast.success('Δημιουργήθηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }); setShowNew(false); setNewForm({ name: '', emoji: '', color: '#6b7280', text_color: null }) },
    onError: () => toast.error('Σφάλμα'),
  })
  const updateMut = useMutation({
    mutationFn: ({ id, ...body }) => client.put(`/api/flags/defs/${id}`, body),
    onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }); setEditingId(null) },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })
  const toggleMut = useMutation({
    mutationFn: (id) => client.patch(`/api/flags/defs/${id}/toggle-active`),
    onSuccess: (res) => { toast.success(res.data.is_active ? 'Ενεργοποιήθηκε' : 'Απενεργοποιήθηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }) },
    onError: () => toast.error('Σφάλμα'),
  })
  const deleteMut = useMutation({
    mutationFn: (id) => client.delete(`/api/flags/defs/${id}`),
    onSuccess: () => { toast.success('Διαγράφηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }) },
    onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
  })
  function startEdit(flag) {
    setEditingId(flag.id)
    setEditForm({ name: flag.name, emoji: flag.emoji || '', color: flag.color || '#6b7280', text_color: flag.text_color || null, sort_order: flag.sort_order })
  }
  const rowStyle = { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' }
  const newRowButton = (
    <button onClick={() => setShowNew(v => !v)} style={{
      height: 32, padding: '0 14px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#374151',
    }}>+ Νέα</button>
  )
  return (
    <SectionCard title="Σημάνσεις Τραπεζιών" description="Χρησιμοποιούνται για να επισημαίνετε καταστάσεις στα τραπέζια" action={newRowButton}>
      {showNew && (
        <div style={{ padding: '14px 20px', background: '#f9fafb', display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'flex-end', borderTop: '1px solid #f4f4f2' }}>
          <EmojiPicker value={newForm.emoji} onChange={v => setNewForm(f => ({ ...f, emoji: v }))} />
          <input placeholder="Όνομα σημαίας" value={newForm.name} onChange={e => setNewForm(f => ({ ...f, name: e.target.value }))}
            style={{ flex: 1, minWidth: 160, height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit' }} />
          <div style={{ display: 'flex', gap: 4 }}>
            {FLAG_COLORS.map(c => (
              <button key={c} onClick={() => setNewForm(f => ({ ...f, color: c }))}
                style={{ width: 24, height: 24, borderRadius: '50%', background: c, border: newForm.color === c ? '3px solid #111' : '2px solid transparent', cursor: 'pointer' }} />
            ))}
          </div>
          <div style={{ display: 'flex', gap: 3, alignItems: 'center' }}>
            <span style={{ fontSize: 11, color: '#6b7280', fontWeight: 600 }}>Χρώμα γραφής:</span>
            {[{ val: null, label: 'Α', bg: newForm.color || '#6b7280', text: '#ffffff' }, { val: '#000000', label: 'Α', bg: newForm.color || '#6b7280', text: '#000000' }].map(opt => (
              <button key={opt.label + opt.text} onClick={() => setNewForm(f => ({ ...f, text_color: opt.val }))}
                style={{ width: 28, height: 28, borderRadius: 6, background: opt.bg, color: opt.text, fontSize: 14, fontWeight: 700, border: newForm.text_color === opt.val ? '3px solid #111' : '2px solid #dfe2e6', cursor: 'pointer' }}>{opt.label}</button>
            ))}
          </div>
          <button onClick={() => createMut.mutate(newForm)} disabled={!newForm.name.trim() || createMut.isPending}
            style={{ height: 36, padding: '0 16px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Αποθήκευση</button>
          <button onClick={() => setShowNew(false)} style={{ height: 36, padding: '0 14px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
        </div>
      )}
      {isLoading && <p style={{ padding: '16px 20px', color: '#9ca3af', fontSize: 13 }}>Φόρτωση…</p>}
      {!isLoading && flags.length === 0 && (
        <p style={{ padding: '24px 20px', textAlign: 'center', color: '#b8bdc4', fontSize: 13 }}>Δεν υπάρχουν σημαίες ακόμα.</p>
      )}
      {flags.map(flag => (
        <div key={flag.id} style={{ ...rowStyle, opacity: flag.is_active ? 1 : 0.45 }}>
          {editingId === flag.id ? (
            <div style={{ display: 'flex', flex: 1, flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
              <EmojiPicker value={editForm.emoji} onChange={v => setEditForm(f => ({ ...f, emoji: v }))} />
              <input value={editForm.name} onChange={e => setEditForm(f => ({ ...f, name: e.target.value }))}
                style={{ flex: 1, minWidth: 120, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} />
              <div style={{ display: 'flex', gap: 3 }}>
                {FLAG_COLORS.map(c => (
                  <button key={c} onClick={() => setEditForm(f => ({ ...f, color: c }))}
                    style={{ width: 20, height: 20, borderRadius: '50%', background: c, border: editForm.color === c ? '3px solid #111' : '2px solid transparent', cursor: 'pointer' }} />
                ))}
              </div>
              <div style={{ display: 'flex', gap: 3, alignItems: 'center' }}>
                {[{ val: null, text: '#ffffff' }, { val: '#000000', text: '#000000' }].map(opt => (
                  <button key={opt.text} onClick={() => setEditForm(f => ({ ...f, text_color: opt.val }))}
                    style={{ width: 24, height: 24, borderRadius: 6, background: editForm.color || '#6b7280', color: opt.text, fontSize: 13, fontWeight: 700, border: editForm.text_color === opt.val ? '3px solid #111' : '2px solid #dfe2e6', cursor: 'pointer' }}>Α</button>
                ))}
              </div>
              <button onClick={() => updateMut.mutate({ id: flag.id, ...editForm })} disabled={updateMut.isPending}
                style={{ height: 32, padding: '0 12px', borderRadius: 6, background: '#16a34a', color: 'white', border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>✓</button>
              <button onClick={() => setEditingId(null)}
                style={{ height: 32, padding: '0 10px', borderRadius: 6, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, cursor: 'pointer' }}>✕</button>
            </div>
          ) : (
            <>
              <div style={{ width: 32, height: 32, borderRadius: '50%', background: flag.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0 }}>
                {flag.emoji || '🏷️'}
              </div>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 500, color: '#111315' }}>{flag.name}</span>
              {!flag.is_active && <span style={{ fontSize: 11, color: '#9ca3af', fontStyle: 'italic' }}>Ανενεργή</span>}
              <button onClick={() => startEdit(flag)} style={{ height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, cursor: 'pointer', color: '#374151' }}>Επεξεργασία</button>
              <button
                onClick={() => toggleMut.mutate(flag.id)}
                disabled={toggleMut.isPending}
                style={{ height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #fed7aa', background: '#fff7ed', fontSize: 12, cursor: 'pointer', color: '#c2410c' }}
              >{flag.is_active ? 'Απενεργοποίηση' : 'Ενεργοποίηση'}</button>
              <button
                onClick={() => {
                  if (window.confirm(`Να διαγραφεί οριστικά η σήμανση "${flag.name}";`)) deleteMut.mutate(flag.id)
                }}
                disabled={deleteMut.isPending}
                style={{ height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #fee2e2', background: '#fff5f5', fontSize: 12, cursor: 'pointer', color: '#dc2626' }}
              >Διαγραφή</button>
            </>
          )}
        </div>
      ))}
    </SectionCard>
  )
}

// ─── Quick message templates ──────────────────────────────────────────────────

function QuickTemplatesSection() {
  const qc = useQueryClient()
  const [editingId, setEditingId] = useState(null)
  const [editBody, setEditBody] = useState('')
  const [newBody, setNewBody] = useState('')
  const [showNew, setShowNew] = useState(false)
  const { data: templates = [], isLoading } = useQuery({
    queryKey: ['quick-templates'],
    queryFn: () => client.get('/api/messages/templates').then(r => r.data),
    staleTime: 30_000,
  })
  const createMut = useMutation({
    mutationFn: (body) => client.post('/api/messages/templates', body),
    onSuccess: () => { toast.success('Δημιουργήθηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }); setShowNew(false); setNewBody('') },
    onError: () => toast.error('Σφάλμα'),
  })
  const updateMut = useMutation({
    mutationFn: ({ id, body }) => client.put(`/api/messages/templates/${id}`, { body }),
    onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }); setEditingId(null) },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })
  const deleteMut = useMutation({
    mutationFn: (id) => client.delete(`/api/messages/templates/${id}`),
    onSuccess: () => { toast.success('Διαγράφηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }) },
    onError: () => toast.error('Σφάλμα'),
  })
  const newButton = (
    <button onClick={() => setShowNew(v => !v)} style={{
      height: 32, padding: '0 14px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#374151',
    }}>+ Νέο</button>
  )
  return (
    <SectionCard title="Γρήγορα Μηνύματα" description="Πρότυπα μηνυμάτων για γρήγορη αποστολή στο προσωπικό" action={newButton}>
      {showNew && (
        <div style={{ padding: '14px 20px', background: '#f9fafb', display: 'flex', gap: 10, alignItems: 'center', borderTop: '1px solid #f4f4f2' }}>
          <input placeholder="Κείμενο μηνύματος…" value={newBody} onChange={e => setNewBody(e.target.value)}
            style={{ flex: 1, height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit' }} />
          <button onClick={() => createMut.mutate({ body: newBody, sort_order: templates.length + 1 })}
            disabled={!newBody.trim() || createMut.isPending}
            style={{ height: 36, padding: '0 16px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Αποθήκευση</button>
          <button onClick={() => setShowNew(false)} style={{ height: 36, padding: '0 14px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
        </div>
      )}
      {isLoading && <p style={{ padding: '16px 20px', color: '#9ca3af', fontSize: 13 }}>Φόρτωση…</p>}
      {!isLoading && templates.length === 0 && (
        <p style={{ padding: '24px 20px', textAlign: 'center', color: '#b8bdc4', fontSize: 13 }}>Δεν υπάρχουν πρότυπα ακόμα.</p>
      )}
      {templates.map((t, idx) => (
        <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' }}>
          <span style={{ width: 22, fontSize: 12, color: '#9ca3af', fontWeight: 600, flexShrink: 0 }}>{idx + 1}.</span>
          {editingId === t.id ? (
            <>
              <input value={editBody} onChange={e => setEditBody(e.target.value)}
                style={{ flex: 1, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} />
              <button onClick={() => updateMut.mutate({ id: t.id, body: editBody })} disabled={updateMut.isPending}
                style={{ height: 32, padding: '0 12px', borderRadius: 6, background: '#16a34a', color: 'white', border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>✓</button>
              <button onClick={() => setEditingId(null)}
                style={{ height: 32, padding: '0 10px', borderRadius: 6, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, cursor: 'pointer' }}>✕</button>
            </>
          ) : (
            <>
              <span style={{ flex: 1, fontSize: 14, color: '#111315' }}>{t.body}</span>
              <button onClick={() => { setEditingId(t.id); setEditBody(t.body) }}
                style={{ height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #dfe2e6', background: 'white', fontSize: 12, cursor: 'pointer', color: '#374151' }}>Επεξεργασία</button>
              <button onClick={() => deleteMut.mutate(t.id)}
                style={{ height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #fee2e2', background: '#fff5f5', fontSize: 12, cursor: 'pointer', color: '#dc2626' }}>Διαγραφή</button>
            </>
          )}
        </div>
      ))}
    </SectionCard>
  )
}

export default function OperationTab() {
  return (
    <div className="space-y-6">
      <ShiftSettingsSection />
      <FlagDefsSection />
      <QuickTemplatesSection />
    </div>
  )
}
