'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

interface Metric {
  id: string
  date: string
  quowavyFollowers: number
  kevinthevpFollowers: number
  oskvlabsFollowers: number
  discordMembersFree: number
  discordMembersPaid: number
  conversionRate: number
  notes: string | null
}

export default function MetricsPage() {
  const [metrics, setMetrics] = useState<Metric[]>([])
  const [loading, setLoading] = useState(true)
  const [showAdd, setShowAdd] = useState(false)
  const [newData, setNewData] = useState({
    date: new Date().toISOString().split('T')[0],
    quowavyFollowers: 0,
    kevinthevpFollowers: 0,
    oskvlabsFollowers: 0,
    discordMembersFree: 0,
    discordMembersPaid: 0,
    conversionRate: 0,
    notes: '',
  })
  const router = useRouter()

  const fetchMetrics = () => {
    fetch('/api/metrics')
      .then(res => { if (res.status === 401) { router.push('/login'); return null } return res.json() })
      .then(d => { if (d) setMetrics(d.metrics); setLoading(false) })
  }

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

  const addMetric = async () => {
    await fetch('/api/metrics', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...newData, conversionRate: parseFloat(String(newData.conversionRate)) }) })
    setShowAdd(false)
    fetchMetrics()
  }

  if (loading) return <div className="flex items-center justify-center h-full"><div className="text-brand-muted">Loading...</div></div>

  const latest = metrics[0] || null
  const prev = metrics[1] || null

  const delta = (curr: number, previous: number) => {
    if (!previous) return null
    const diff = curr - previous
    return diff
  }

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-brand-text">Funnel Metrics</h1>
          <p className="text-brand-muted text-sm mt-1">Track Instagram followers, Discord members, and conversions</p>
        </div>
        <button onClick={() => setShowAdd(!showAdd)} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">
          + Record Metrics
        </button>
      </div>

      {/* Current Snapshot */}
      {latest && (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
          {[
            { label: '@quowavy', value: latest.quowavyFollowers, prev: prev?.quowavyFollowers, icon: '📸' },
            { label: '@kevinthevp', value: latest.kevinthevpFollowers, prev: prev?.kevinthevpFollowers, icon: '📸' },
            { label: '@oskv.labs', value: latest.oskvlabsFollowers, prev: prev?.oskvlabsFollowers, icon: '📸' },
            { label: 'Discord Free', value: latest.discordMembersFree, prev: prev?.discordMembersFree, icon: '💬' },
            { label: 'Discord Paid', value: latest.discordMembersPaid, prev: prev?.discordMembersPaid, icon: '💎' },
            { label: 'Conversion', value: latest.conversionRate, prev: prev?.conversionRate, icon: '📈', suffix: '%' },
          ].map(item => {
            const d = item.prev != null ? delta(item.value, item.prev) : null
            return (
              <div key={item.label} className="bg-brand-card border border-brand-border rounded-xl p-4">
                <p className="text-xs text-brand-muted">{item.icon} {item.label}</p>
                <p className="text-2xl font-bold text-brand-text mt-1">{item.value.toLocaleString()}{item.suffix || ''}</p>
                {d !== null && (
                  <p className={`text-xs mt-1 ${d > 0 ? 'text-green-400' : d < 0 ? 'text-red-400' : 'text-brand-muted'}`}>
                    {d > 0 ? '+' : ''}{d}{item.suffix || ''} vs prev
                  </p>
                )}
              </div>
            )
          })}
        </div>
      )}

      {/* Add Metrics Form */}
      {showAdd && (
        <div className="bg-brand-card border border-brand-border rounded-xl p-6 space-y-4">
          <h3 className="text-sm font-semibold text-brand-text">Record New Metrics</h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            <div>
              <label className="text-xs text-brand-muted">Date</label>
              <input type="date" value={newData.date} onChange={e => setNewData({ ...newData, date: e.target.value })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">@quowavy followers</label>
              <input type="number" value={newData.quowavyFollowers} onChange={e => setNewData({ ...newData, quowavyFollowers: Number(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">@kevinthevp followers</label>
              <input type="number" value={newData.kevinthevpFollowers} onChange={e => setNewData({ ...newData, kevinthevpFollowers: Number(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">@oskv.labs followers</label>
              <input type="number" value={newData.oskvlabsFollowers} onChange={e => setNewData({ ...newData, oskvlabsFollowers: Number(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">Discord Free Members</label>
              <input type="number" value={newData.discordMembersFree} onChange={e => setNewData({ ...newData, discordMembersFree: Number(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">Discord Paid Members</label>
              <input type="number" value={newData.discordMembersPaid} onChange={e => setNewData({ ...newData, discordMembersPaid: Number(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">Conversion Rate %</label>
              <input type="number" step="0.1" value={newData.conversionRate} onChange={e => setNewData({ ...newData, conversionRate: parseFloat(e.target.value) })} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 focus:outline-none focus:border-brand-accent" />
            </div>
            <div>
              <label className="text-xs text-brand-muted">Notes</label>
              <input type="text" value={newData.notes} onChange={e => setNewData({ ...newData, notes: e.target.value })} placeholder="Optional notes" className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm mt-1 placeholder-brand-muted/50 focus:outline-none focus:border-brand-accent" />
            </div>
          </div>
          <div className="flex gap-3">
            <button onClick={addMetric} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">Save</button>
            <button onClick={() => setShowAdd(false)} className="text-brand-muted hover:text-brand-text text-sm px-4 py-2 transition-colors">Cancel</button>
          </div>
        </div>
      )}

      {/* History Table */}
      <div className="bg-brand-card border border-brand-border rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-brand-border">
                <th className="text-left px-4 py-3 text-xs font-medium text-brand-muted uppercase">Date</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">@quowavy</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">@kevinthevp</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">@oskv.labs</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">Discord Free</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">Discord Paid</th>
                <th className="text-right px-4 py-3 text-xs font-medium text-brand-muted uppercase">Conv %</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-brand-muted uppercase">Notes</th>
              </tr>
            </thead>
            <tbody>
              {metrics.map(m => (
                <tr key={m.id} className="border-b border-brand-border/50 hover:bg-white/[0.02]">
                  <td className="px-4 py-3 text-brand-text">{new Date(m.date).toLocaleDateString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.quowavyFollowers.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.kevinthevpFollowers.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.oskvlabsFollowers.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.discordMembersFree.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.discordMembersPaid.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-brand-text">{m.conversionRate}%</td>
                  <td className="px-4 py-3 text-brand-muted text-xs max-w-[200px] truncate">{m.notes || '—'}</td>
                </tr>
              ))}
              {metrics.length === 0 && (
                <tr><td colSpan={8} className="px-4 py-8 text-center text-brand-muted">No metrics recorded yet</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
