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

const API_URL = import.meta.env.VITE_API_URL || ''

function avatarColor(name) {
  const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
  let h = 0
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
  return palette[h % palette.length]
}

function WaiterAvatar({ waiter, size = 40 }) {
  const displayName = waiter.full_name || waiter.nickname || waiter.username
  if (waiter.avatar_url) {
    return (
      <img
        src={API_URL + waiter.avatar_url}
        alt={displayName}
        style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }}
      />
    )
  }
  const parts = displayName.trim().split(' ')
  const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: avatarColor(displayName),
      color: 'white', fontSize: size * 0.38, fontWeight: 600,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>{initials}</div>
  )
}

const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']

function PinInput({ value, onChange }) {
  function press(d) {
    if (d === '⌫') { onChange(value.slice(0, -1)); return }
    if (d === '' || value.length >= 6) return
    onChange(value + d)
  }
  return (
    <div className="space-y-3">
      <div className="flex justify-center gap-2">
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} className={`w-3 h-3 rounded-full border-2 ${i < value.length ? 'bg-primary-700 border-primary-700' : 'border-gray-300'}`} />
        ))}
      </div>
      <div className="grid grid-cols-3 gap-2">
        {DIGITS.map((d, i) => (
          <button key={i} type="button" onClick={() => press(d)} disabled={d === ''} className={`h-11 rounded-xl text-lg font-semibold transition-colors ${d === '' ? 'invisible' : d === '⌫' ? 'bg-gray-100 hover:bg-gray-200 text-gray-600' : 'bg-gray-100 hover:bg-primary-100 text-gray-800'}`}>
            {d}
          </button>
        ))}
      </div>
    </div>
  )
}

function ZoneModal({ waiter, groups, onClose }) {
  const qc = useQueryClient()
  // Derive initial state from waiter's zone_assignments
  const hasAllZones = waiter.zone_assignments.some(z => z.group_id === null)
  const assignedIds = new Set(waiter.zone_assignments.map(z => z.group_id).filter(id => id !== null))

  const [allZones, setAllZones] = useState(hasAllZones)
  const [selected, setSelected] = useState(new Set(assignedIds))

  const saveZones = useMutation({
    mutationFn: (body) => client.put(`/api/waiters/${waiter.id}/zones`, body),
    onSuccess: () => { toast.success('Zones ενημερώθηκαν'); qc.invalidateQueries({ queryKey: ['waiters'] }); onClose() },
    onError: () => toast.error('Σφάλμα'),
  })

  function toggleGroup(gid) {
    setSelected(prev => {
      const next = new Set(prev)
      if (next.has(gid)) next.delete(gid); else next.add(gid)
      return next
    })
  }

  function save() {
    if (allZones) {
      saveZones.mutate({ all_zones: true, group_ids: [] })
    } else {
      saveZones.mutate({ all_zones: false, group_ids: [...selected] })
    }
  }

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4">
        <h2 className="font-bold text-gray-800">Ζώνες — {waiter.username}</h2>

        <label className="flex items-center gap-3 cursor-pointer select-none">
          <input
            type="checkbox"
            className="w-5 h-5 rounded accent-primary-700"
            checked={allZones}
            onChange={e => { setAllZones(e.target.checked); if (e.target.checked) setSelected(new Set()) }}
          />
          <span className="font-semibold text-gray-700">Όλες οι ζώνες</span>
        </label>

        {!allZones && (
          <div className="space-y-2 max-h-60 overflow-y-auto">
            {groups.length === 0 && (
              <p className="text-sm text-gray-400">Δεν υπάρχουν ομάδες τραπεζιών.</p>
            )}
            {groups.map(g => (
              <label key={g.id} className="flex items-center gap-3 cursor-pointer select-none px-1">
                <input
                  type="checkbox"
                  className="w-5 h-5 rounded accent-primary-700"
                  checked={selected.has(g.id)}
                  onChange={() => toggleGroup(g.id)}
                />
                <span className="text-gray-700">{g.name}</span>
                {g.color && (
                  <span className="w-3 h-3 rounded-full inline-block ml-auto" style={{ background: g.color }} />
                )}
              </label>
            ))}
          </div>
        )}

        {!allZones && selected.size === 0 && (
          <p className="text-xs text-amber-600 bg-amber-50 rounded px-3 py-1.5">
            Χωρίς επιλογή ο σερβιτόρος δεν βλέπει κανένα τραπέζι.
          </p>
        )}

        <div className="flex gap-3 pt-2">
          <button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
          <button onClick={save} disabled={saveZones.isPending} className="flex-1 btn btn-primary">
            Αποθήκευση
          </button>
        </div>
      </div>
    </div>
  )
}


