'use client'

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

interface Tier {
  id: string
  tierNumber: number
  name: string
  price: number
  priceMax: number | null
  description: string | null
  isApplicationOnly: boolean
  hardCap: number | null
  paymentLink: string | null
  paymentLinkStatus: string
  subscriberCount: number
}

export default function TiersPage() {
  const [tiers, setTiers] = useState<Tier[]>([])
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState<string | null>(null)
  const [editData, setEditData] = useState<Partial<Tier>>({})
  const router = useRouter()

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

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

  const saveTier = async (id: string) => {
    await fetch('/api/tiers', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, ...editData }) })
    setEditing(null); setEditData({})
    fetchTiers()
  }

  const mrr = tiers.reduce((s, t) => s + t.subscriberCount * t.price, 0)
  const totalSubs = tiers.reduce((s, t) => s + t.subscriberCount, 0)

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

  const tierColors = ['bg-slate-500/10 border-slate-500/20', 'bg-blue-500/10 border-blue-500/20', 'bg-purple-500/10 border-purple-500/20', 'bg-amber-500/10 border-amber-500/20', 'bg-rose-500/10 border-rose-500/20']

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-brand-text">Subscription Tiers</h1>
        <p className="text-brand-muted text-sm mt-1">Manage tiers, subscriber counts, and payment links</p>
      </div>

      {/* Summary */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-green-400/10 border border-green-400/20 rounded-xl p-5">
          <p className="text-xs font-medium text-brand-muted uppercase">MRR</p>
          <p className="text-3xl font-bold text-green-400 mt-1">${mrr.toLocaleString()}</p>
        </div>
        <div className="bg-brand-accent/10 border border-brand-accent/20 rounded-xl p-5">
          <p className="text-xs font-medium text-brand-muted uppercase">Total Subscribers</p>
          <p className="text-3xl font-bold text-brand-accent mt-1">{totalSubs}</p>
        </div>
        <div className="bg-purple-400/10 border border-purple-400/20 rounded-xl p-5">
          <p className="text-xs font-medium text-brand-muted uppercase">Payment Links</p>
          <p className="text-3xl font-bold text-purple-400 mt-1">{tiers.filter(t => t.paymentLinkStatus === 'collected').length}/{tiers.length}</p>
          <p className="text-xs text-brand-muted mt-1">collected</p>
        </div>
      </div>

      {/* Tier Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
        {tiers.map((tier, i) => (
          <div key={tier.id} className={`${tierColors[i] || tierColors[0]} border rounded-xl p-6`}>
            <div className="flex items-start justify-between mb-4">
              <div>
                <p className="text-xs text-brand-muted uppercase tracking-wider">Tier {tier.tierNumber}</p>
                <h3 className="text-lg font-bold text-brand-text mt-1">{tier.name}</h3>
                <p className="text-sm text-brand-muted mt-0.5">
                  {tier.price === 0 ? 'Free' : tier.priceMax ? `$${tier.price}–$${tier.priceMax}/mo` : `$${tier.price}/mo`}
                </p>
              </div>
              <button onClick={() => { setEditing(editing === tier.id ? null : tier.id); setEditData({ subscriberCount: tier.subscriberCount, paymentLink: tier.paymentLink || '', paymentLinkStatus: tier.paymentLinkStatus }) }} className="text-xs text-brand-accent hover:text-brand-accent-hover transition-colors">
                {editing === tier.id ? 'Cancel' : 'Edit'}
              </button>
            </div>

            {tier.description && <p className="text-xs text-brand-muted mb-4">{tier.description}</p>}

            {tier.isApplicationOnly && (
              <div className="bg-rose-500/10 text-rose-400 text-xs font-medium px-2 py-1 rounded-md inline-block mb-3">Application Only{tier.hardCap ? ` • Cap: ${tier.hardCap}` : ''}</div>
            )}

            {editing === tier.id ? (
              <div className="space-y-3 mt-4 pt-4 border-t border-brand-border/50">
                <div>
                  <label className="text-xs text-brand-muted">Subscriber Count</label>
                  <input type="number" value={editData.subscriberCount || 0} onChange={e => setEditData({ ...editData, subscriberCount: 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">Payment Link</label>
                  <input type="text" value={editData.paymentLink || ''} onChange={e => setEditData({ ...editData, paymentLink: e.target.value })} placeholder="https://..." 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">Payment Link Status</label>
                  <select value={editData.paymentLinkStatus || 'not_collected'} onChange={e => setEditData({ ...editData, paymentLinkStatus: 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">
                    <option value="not_collected">Not Collected</option>
                    <option value="collected">Collected</option>
                  </select>
                </div>
                <button onClick={() => saveTier(tier.id)} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors w-full">Save</button>
              </div>
            ) : (
              <div className="mt-4 pt-4 border-t border-brand-border/50 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-brand-muted">Subscribers</span>
                  <span className="text-brand-text font-semibold">{tier.subscriberCount}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-brand-muted">Revenue</span>
                  <span className="text-green-400 font-semibold">${(tier.subscriberCount * tier.price).toLocaleString()}/mo</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-brand-muted">Payment Link</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${tier.paymentLinkStatus === 'collected' ? 'bg-green-400/10 text-green-400' : 'bg-amber-400/10 text-amber-400'}`}>
                    {tier.paymentLinkStatus === 'collected' ? '✓ Collected' : 'Needed'}
                  </span>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}
