'use client'

import { useEffect, useState } from 'react'
import { apiFetch } from '@/lib/api'

type NotificationItem = {
  id: string
  type: string
  title: string
  body: string
  readAt: string | null
  createdAt: string
}

type PreferenceItem = {
  notificationType: string
  channel: string
  enabled: boolean
}

const COMPANY_EVENTS = [
  'NEW_RESERVATION',
  'RESERVATION_CANCELLED',
  'PAYMENT_RECEIVED',
  'SUBSCRIPTION_TRIAL_ENDING',
  'MAINTENANCE_DUE',
  'OFFER_EXPIRING',
]

const COMPANY_CHANNELS = ['EMAIL', 'SMS', 'WHATSAPP', 'IN_APP', 'PUSH']

export default function DashboardNotificationsPage() {
  const [notifications, setNotifications] = useState<NotificationItem[]>([])
  const [preferences, setPreferences] = useState<Record<string, boolean>>({})
  const [activeTab, setActiveTab] = useState<'inbox' | 'preferences'>('inbox')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function load() {
    setLoading(true)
    setError(null)
    try {
      const [notificationData, preferenceData] = await Promise.all([
        apiFetch<NotificationItem[]>('/notifications/company'),
        apiFetch<PreferenceItem[]>('/notifications/company/preferences'),
      ])
      setNotifications(notificationData)
      const mapped = Object.fromEntries(
        preferenceData.map((item) => [`${item.notificationType}:${item.channel}`, item.enabled]),
      )
      setPreferences(mapped)
    } catch (err: any) {
      setError(err.message ?? 'Failed to load notifications')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  async function markRead(id: string) {
    await apiFetch(`/notifications/company/${id}/read`, { method: 'POST' })
    setNotifications((current) =>
      current.map((item) => (item.id === id ? { ...item, readAt: new Date().toISOString() } : item)),
    )
  }

  async function markAllRead() {
    await apiFetch('/notifications/company/read-all', { method: 'POST' })
    setNotifications((current) => current.map((item) => ({ ...item, readAt: item.readAt ?? new Date().toISOString() })))
  }

  async function savePreferences() {
    setSaving(true)
    setError(null)
    try {
      const body = Object.entries(preferences).map(([key, enabled]) => {
        const [notificationType, channel] = key.split(':')
        return { notificationType, channel, enabled }
      })
      await apiFetch('/notifications/company/preferences', {
        method: 'PATCH',
        body: JSON.stringify(body),
      })
    } catch (err: any) {
      setError(err.message ?? 'Failed to save preferences')
    } finally {
      setSaving(false)
    }
  }

  function preferenceValue(notificationType: string, channel: string) {
    return preferences[`${notificationType}:${channel}`] ?? true
  }

  function setPreference(notificationType: string, channel: string, enabled: boolean) {
    setPreferences((current) => ({
      ...current,
      [`${notificationType}:${channel}`]: enabled,
    }))
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-slate-900">Notifications</h1>
          <p className="mt-1 text-sm text-slate-500">Track in-app alerts and control delivery preferences for your team account.</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setActiveTab('inbox')}
            className={activeTab === 'inbox' ? 'btn-primary' : 'btn-secondary'}
          >
            Inbox
          </button>
          <button
            type="button"
            onClick={() => setActiveTab('preferences')}
            className={activeTab === 'preferences' ? 'btn-primary' : 'btn-secondary'}
          >
            Preferences
          </button>
        </div>
      </div>

      {error ? <div className="card p-4 text-sm text-red-600">{error}</div> : null}

      {activeTab === 'inbox' ? (
        <div className="space-y-4">
          <div className="flex justify-end">
            <button type="button" onClick={markAllRead} className="btn-secondary">
              Mark all as read
            </button>
          </div>
          {loading ? <div className="card p-6 text-sm text-slate-500">Loading notifications…</div> : null}
          {!loading && notifications.length === 0 ? <div className="card p-6 text-sm text-slate-500">No notifications yet.</div> : null}
          {!loading
            ? notifications.map((notification) => (
                <article key={notification.id} className="card p-6">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">
                        {notification.type.replaceAll('_', ' ')}
                      </p>
                      <h2 className="mt-2 text-lg font-semibold text-slate-900">{notification.title}</h2>
                    </div>
                    {notification.readAt ? (
                      <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">Read</span>
                    ) : (
                      <button type="button" onClick={() => markRead(notification.id)} className="btn-secondary">
                        Mark as read
                      </button>
                    )}
                  </div>
                  <p className="mt-3 text-sm leading-7 text-slate-600">{notification.body}</p>
                  <p className="mt-4 text-xs text-slate-400">{new Date(notification.createdAt).toLocaleString()}</p>
                </article>
              ))
            : null}
        </div>
      ) : (
        <div className="card overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead className="bg-slate-50">
                <tr>
                  <th className="px-4 py-3 text-left font-semibold text-slate-600">Event</th>
                  {COMPANY_CHANNELS.map((channel) => (
                    <th key={channel} className="px-4 py-3 text-center font-semibold text-slate-600">
                      {channel.replace('_', ' ')}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {COMPANY_EVENTS.map((eventName) => (
                  <tr key={eventName} className="border-t border-slate-100">
                    <td className="px-4 py-3 font-medium text-slate-900">{eventName.replaceAll('_', ' ')}</td>
                    {COMPANY_CHANNELS.map((channel) => (
                      <td key={`${eventName}-${channel}`} className="px-4 py-3 text-center">
                        <input
                          type="checkbox"
                          checked={preferenceValue(eventName, channel)}
                          onChange={(event) => setPreference(eventName, channel, event.target.checked)}
                          className="h-4 w-4 rounded border-slate-300 text-blue-600"
                        />
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="flex justify-end border-t border-slate-100 p-4">
            <button type="button" onClick={savePreferences} disabled={saving} className="btn-primary">
              {saving ? 'Saving…' : 'Save preferences'}
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
