import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import client from '../api/client'
import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore'

// ─── Relative time (Greek) ────────────────────────────────────────────────────

function relativeTime(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now - date
  const diffMin = Math.floor(diffMs / 60_000)
  const diffHours = Math.floor(diffMs / 3_600_000)

  if (diffMin < 1) return 'τώρα'
  if (diffMin < 60) return `${diffMin}λ`
  if (diffHours < 24) return `${diffHours}ω`

  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (
    date.getDate() === yesterday.getDate() &&
    date.getMonth() === yesterday.getMonth() &&
    date.getFullYear() === yesterday.getFullYear()
  ) return 'χθες'

  return date.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' })
}

// ─── Avatar ───────────────────────────────────────────────────────────────────

function Avatar({ label, size = 44, isGroup = false }) {
  const initials = isGroup
    ? '👥'
    : (label || '?').slice(0, 2).toUpperCase()

  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: isGroup ? 'var(--bg3)' : 'var(--accent)',
      color: isGroup ? 'var(--text)' : 'var(--accent-fg)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: isGroup ? 20 : 16, fontWeight: 700,
    }}>
      {initials}
    </div>
  )
}

// ─── Conversation row ─────────────────────────────────────────────────────────

function ConvRow({ conv, currentUserId, onClick }) {
  const isGroup = conv.type === 'group'
  const isDirect = conv.type === 'direct'

  const title = isGroup
    ? (conv.name || 'Ομάδα')
    : (conv.participants?.find(p => p.user_id !== currentUserId)?.username || 'Άγνωστος')

  const lastMsg = conv.last_message
  const preview = lastMsg
    ? lastMsg.is_deleted
      ? 'Το μήνυμα διαγράφηκε'
      : lastMsg.body
    : 'Δεν υπάρχουν μηνύματα'

  const timestamp = lastMsg?.sent_at || conv.created_at
  const hasUnread = (conv.unread_count || 0) > 0

  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px', borderBottom: '1px solid var(--border)',
        background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
        width: '100%', textAlign: 'left', cursor: 'pointer',
      }}
    >
      <Avatar label={isGroup ? null : title} isGroup={isGroup} />

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{
            fontSize: 15, fontWeight: hasUnread ? 700 : 600,
            color: 'var(--text)', flex: 1,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {title}
          </span>
          <span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>
            {relativeTime(timestamp)}
          </span>
        </div>
        <div style={{
          fontSize: 13, color: 'var(--muted)', marginTop: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          fontStyle: lastMsg?.is_deleted ? 'italic' : 'normal',
          fontWeight: hasUnread ? 600 : 400,
        }}>
          {isGroup && lastMsg && !lastMsg.is_deleted && lastMsg.sender_name
            ? `${lastMsg.sender_name}: ${preview}`
            : preview
          }
        </div>
      </div>

      {hasUnread && (
        <div style={{
          background: 'var(--danger)', color: '#fff',
          borderRadius: '50%', minWidth: 20, height: 20,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 11, fontWeight: 800, flexShrink: 0,
          padding: conv.unread_count > 9 ? '0 6px' : '0',
        }}>
          {conv.unread_count > 99 ? '99+' : conv.unread_count}
        </div>
      )}
    </button>
  )
}

// ─── New Chat bottom drawer ───────────────────────────────────────────────────

