import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Tag, Power, Pencil, Trash2, Clock } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import Button from '../../../ui/Button'
import Modal from '../../../ui/Modal'
import { ConfirmModal } from '../../../ui/Modal'

const DAYS = ['Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ', 'Κυρ']

const api = {
  list:   ()     => client.get('/api/pricing/groups').then(r => r.data),
  create: body   => client.post('/api/pricing/groups', body).then(r => r.data),
  update: (id,b) => client.put(`/api/pricing/groups/${id}`, b).then(r => r.data),
  toggle: id     => client.patch(`/api/pricing/groups/${id}/toggle`).then(r => r.data),
  remove: id     => client.delete(`/api/pricing/groups/${id}`),
}

const COLORS = [
  '#6366f1','#8b5cf6','#ec4899','#f43f5e','#f97316',
  '#eab308','#22c55e','#14b8a6','#0ea5e9','#64748b',
]

function GroupForm({ initial, onSave, onCancel, saving }) {
  const blank = { name: '', description: '', color: COLORS[0], is_active: false,
                  auto_enable_time: '', auto_disable_time: '', auto_days: [] }
  const [f, setF] = useState(initial ? {
    ...initial,
    auto_days: initial.auto_days ?? [],
  } : blank)

  const set = (k, v) => setF(p => ({ ...p, [k]: v }))
  const toggleDay = d => set('auto_days', f.auto_days.includes(d)
    ? f.auto_days.filter(x => x !== d)
    : [...f.auto_days, d])

  const hasSchedule = f.auto_enable_time || f.auto_disable_time || f.auto_days.length > 0

  function submit(e) {
    e.preventDefault()
    if (!f.name.trim()) return toast.error('Απαιτείται όνομα')
    onSave({
      ...f,
      auto_days: f.auto_days.length ? f.auto_days : null,
      auto_enable_time:  f.auto_enable_time  || null,
      auto_disable_time: f.auto_disable_time || null,
    })
  }

  return (
    <form onSubmit={submit} className="space-y-4">
      {/* Name */}
      <div>
        <label className="block text-[12px] font-medium text-slate-600 mb-1">Όνομα</label>
        <input className="input w-full" value={f.name} onChange={e => set('name', e.target.value)}
          placeholder="π.χ. Happy Hour" autoFocus />
      </div>

      {/* Description */}
      <div>
        <label className="block text-[12px] font-medium text-slate-600 mb-1">Περιγραφή (προαιρετική)</label>
        <input className="input w-full" value={f.description ?? ''} onChange={e => set('description', e.target.value)}
          placeholder="Σύντομη περιγραφή..." />
      </div>

      {/* Color */}
      <div>
        <label className="block text-[12px] font-medium text-slate-600 mb-2">Χρώμα</label>
        <div className="flex flex-wrap gap-2">
          {COLORS.map(c => (
            <button type="button" key={c} onClick={() => set('color', c)}
              className={`w-7 h-7 rounded-full transition-transform ${f.color === c ? 'ring-2 ring-offset-2 ring-slate-400 scale-110' : 'hover:scale-105'}`}
              style={{ background: c }} />
          ))}
          <input type="color" value={f.color ?? '#6366f1'} onChange={e => set('color', e.target.value)}
            className="w-7 h-7 rounded-full border-0 cursor-pointer p-0.5 bg-transparent" title="Προσαρμοσμένο χρώμα" />
        </div>
      </div>

      {/* Active toggle */}
      <label className="flex items-center gap-3 cursor-pointer select-none">
        <div onClick={() => set('is_active', !f.is_active)}
          className={`relative w-9 h-5 rounded-full transition-colors ${f.is_active ? 'bg-sky-500' : 'bg-slate-200'}`}>
          <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${f.is_active ? 'translate-x-4' : ''}`} />
        </div>
        <span className="text-[13px] font-medium text-slate-700">Ενεργή τώρα</span>
      </label>

      {/* Auto-schedule */}
      <div className="rounded-lg border border-slate-200 p-3 space-y-3">
        <div className="flex items-center gap-2">
          <Clock className="w-3.5 h-3.5 text-slate-400" />
          <span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">Αυτόματο Χρονοδιάγραμμα</span>
          <span className="text-[11px] text-slate-400">(προαιρετικό)</span>
        </div>

        <div className="flex gap-3">
          <div className="flex-1">
            <label className="block text-[11px] text-slate-500 mb-1">Ενεργοποίηση</label>
            <input type="time" className="input w-full text-[13px]"
              value={f.auto_enable_time ?? ''} onChange={e => set('auto_enable_time', e.target.value)} />
          </div>
          <div className="flex-1">
            <label className="block text-[11px] text-slate-500 mb-1">Απενεργοποίηση</label>
            <input type="time" className="input w-full text-[13px]"
              value={f.auto_disable_time ?? ''} onChange={e => set('auto_disable_time', e.target.value)} />
          </div>
        </div>

        <div>
          <label className="block text-[11px] text-slate-500 mb-1.5">Ημέρες</label>
          <div className="flex gap-1.5 flex-wrap">
            {DAYS.map((d, i) => (
              <button type="button" key={i} onClick={() => toggleDay(i)}
                className={`px-2.5 py-1 rounded text-[12px] font-medium transition-colors ${
                  f.auto_days.includes(i) ? 'bg-sky-100 text-sky-700' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'
                }`}>{d}</button>
            ))}
          </div>
        </div>

        {hasSchedule && (!f.auto_enable_time || !f.auto_disable_time || !f.auto_days.length) && (
          <p className="text-[11px] text-amber-600 bg-amber-50 rounded px-2 py-1">
            Για πλήρες χρονοδιάγραμμα ορίστε ώρα ενεργοποίησης, ώρα απενεργοποίησης και τουλάχιστον μία ημέρα.
          </p>
        )}
      </div>

      <Modal.Footer>
        <Button type="button" variant="secondary" onClick={onCancel}>Ακύρωση</Button>
        <Button type="submit" variant="primary" disabled={saving}>
          {saving ? 'Αποθήκευση...' : 'Αποθήκευση'}
        </Button>
      </Modal.Footer>
    </form>
  )
}

function GroupCard({ group, onEdit, onDelete }) {
  const qc = useQueryClient()
  const toggle = useMutation({
    mutationFn: () => api.toggle(group.id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['pricing-groups'] }),
    onError: () => toast.error('Σφάλμα'),
  })

  return (
    <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-4 flex items-start gap-3">
      {/* Color dot */}
      <div className="w-3 h-3 rounded-full mt-1 shrink-0" style={{ background: group.color ?? '#6366f1' }} />

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-[14px] font-semibold text-slate-800 truncate">{group.name}</span>
          <span className={`text-[11px] font-medium px-1.5 py-0.5 rounded-full ${
            group.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'
          }`}>{group.is_active ? 'Ενεργή' : 'Ανενεργή'}</span>
        </div>
        {group.description && <p className="text-[12px] text-slate-500 mt-0.5 truncate">{group.description}</p>}
        {group.auto_enable_time && group.auto_disable_time && (
          <p className="text-[11px] text-slate-400 mt-1 flex items-center gap-1">
            <Clock className="w-3 h-3" />
            {group.auto_enable_time}–{group.auto_disable_time}
            {group.auto_days?.length > 0 && (
              <span className="ml-1">{group.auto_days.map(d => DAYS[d]).join(', ')}</span>
            )}
          </p>
        )}
      </div>

      <div className="flex items-center gap-1 shrink-0">
        {/* Quick toggle */}
        <button onClick={() => toggle.mutate()}
          className={`p-1.5 rounded-lg transition-colors ${
            group.is_active ? 'text-emerald-600 hover:bg-emerald-50' : 'text-slate-400 hover:bg-slate-100'
          }`} title={group.is_active ? 'Απενεργοποίηση' : 'Ενεργοποίηση'}>
          <Power className="w-4 h-4" />
        </button>
        <button onClick={() => onEdit(group)}
          className="p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
          <Pencil className="w-4 h-4" />
        </button>
        <button onClick={() => onDelete(group)}
          className="p-1.5 rounded-lg text-slate-400 hover:bg-rose-50 hover:text-rose-500 transition-colors">
          <Trash2 className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

export default function PriceGroupsTab() {
  const qc = useQueryClient()
  const [showForm, setShowForm] = useState(false)
  const [editing, setEditing] = useState(null)
  const [deleting, setDeleting] = useState(null)

  const { data: groups = [], isLoading } = useQuery({ queryKey: ['pricing-groups'], queryFn: api.list })

  const create = useMutation({
    mutationFn: api.create,
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setShowForm(false); toast.success('Ομάδα δημιουργήθηκε') },
    onError: () => toast.error('Σφάλμα δημιουργίας'),
  })
  const update = useMutation({
    mutationFn: ({ id, body }) => api.update(id, body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setEditing(null); toast.success('Αποθηκεύτηκε') },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })
  const remove = useMutation({
    mutationFn: api.remove,
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setDeleting(null); toast.success('Διαγράφηκε') },
    onError: () => toast.error('Σφάλμα διαγραφής'),
  })

  return (
    <div className="p-6 space-y-4">
      {/* Header row */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-[14px] font-semibold text-slate-800">Ομάδες Τιμών</h2>
          <p className="text-[12px] text-slate-500 mt-0.5">
            Ονομαστές ομάδες που ενεργοποιούνται χειροκίνητα ή αυτόματα. Χρησιμοποιούνται ως συνθήκη σε τροποποιητές τιμής.
          </p>
        </div>
        <Button variant="primary" onClick={() => setShowForm(true)}>
          <Plus className="w-4 h-4 mr-1.5" />Νέα Ομάδα
        </Button>
      </div>

      {/* List */}
      {isLoading ? (
        <div className="flex justify-center py-12">
          <div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
        </div>
      ) : groups.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-slate-400">
          <Tag className="w-10 h-10 mb-3 opacity-30" />
          <p className="text-[13px]">Δεν υπάρχουν ομάδες τιμών</p>
          <p className="text-[12px] mt-1">Δημιουργήστε μια ομάδα για Happy Hour, Εποχή κ.λπ.</p>
        </div>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {groups.map(g => (
            <GroupCard key={g.id} group={g}
              onEdit={setEditing}
              onDelete={setDeleting} />
          ))}
        </div>
      )}

      {/* Create modal */}
      {showForm && (
        <Modal title="Νέα Ομάδα Τιμών" onClose={() => setShowForm(false)} maxWidth="max-w-md">
          <GroupForm onSave={body => create.mutate(body)} onCancel={() => setShowForm(false)} saving={create.isPending} />
        </Modal>
      )}

      {/* Edit modal */}
      {editing && (
        <Modal title="Επεξεργασία Ομάδας" onClose={() => setEditing(null)} maxWidth="max-w-md">
          <GroupForm initial={editing} onSave={body => update.mutate({ id: editing.id, body })}
            onCancel={() => setEditing(null)} saving={update.isPending} />
        </Modal>
      )}

      {/* Delete confirm */}
      {deleting && (
        <ConfirmModal
          title="Διαγραφή Ομάδας"
          message={`Θέλετε σίγουρα να διαγράψετε την ομάδα "${deleting.name}"; Τυχόν τροποποιητές που τη χρησιμοποιούν δεν θα επηρεαστούν αλλά η συνθήκη δεν θα εκπληρώνεται πλέον.`}
          confirmLabel="Διαγραφή"
          onConfirm={() => remove.mutate(deleting.id)}
          onCancel={() => setDeleting(null)}
        />
      )}
    </div>
  )
}
