import { useState, useEffect } from 'react'
import { useAuth } from '../contexts/AuthContext'
import { getUserEntries, deleteEntry, updateEntry, type JournalEntry } from '../lib/api'
import { decryptEntry, encryptEntry } from '../lib/crypto'
import { formatIST, getISTDateComponents } from '../lib/timezone'
import BottomNav from '../components/BottomNav'
import { useOnboardingTour, hasPendingTourStep, clearPendingTourStep } from '../hooks/useOnboardingTour'
import { PageLoader } from '../components/PageLoader'

interface DecryptedEntry extends JournalEntry {
  decryptedTitle?: string
  decryptedContent?: string
  decryptError?: string
}

export default function HistoryPage() {
  const { user, userId, secretKey, loading } = useAuth()
  const [currentMonth, setCurrentMonth] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState(new Date())
  const [entries, setEntries] = useState<DecryptedEntry[]>([])
  const [loadingEntries, setLoadingEntries] = useState(false)
  const [selectedEntry, setSelectedEntry] = useState<DecryptedEntry | null>(null)
  const [entryToDelete, setEntryToDelete] = useState<DecryptedEntry | null>(null)
  const [deleting, setDeleting] = useState(false)
  const [entryToEdit, setEntryToEdit] = useState<DecryptedEntry | null>(null)
  const [editTitle, setEditTitle] = useState('')
  const [editContent, setEditContent] = useState('')
  const [saving, setSaving] = useState(false)

  const { continueTourOnHistory } = useOnboardingTour()

  // Continue onboarding tour if navigated here from the home page tour
  useEffect(() => {
    if (hasPendingTourStep() === 'history') {
      clearPendingTourStep()
      continueTourOnHistory()
    }
  }, [])

  // Fetch entries on mount and when userId changes
  useEffect(() => {
    if (!user || !userId) return

    const fetchEntries = async () => {
      setLoadingEntries(true)
      try {
        const token = await user.getIdToken()
        const response = await getUserEntries(userId, token, 100, 0)
        
        // Decrypt entries if they are encrypted
        const decryptedEntries: DecryptedEntry[] = await Promise.all(
          response.entries.map(async (entry) => {
            if (entry.encryption?.encrypted && entry.encryption?.ciphertext && entry.encryption?.nonce) {
              // Entry is encrypted, try to decrypt
              if (!secretKey) {
                return {
                  ...entry,
                  decryptError: 'Encryption key not available',
                  decryptedTitle: '[Encrypted]',
                }
              }

              try {
                const decrypted = await decryptEntry(
                  entry.encryption.ciphertext,
                  entry.encryption.nonce,
                  secretKey
                )

                // Split decrypted content: first line is title, rest is content
                const lines = decrypted.split('\n\n')
                const decryptedTitle = lines[0]
                const decryptedContent = lines.slice(1).join('\n\n')

                return {
                  ...entry,
                  decryptedTitle,
                  decryptedContent,
                }
              } catch (error) {
                console.error(`Failed to decrypt entry ${entry.id}:`, error)
                return {
                  ...entry,
                  decryptError: 'Failed to decrypt entry',
                  decryptedTitle: '[Decryption Failed]',
                }
              }
            } else {
              // Entry is not encrypted, use plaintext
              return {
                ...entry,
                decryptedTitle: entry.title || '[Untitled]',
                decryptedContent: entry.content || '',
              }
            }
          })
        )

        setEntries(decryptedEntries)
      } catch (error) {
        console.error('Error fetching entries:', error)
      } finally {
        setLoadingEntries(false)
      }
    }

    fetchEntries()
  }, [user, userId, secretKey])

  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    const daysInMonth = lastDay.getDate()
    const startingDayOfWeek = firstDay.getDay()

    return { daysInMonth, startingDayOfWeek }
  }

  const hasEntryOnDate = (day: number) => {
    return entries.some((entry) => {
      const components = getISTDateComponents(entry.createdAt)
      return (
        components.date === day &&
        components.month === currentMonth.getMonth() &&
        components.year === currentMonth.getFullYear()
      )
    })
  }

  const isToday = (day: number) => {
    const today = new Date()
    return (
      day === today.getDate() &&
      currentMonth.getMonth() === today.getMonth() &&
      currentMonth.getFullYear() === today.getFullYear()
    )
  }

  const formatDate = (date: string) => {
    return formatIST(date, 'date')
  }

  const formatTime = (date: string) => {
    return formatIST(date, 'time')
  }

  const { daysInMonth, startingDayOfWeek } = getDaysInMonth(currentMonth)
  const monthName = currentMonth.toLocaleDateString('en-US', {
    month: 'long',
    year: 'numeric',
  })

  const previousMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1))
  }

  const nextMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1))
  }

  // Get entries for selected date (in IST)
  const selectedDateEntries = entries.filter((entry) => {
    const components = getISTDateComponents(entry.createdAt)
    return (
      components.date === selectedDate.getDate() &&
      components.month === selectedDate.getMonth() &&
      components.year === selectedDate.getFullYear()
    )
  })

  const isDateSelected = (day: number) => {
    return (
      day === selectedDate.getDate() &&
      currentMonth.getMonth() === selectedDate.getMonth() &&
      currentMonth.getFullYear() === selectedDate.getFullYear()
    )
  }

  const handleDateClick = (day: number) => {
    setSelectedDate(new Date(currentMonth.getFullYear(), currentMonth.getMonth(), day))
  }

  const isEntryFromToday = (createdAt: string): boolean => {
    const nowIST = new Date(new Date().getTime() + 5.5 * 60 * 60 * 1000)
    const components = getISTDateComponents(createdAt)
    return (
      components.year === nowIST.getUTCFullYear() &&
      components.month === nowIST.getUTCMonth() &&
      components.date === nowIST.getUTCDate()
    )
  }

  const openEditModal = (entry: DecryptedEntry) => {
    setEntryToEdit(entry)
    setEditTitle(entry.decryptedTitle || '')
    setEditContent(entry.decryptedContent || '')
  }

  const handleEditSave = async () => {
    if (!entryToEdit || !user || !userId || !secretKey) return
    setSaving(true)
    try {
      const token = await user.getIdToken()
      const combined = `${editTitle.trim()}\n\n${editContent.trim()}`
      const { ciphertext, nonce } = await encryptEntry(combined, secretKey)

      await updateEntry(userId, entryToEdit.id, {
        title: undefined,
        content: undefined,
        encryption: {
          encrypted: true,
          ciphertext,
          nonce,
          algorithm: 'XSalsa20-Poly1305',
        },
      }, token)

      const updatedEntry: DecryptedEntry = {
        ...entryToEdit,
        encryption: { encrypted: true, ciphertext, nonce, algorithm: 'XSalsa20-Poly1305' },
        decryptedTitle: editTitle.trim(),
        decryptedContent: editContent.trim(),
      }

      setEntries((prev) => prev.map((e) => e.id === entryToEdit.id ? updatedEntry : e))
      if (selectedEntry?.id === entryToEdit.id) setSelectedEntry(updatedEntry)
      setEntryToEdit(null)
    } catch (error) {
      console.error('Failed to update entry:', error)
    } finally {
      setSaving(false)
    }
  }

  const handleDeleteConfirm = async () => {
    if (!entryToDelete || !user || !userId) return
    setDeleting(true)
    try {
      const token = await user.getIdToken()
      await deleteEntry(userId, entryToDelete.id, token)
      setEntries((prev) => prev.filter((e) => e.id !== entryToDelete.id))
      if (selectedEntry?.id === entryToDelete.id) setSelectedEntry(null)
    } catch (error) {
      console.error('Failed to delete entry:', error)
    } finally {
      setDeleting(false)
      setEntryToDelete(null)
    }
  }

  if (loading) {
    return <PageLoader />
  }

  return (
    <div className="history-page">
      <header className="history-header">
        <div className="history-header-text">
          <h1>History</h1>
          <p className="history-subtitle">Your past reflections</p>
        </div>
        {/* <button type="button" className="history-search-btn" title="Search entries">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="11" cy="11" r="8"></circle>
            <path d="m21 21-4.35-4.35"></path>
          </svg>
        </button> */}
      </header>

      <main className="history-container">
        <div id="tour-calendar" className="calendar-card">
          <div className="calendar-header">
            <h2 className="calendar-month">{monthName}</h2>
            <div className="calendar-nav">
              <button type="button" onClick={previousMonth} className="calendar-nav-btn" title="Previous month">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="15 18 9 12 15 6"></polyline>
                </svg>
              </button>
              <button type="button" onClick={nextMonth} className="calendar-nav-btn" title="Next month">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="9 18 15 12 9 6"></polyline>
                </svg>
              </button>
            </div>
          </div>

          <div className="calendar-grid">
            <div className="calendar-weekday">S</div>
            <div className="calendar-weekday">M</div>
            <div className="calendar-weekday">T</div>
            <div className="calendar-weekday">W</div>
            <div className="calendar-weekday">T</div>
            <div className="calendar-weekday">F</div>
            <div className="calendar-weekday">S</div>

            {Array.from({ length: startingDayOfWeek }).map((_, i) => (
              <div key={`empty-${i}`} className="calendar-day calendar-day-empty"></div>
            ))}

            {Array.from({ length: daysInMonth }).map((_, i) => {
              const day = i + 1
              const hasEntry = hasEntryOnDate(day)
              const isTodayDate = isToday(day)
              const isSelected = isDateSelected(day)

              return (
                <button
                  key={day}
                  type="button"
                  className={`calendar-day ${hasEntry ? 'calendar-day-has-entry' : ''} ${isTodayDate ? 'calendar-day-today' : ''} ${isSelected ? 'calendar-day-selected' : ''}`}
                  onClick={() => handleDateClick(day)}
                >
                  {day}
                </button>
              )
            })}
          </div>
        </div>

        <section id="tour-entries-list" className="recent-entries">
          <h3 className="recent-entries-title">
            {selectedDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).toUpperCase()}
          </h3>

          {loadingEntries ? (
            <PageLoader transparent />
          ) : (
            <div className="entries-list">
              {selectedDateEntries.length === 0 ? (
                <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem', textAlign: 'center', padding: '1.5rem 0', fontFamily: '"Sniglet", system-ui' }}>
                  No entries for this day yet. Start writing!
                </p>
              ) : (
                selectedDateEntries.map((entry) => (
                  <div
                    key={entry.id}
                    className="entry-card"
                    role="button"
                    tabIndex={0}
                    onClick={() => setSelectedEntry(entry)}
                    onKeyDown={(e) => e.key === 'Enter' && setSelectedEntry(entry)}
                  >
                    <div className="entry-header">
                      <span className="entry-date">{formatDate(entry.createdAt)}</span>
                      <div className="entry-header-right">
                        <span className="entry-time">{formatTime(entry.createdAt)}</span>
                        {isEntryFromToday(entry.createdAt) && (
                          <button
                            type="button"
                            className="entry-edit-btn"
                            title="Edit entry"
                            onClick={(e) => { e.stopPropagation(); openEditModal(entry) }}
                          >
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                            </svg>
                          </button>
                        )}
                        <button
                          type="button"
                          className="entry-delete-btn"
                          title="Delete entry"
                          onClick={(e) => { e.stopPropagation(); setEntryToDelete(entry) }}
                        >
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="3 6 5 6 21 6" />
                            <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
                            <path d="M10 11v6M14 11v6" />
                            <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
                          </svg>
                        </button>
                      </div>
                    </div>
                    <h4 className="entry-title">{entry.decryptedTitle || entry.title || '[Untitled]'}</h4>
                    {entry.decryptedContent && (
                      <p className="entry-preview">{entry.decryptedContent}</p>
                    )}
                  </div>
                ))
              )}
            </div>
          )}
        </section>
      </main>

      {/* Entry Detail Modal */}
      {selectedEntry && (
        <div
          className="entry-modal-overlay"
          onClick={(e) => {
            if (e.target === e.currentTarget) setSelectedEntry(null)
          }}
        >
          <div className="entry-modal">
            <div className="entry-modal-header">
              <div className="entry-modal-meta">
                <span className="entry-modal-date">{formatDate(selectedEntry.createdAt)}</span>
                <span className="entry-modal-time">{formatTime(selectedEntry.createdAt)}</span>
              </div>
              <div className="entry-modal-actions">
                {isEntryFromToday(selectedEntry.createdAt) && (
                  <button
                    type="button"
                    className="entry-modal-edit"
                    onClick={() => { setSelectedEntry(null); openEditModal(selectedEntry) }}
                    title="Edit entry"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                    </svg>
                  </button>
                )}
                <button
                  type="button"
                  className="entry-modal-close"
                  onClick={() => setSelectedEntry(null)}
                  title="Close"
                >
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </svg>
                </button>
              </div>
            </div>

            <h2 className="entry-modal-title">
              {selectedEntry.decryptedTitle || selectedEntry.title || '[Untitled]'}
            </h2>

            {selectedEntry.decryptError ? (
              <div className="entry-modal-error">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                  <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
                {selectedEntry.decryptError}
              </div>
            ) : (
              <div className="entry-modal-content">
                {selectedEntry.decryptedContent
                  ? selectedEntry.decryptedContent.split('\n').map((line, i) => (
                      <p key={i}>{line || '\u00A0'}</p>
                    ))
                  : <p className="entry-modal-empty">No content</p>
                }
              </div>
            )}

            {selectedEntry.encryption?.encrypted && (
              <div className="entry-modal-badge">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                  <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
                End-to-end Encrypted
              </div>
            )}
          </div>
        </div>
      )}

      {/* Edit Entry Modal */}
      {entryToEdit && (
        <div
          className="entry-modal-overlay"
          onClick={(e) => {
            if (e.target === e.currentTarget && !saving) setEntryToEdit(null)
          }}
        >
          <div className="entry-modal edit-entry-modal">
            <div className="entry-modal-header">
              <span className="entry-modal-date">Edit Entry</span>
              <button
                type="button"
                className="entry-modal-close"
                onClick={() => setEntryToEdit(null)}
                disabled={saving}
                title="Close"
              >
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="18" y1="6" x2="6" y2="18" />
                  <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>
            <div className="edit-entry-fields">
              <input
                className="edit-entry-title-input"
                type="text"
                placeholder="Title"
                value={editTitle}
                onChange={(e) => setEditTitle(e.target.value)}
                disabled={saving}
                maxLength={200}
              />
              <textarea
                className="edit-entry-content-input"
                placeholder="What are you grateful for today?"
                value={editContent}
                onChange={(e) => setEditContent(e.target.value)}
                disabled={saving}
                rows={8}
              />
            </div>
            <div className="edit-entry-actions">
              <button
                type="button"
                className="delete-confirm-cancel"
                onClick={() => setEntryToEdit(null)}
                disabled={saving}
              >
                Cancel
              </button>
              <button
                type="button"
                className="edit-entry-save"
                onClick={handleEditSave}
                disabled={saving || (!editTitle.trim() && !editContent.trim())}
              >
                {saving ? 'Saving…' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {entryToDelete && (
        <div
          className="entry-modal-overlay"
          onClick={(e) => {
            if (e.target === e.currentTarget && !deleting) setEntryToDelete(null)
          }}
        >
          <div className="entry-modal delete-confirm-modal">
            <div className="delete-confirm-icon">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="3 6 5 6 21 6" />
                <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
                <path d="M10 11v6M14 11v6" />
                <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
              </svg>
            </div>
            <h2 className="delete-confirm-title">Delete entry?</h2>
            <p className="delete-confirm-body">
              "{entryToDelete.decryptedTitle || entryToDelete.title || 'Untitled'}" will be permanently deleted and cannot be recovered.
            </p>
            <div className="delete-confirm-actions">
              <button
                type="button"
                className="delete-confirm-cancel"
                onClick={() => setEntryToDelete(null)}
                disabled={deleting}
              >
                Cancel
              </button>
              <button
                type="button"
                className="delete-confirm-delete"
                onClick={handleDeleteConfirm}
                disabled={deleting}
              >
                {deleting ? 'Deleting…' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}

      <BottomNav />
    </div>
  )
}