function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
  const [staff, setStaff] = useState([])
  const [loading, setLoading] = useState(true)
  const [mode, setMode] = useState('picker') // 'picker' | 'group_name' | 'group_pick'
  const [groupName, setGroupName] = useState('')
  const [selectedIds, setSelectedIds] = useState([])
  const [creating, setCreating] = useState(false)
  const [error, setError] = useState(null)

  useEffect(() => {
    client.get('/api/chat/users')
      .then(r => setStaff((r.data || []).filter(u => u.id !== currentUserId)))
      .catch(() => setError('Αποτυχία φόρτωσης χρηστών'))
      .finally(() => setLoading(false))
  }, [currentUserId])

  async function startDirect(userId) {
    setCreating(true)
    setError(null)
    try {
      const res = await client.post('/api/chat/conversations', {
        type: 'direct',
        participant_ids: [userId],
      })
      onConversationCreated(res.data)
    } catch (e) {
      setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας συνομιλίας')
      setCreating(false)
    }
  }

  async function createGroup() {
    if (!groupName.trim()) return
    setCreating(true)
    setError(null)
    try {
      const res = await client.post('/api/chat/conversations', {
        type: 'group',
        name: groupName.trim(),
        participant_ids: selectedIds,
      })
      onConversationCreated(res.data)
    } catch (e) {
      setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας ομάδας')
      setCreating(false)
    }
  }

  function toggleSelect(id) {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    )
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ maxHeight: '80svh' }}>
        <div className="modal-handle" />

        {mode === 'picker' && (
          <>
            <h2 className="modal-title" style={{ marginBottom: 16 }}>Νέα Συνομιλία</h2>

            {/* New Group option */}
            <button
              onClick={() => setMode('group_name')}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 4px', background: 'none', border: 'none',
                borderBottom: '1px solid var(--border)', width: '100%',
                cursor: 'pointer', textAlign: 'left', marginBottom: 4,
              }}
            >
              <div style={{
                width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
                background: 'var(--accent)', display: 'flex', alignItems: 'center',
                justifyContent: 'center', fontSize: 20,
              }}>
                👥
              </div>
              <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>Νέα Ομάδα</span>
            </button>

            <div style={{ flex: 1, overflowY: 'auto', marginTop: 4 }}>
              {loading && (
                <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
                  Φόρτωση…
                </p>
              )}
              {!loading && staff.length === 0 && !error && (
                <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>
                  Δεν υπάρχει άλλο προσωπικό
                </p>
              )}
              {staff.map(u => (
                <button
                  key={u.id}
                  onClick={() => startDirect(u.id)}
                  disabled={creating}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '12px 4px', background: 'none', border: 'none',
                    borderBottom: '1px solid var(--border)', width: '100%',
                    cursor: creating ? 'not-allowed' : 'pointer', textAlign: 'left',
                    opacity: creating ? 0.6 : 1,
                  }}
                >
                  <Avatar label={u.username || u.full_name} />
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
                      {u.full_name || u.username}
                    </div>
                    {u.full_name && (
                      <div style={{ fontSize: 12, color: 'var(--muted)' }}>{u.username}</div>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </>
        )}

        {mode === 'group_name' && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <button
                onClick={() => setMode('picker')}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text)', padding: 0 }}
              >
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                  <path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <h2 className="modal-title" style={{ margin: 0 }}>Όνομα Ομάδας</h2>
            </div>
            <input
              autoFocus
              value={groupName}
              onChange={e => setGroupName(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && groupName.trim() && setMode('group_pick')}
              placeholder="π.χ. Βραδινή βάρδια"
              style={{
                width: '100%', padding: '12px 14px',
                background: 'var(--bg3)', border: '1px solid var(--border)',
                borderRadius: 12, color: 'var(--text)', fontSize: 16, outline: 'none',
                boxSizing: 'border-box', marginBottom: 16,
              }}
            />
            <button
              className="btn"
              style={{ width: '100%' }}
              disabled={!groupName.trim()}
              onClick={() => groupName.trim() && setMode('group_pick')}
            >
              Επόμενο
            </button>
          </>
        )}

        {mode === 'group_pick' && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <button
                onClick={() => setMode('group_name')}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text)', padding: 0 }}
              >
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                  <path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <h2 className="modal-title" style={{ margin: 0 }}>Επιλογή Μελών</h2>
            </div>
            <p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>
              Ομάδα: <strong style={{ color: 'var(--text)' }}>{groupName}</strong>
            </p>

            <div style={{ flex: 1, overflowY: 'auto', marginBottom: 12 }}>
              {staff.map(u => {
                const selected = selectedIds.includes(u.id)
                return (
                  <button
                    key={u.id}
                    onClick={() => toggleSelect(u.id)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '11px 4px', background: 'none', border: 'none',
                      borderBottom: '1px solid var(--border)', width: '100%',
                      cursor: 'pointer', textAlign: 'left',
                    }}
                  >
                    <div style={{
                      width: 24, height: 24, borderRadius: 6, flexShrink: 0,
                      border: `2px solid ${selected ? 'var(--accent)' : 'var(--border)'}`,
                      background: selected ? 'var(--accent)' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      transition: 'background 0.12s, border-color 0.12s',
                    }}>
                      {selected && (
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                          <path d="M2.5 7l3 3 6-6" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      )}
                    </div>
                    <Avatar label={u.username || u.full_name} size={40} />
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
                        {u.full_name || u.username}
                      </div>
                      {u.full_name && (
                        <div style={{ fontSize: 12, color: 'var(--muted)' }}>{u.username}</div>
                      )}
                    </div>
                  </button>
                )
              })}
            </div>

            <button
              className="btn"
              style={{ width: '100%' }}
              disabled={creating}
              onClick={createGroup}
            >
              {creating ? 'Δημιουργία…' : `Δημιουργία Ομάδας${selectedIds.length > 0 ? ` (${selectedIds.length})` : ''}`}
            </button>
          </>
        )}

        {error && (
          <p style={{ fontSize: 13, color: 'var(--danger)', marginTop: 10, textAlign: 'center' }}>{error}</p>
        )}
      </div>
    </div>
  )
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function ChatListPage() {
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const { conversations, setConversations, upsertConversation } = useChatStore()
  const [showNewChat, setShowNewChat] = useState(false)
  const [loading, setLoading] = useState(true)

  // ── Load conversations ───────────────────────────────────────────────────────
  useEffect(() => {
    client.get('/api/chat/conversations')
      .then(r => setConversations(r.data || []))
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])


  function handleConversationCreated(conv) {
    upsertConversation(conv)
    setShowNewChat(false)
    navigate(`/messages/${conv.id}`)
  }

  // Separate system group (pinned) from regular conversations
  const systemConv = conversations.find(c => c.is_system)
  const regularConvs = conversations.filter(c => !c.is_system)

  return (
    <>
      {/* Conversation list */}
      <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>

        {/* ── New conversation row (always first) ─────────────────────── */}
        <button
          onClick={() => setShowNewChat(true)}
          style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 16px', width: '100%',
            background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
            cursor: 'pointer', textAlign: 'left',
          }}
        >
          <div style={{
            width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
            background: 'var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="var(--accent-fg)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--accent)' }}>
            Νέα Συνομιλία
          </span>
        </button>

        {/* ── System group (pinned second) ────────────────────────────── */}
        {systemConv && (
          <ConvRow
            conv={systemConv}
            currentUserId={user?.id}
            onClick={() => navigate(`/messages/${systemConv.id}`)}
          />
        )}

        {/* ── Regular conversations ────────────────────────────────────── */}
        {loading && (
          <div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)', fontSize: 14 }}>
            Φόρτωση…
          </div>
        )}

        {!loading && regularConvs.length === 0 && !systemConv && (
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            flex: 1, padding: 40, gap: 12, minHeight: 200,
          }}>
            <span style={{ fontSize: 40 }}>💬</span>
            <p style={{ fontSize: 15, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
              Πατήστε «Νέα Συνομιλία» για να ξεκινήσετε μια συζήτηση.
            </p>
          </div>
        )}

        {!loading && regularConvs.map(conv => (
          <ConvRow
            key={conv.id}
            conv={conv}
            currentUserId={user?.id}
            onClick={() => navigate(`/messages/${conv.id}`)}
          />
        ))}
      </div>

      {showNewChat && (
        <NewChatDrawer
          currentUserId={user?.id}
          onClose={() => setShowNewChat(false)}
          onConversationCreated={handleConversationCreated}
        />
      )}
    </>
  )
}