const EMPTY_FORM = { username: '', full_name: '', nickname: '', mobile_phone: '', role: 'waiter', pin: '' }

export default function WaitersPage() {
  const qc = useQueryClient()
  const [addModal, setAddModal] = useState(false)
  const [pinModal, setPinModal] = useState(null) // waiter id
  const [zoneModal, setZoneModal] = useState(null) // waiter object
  const [confirmDelete, setConfirmDelete] = useState(null) // waiter id
  const [newPin, setNewPin] = useState('')
  const [newForm, setNewForm] = useState(EMPTY_FORM)
  const [newAvatarFile, setNewAvatarFile] = useState(null)
  const [newAvatarPreview, setNewAvatarPreview] = useState(null)

  const [editModal, setEditModal] = useState(null) // waiter object
  const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', role: 'waiter' })
  const avatarInputRef = useRef(null)
  const newAvatarInputRef = useRef(null)

  const { data: waiters = [], isLoading } = useQuery({
    queryKey: ['waiters'],
    queryFn: () => client.get('/api/waiters/').then(r => r.data),
  })

  const { data: groups = [] } = useQuery({
    queryKey: ['table-groups'],
    queryFn: () => client.get('/api/tables/groups').then(r => r.data),
  })

  const invalidate = () => qc.invalidateQueries({ queryKey: ['waiters'] })

  const createWaiter = useMutation({
    mutationFn: async (body) => {
      const res = await client.post('/api/waiters/', body)
      if (newAvatarFile) {
        const fd = new FormData()
        fd.append('file', newAvatarFile)
        await client.post(`/api/waiters/${res.data.id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } })
      }
      return res
    },
    onSuccess: () => {
      toast.success('Σερβιτόρος δημιουργήθηκε')
      setAddModal(false)
      setNewForm(EMPTY_FORM)
      setNewAvatarFile(null)
      setNewAvatarPreview(null)
      invalidate()
    },
    onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
  })

  const updateWaiter = useMutation({
    mutationFn: ({ id, ...body }) => client.put(`/api/waiters/${id}`, body),
    onSuccess: () => { toast.success('Στοιχεία ενημερώθηκαν'); setEditModal(null); invalidate() },
    onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
  })

  const uploadAvatar = useMutation({
    mutationFn: ({ id, file }) => {
      const fd = new FormData()
      fd.append('file', file)
      return client.post(`/api/waiters/${id}/avatar`, fd, { headers: { 'Content-Type': 'multipart/form-data' } })
    },
    onSuccess: (res) => {
      toast.success('Avatar ανέβηκε')
      setEditModal(res.data)
      invalidate()
    },
    onError: () => toast.error('Σφάλμα μεταφόρτωσης'),
  })

  const deleteAvatar = useMutation({
    mutationFn: (id) => client.delete(`/api/waiters/${id}/avatar`),
    onSuccess: (res) => {
      toast.success('Avatar αφαιρέθηκε')
      setEditModal(res.data)
      invalidate()
    },
    onError: () => toast.error('Σφάλμα'),
  })

  const toggleBlock = useMutation({
    mutationFn: (id) => client.put(`/api/waiters/${id}/block`),
    onSuccess: () => { invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  const resetPin = useMutation({
    mutationFn: ({ id, pin }) => client.put(`/api/waiters/${id}/reset-pin?pin=${encodeURIComponent(pin)}`),
    onSuccess: () => { toast.success('PIN ανανεώθηκε'); setPinModal(null); setNewPin('') },
    onError: () => toast.error('Σφάλμα'),
  })

  const deleteWaiter = useMutation({
    mutationFn: (id) => client.delete(`/api/waiters/${id}`),
    onSuccess: () => { toast.success('Διαγράφηκε'); setConfirmDelete(null); invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-end">
        <button onClick={() => setAddModal(true)} className="btn btn-primary">+ Νέος σερβιτόρος</button>
      </div>

      <div className="card divide-y divide-gray-100">
        {waiters.length === 0 && (
          <p className="px-4 py-8 text-center text-gray-400">Δεν υπάρχουν σερβιτόροι.</p>
        )}
        {waiters.map(w => (
          <div key={w.id} className="flex items-center gap-4 px-4 py-3">
            <WaiterAvatar waiter={w} size={44} />
            <div className="flex-1 min-w-0">
              <div className="flex items-baseline gap-2">
                <p className="font-semibold text-gray-800">{w.full_name || w.username}</p>
                {w.nickname && <span className="text-xs text-gray-400">({w.nickname})</span>}
              </div>
              <p className="text-xs text-gray-500">{w.username} · {w.role}</p>
              {w.mobile_phone && <p className="text-xs text-gray-400">{w.mobile_phone}</p>}
              {w.role === 'waiter' && (
                <p className="text-xs text-gray-400 mt-0.5">
                  {w.zone_assignments.length === 0
                    ? 'Χωρίς ζώνες'
                    : w.zone_assignments.some(z => z.group_id === null)
                    ? 'Όλες οι ζώνες'
                    : `${w.zone_assignments.length} ζών${w.zone_assignments.length === 1 ? 'η' : 'ες'}`}
                </p>
              )}
            </div>
            <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${w.is_active ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}`}>
              {w.is_active ? 'Ενεργός' : 'Αποκλεισμένος'}
            </span>
            <button onClick={() => { setEditModal(w); setEditForm({ username: w.username || '', full_name: w.full_name || '', nickname: w.nickname || '', mobile_phone: w.mobile_phone || '', role: w.role || 'waiter' }) }} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">Επεξεργασία</button>
            {w.role === 'waiter' && (
              <button onClick={() => setZoneModal(w)} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">Ζώνες</button>
            )}
            <button onClick={() => setPinModal(w.id)} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">Reset PIN</button>
            <button onClick={() => toggleBlock.mutate(w.id)} className={`btn text-sm px-3 py-1.5 min-h-0 h-9 ${w.is_active ? 'btn-danger' : 'btn-secondary'}`}>
              {w.is_active ? 'Αποκλεισμός' : 'Ενεργοποίηση'}
            </button>
            <button onClick={() => setConfirmDelete(w.id)} className="btn btn-ghost text-sm px-2 py-1.5 min-h-0 h-9 text-red-500 hover:bg-red-50">🗑</button>
          </div>
        ))}
      </div>

      {/* Add waiter modal */}
      {addModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4 max-h-[90vh] overflow-y-auto">
            <h2 className="font-bold text-gray-800">Νέος σερβιτόρος</h2>

            {/* Avatar picker */}
            <div className="flex items-center gap-4">
              {newAvatarPreview ? (
                <img src={newAvatarPreview} alt="preview" style={{ width: 64, height: 64, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />
              ) : (
                <div style={{ width: 64, height: 64, borderRadius: '50%', background: '#e5e7eb', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <span style={{ fontSize: 28, color: '#9ca3af' }}>👤</span>
                </div>
              )}
              <div className="flex flex-col gap-2">
                <input
                  ref={newAvatarInputRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={e => {
                    const file = e.target.files?.[0]
                    if (file) {
                      setNewAvatarFile(file)
                      setNewAvatarPreview(URL.createObjectURL(file))
                    }
                    e.target.value = ''
                  }}
                />
                <button onClick={() => newAvatarInputRef.current?.click()} type="button" className="btn btn-secondary text-xs px-3 py-1.5 min-h-0 h-8">
                  {newAvatarPreview ? 'Αλλαγή φωτογραφίας' : 'Προσθήκη φωτογραφίας'}
                </button>
                {newAvatarPreview && (
                  <button type="button" onClick={() => { setNewAvatarFile(null); setNewAvatarPreview(null) }} className="btn btn-ghost text-xs px-3 py-1.5 min-h-0 h-8 text-red-500 hover:bg-red-50">
                    Αφαίρεση
                  </button>
                )}
              </div>
            </div>

            <div>
              <label className="label">Πλήρες όνομα *</label>
              <input className="input" placeholder="π.χ. Γιώργος Παπαδόπουλος" value={newForm.full_name} onChange={e => setNewForm(f => ({ ...f, full_name: e.target.value }))} autoFocus />
            </div>
            <div>
              <label className="label">Παρατσούκλι (nickname) *</label>
              <input className="input" placeholder="π.χ. Γιώργος" value={newForm.nickname} onChange={e => setNewForm(f => ({ ...f, nickname: e.target.value }))} />
            </div>
            <div>
              <label className="label">Κινητό τηλέφωνο</label>
              <input className="input" placeholder="π.χ. 6901234567" value={newForm.mobile_phone} onChange={e => setNewForm(f => ({ ...f, mobile_phone: e.target.value }))} />
            </div>
            <div>
              <label className="label">Όνομα χρήστη *</label>
              <input className="input" placeholder="π.χ. giorgos" value={newForm.username} onChange={e => setNewForm(f => ({ ...f, username: e.target.value }))} />
            </div>
            <div>
              <label className="label">Ρόλος *</label>
              <select className="input" value={newForm.role} onChange={e => setNewForm(f => ({ ...f, role: e.target.value }))}>
                <option value="waiter">Σερβιτόρος</option>
                <option value="manager">Διαχειριστής</option>
              </select>
            </div>
            <div>
              <label className="label mb-2">PIN *</label>
              <PinInput value={newForm.pin} onChange={pin => setNewForm(f => ({ ...f, pin }))} />
            </div>
            <div className="flex gap-3 pt-2">
              <button onClick={() => { setAddModal(false); setNewForm(EMPTY_FORM); setNewAvatarFile(null); setNewAvatarPreview(null) }} className="flex-1 btn btn-secondary">Ακύρωση</button>
              <button
                onClick={() => createWaiter.mutate({ username: newForm.username, full_name: newForm.full_name || null, nickname: newForm.nickname || null, mobile_phone: newForm.mobile_phone || null, pin: newForm.pin, role: newForm.role, is_active: true })}
                disabled={createWaiter.isPending || !newForm.username.trim() || !newForm.full_name.trim() || !newForm.nickname.trim() || newForm.pin.length < 4}
                className="flex-1 btn btn-primary"
              >
                {createWaiter.isPending ? 'Δημιουργία…' : 'Δημιουργία'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit profile modal */}
      {editModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4 max-h-[90vh] overflow-y-auto">
            <h2 className="font-bold text-gray-800">Επεξεργασία — {editModal.full_name || editModal.username}</h2>

            {/* Avatar section */}
            <div className="flex items-center gap-4">
              <WaiterAvatar waiter={editModal} size={64} />
              <div className="flex flex-col gap-2">
                <input
                  ref={avatarInputRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={e => {
                    const file = e.target.files?.[0]
                    if (file) uploadAvatar.mutate({ id: editModal.id, file })
                    e.target.value = ''
                  }}
                />
                <button
                  onClick={() => avatarInputRef.current?.click()}
                  disabled={uploadAvatar.isPending}
                  className="btn btn-secondary text-xs px-3 py-1.5 min-h-0 h-8"
                >
                  {uploadAvatar.isPending ? 'Μεταφόρτωση…' : editModal.avatar_url ? 'Αλλαγή φωτογραφίας' : 'Προσθήκη φωτογραφίας'}
                </button>
                {editModal.avatar_url && (
                  <button
                    onClick={() => deleteAvatar.mutate(editModal.id)}
                    disabled={deleteAvatar.isPending}
                    className="btn btn-ghost text-xs px-3 py-1.5 min-h-0 h-8 text-red-500 hover:bg-red-50"
                  >
                    Αφαίρεση
                  </button>
                )}
              </div>
            </div>

            <div>
              <label className="label">Πλήρες όνομα *</label>
              <input className="input" value={editForm.full_name} onChange={e => setEditForm(f => ({ ...f, full_name: e.target.value }))} autoFocus />
            </div>
            <div>
              <label className="label">Παρατσούκλι (nickname) *</label>
              <input className="input" placeholder="π.χ. Γιώργος" value={editForm.nickname} onChange={e => setEditForm(f => ({ ...f, nickname: e.target.value }))} />
            </div>
            <div>
              <label className="label">Κινητό τηλέφωνο</label>
              <input className="input" value={editForm.mobile_phone} onChange={e => setEditForm(f => ({ ...f, mobile_phone: e.target.value }))} />
            </div>
            <div>
              <label className="label">Όνομα χρήστη *</label>
              <input className="input" value={editForm.username} onChange={e => setEditForm(f => ({ ...f, username: e.target.value }))} />
            </div>
            <div>
              <label className="label">Ρόλος *</label>
              <select className="input" value={editForm.role} onChange={e => setEditForm(f => ({ ...f, role: e.target.value }))}>
                <option value="waiter">Σερβιτόρος</option>
                <option value="manager">Διαχειριστής</option>
              </select>
            </div>
            <div className="flex gap-3 pt-2">
              <button onClick={() => setEditModal(null)} className="flex-1 btn btn-secondary">Ακύρωση</button>
              <button
                onClick={() => updateWaiter.mutate({ id: editModal.id, username: editForm.username.trim() || undefined, full_name: editForm.full_name || null, nickname: editForm.nickname || null, mobile_phone: editForm.mobile_phone || null, role: editForm.role })}
                disabled={updateWaiter.isPending || !editForm.username.trim() || !editForm.full_name.trim() || !editForm.nickname.trim()}
                className="flex-1 btn btn-primary"
              >
                {updateWaiter.isPending ? 'Αποθήκευση…' : 'Αποθήκευση'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Reset PIN modal */}
      {pinModal !== null && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-xs p-6 space-y-4">
            <h2 className="font-bold text-gray-800">Reset PIN — {waiters.find(w => w.id === pinModal)?.username}</h2>
            <PinInput value={newPin} onChange={setNewPin} />
            <div className="flex gap-3 pt-2">
              <button onClick={() => { setPinModal(null); setNewPin('') }} className="flex-1 btn btn-secondary">Ακύρωση</button>
              <button
                onClick={() => resetPin.mutate({ id: pinModal, pin: newPin })}
                disabled={newPin.length < 4}
                className="flex-1 btn btn-primary"
              >
                Αποθήκευση
              </button>
            </div>
          </div>
        </div>
      )}

      {confirmDelete !== null && (
        <ConfirmModal
          title="Διαγραφή σερβιτόρου;"
          message="Αυτή η ενέργεια δεν μπορεί να αναιρεθεί."
          confirmLabel="Διαγραφή"
          confirmClass="btn-danger"
          onConfirm={() => deleteWaiter.mutate(confirmDelete)}
          onCancel={() => setConfirmDelete(null)}
        />
      )}

      {zoneModal && (
        <ZoneModal waiter={zoneModal} groups={groups} onClose={() => setZoneModal(null)} />
      )}
    </div>
  )
}
