'use client'

import { useEffect, useState } from 'react'
import { Plus, Pencil, Trash2, Loader2, X, Star } from 'lucide-react'
import toast from 'react-hot-toast'
import { PLAN_FEATURES } from '@/lib/constants'

function formatCurrency(amount: number | string): string {
  const num = typeof amount === 'string' ? parseFloat(amount) : amount
  return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(num)
}

interface Plan {
  id: string
  name: string
  slug: string
  description: string | null
  price: number
  yearlyPrice: number
  currency: string
  maxStores: number
  maxStaff: number
  maxMenuItems: number
  maxOrders: number
  features: string
  isActive: boolean
  isPopular: boolean
  sortOrder: number
}

const defaultForm = {
  name: '',
  description: '',
  price: 0,
  yearlyPrice: 0,
  maxStores: 1,
  maxStaff: 5,
  maxMenuItems: 50,
  maxOrders: 0,
  features: [] as string[],
  isPopular: false,
  sortOrder: 0,
}

export default function PlansPage() {
  const [plans, setPlans] = useState<Plan[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<Plan | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [saving, setSaving] = useState(false)

  const fetchPlans = async () => {
    try {
      const res = await fetch('/api/superadmin/plans')
      const data = await res.json()
      setPlans(data.plans || [])
    } catch (err) {
      toast.error('Gagal memuat paket')
    } finally {
      setLoading(false)
    }
  }

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

  const parseFeatures = (features: string): string[] => {
    try {
      const parsed = JSON.parse(features)
      return Array.isArray(parsed) ? parsed : []
    } catch {
      return []
    }
  }

  const openCreate = () => {
    setEditing(null)
    setForm(defaultForm)
    setShowModal(true)
  }

  const openEdit = (plan: Plan) => {
    setEditing(plan)
    setForm({
      name: plan.name,
      description: plan.description || '',
      price: plan.price,
      yearlyPrice: plan.yearlyPrice,
      maxStores: plan.maxStores,
      maxStaff: plan.maxStaff,
      maxMenuItems: plan.maxMenuItems,
      maxOrders: plan.maxOrders,
      features: parseFeatures(plan.features),
      isPopular: plan.isPopular,
      sortOrder: plan.sortOrder,
    })
    setShowModal(true)
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    try {
      const url = editing ? `/api/superadmin/plans/${editing.id}` : '/api/superadmin/plans'
      const method = editing ? 'PUT' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error)
      }
      toast.success(editing ? 'Paket berhasil diupdate' : 'Paket berhasil ditambahkan')
      setShowModal(false)
      setEditing(null)
      setForm(defaultForm)
      fetchPlans()
    } catch (err: any) {
      toast.error(err.message || 'Gagal menyimpan paket')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (plan: Plan) => {
    if (!confirm(`Nonaktifkan paket "${plan.name}"?`)) return
    try {
      const res = await fetch(`/api/superadmin/plans/${plan.id}`, { method: 'DELETE' })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error)
      }
      toast.success('Paket berhasil dinonaktifkan')
      fetchPlans()
    } catch (err: any) {
      toast.error(err.message || 'Gagal menonaktifkan paket')
    }
  }

  const toggleFeature = (featureKey: string) => {
    setForm(prev => ({
      ...prev,
      features: prev.features.includes(featureKey)
        ? prev.features.filter(f => f !== featureKey)
        : [...prev.features, featureKey],
    }))
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Paket Langganan</h1>
          <p className="text-gray-600 mt-1">Kelola paket langganan platform.</p>
        </div>
        <button onClick={openCreate} className="btn-primary text-sm flex items-center gap-1">
          <Plus className="w-4 h-4" /> Tambah Paket
        </button>
      </div>

      <div className="card">
        {plans.length === 0 ? (
          <p className="text-gray-500 text-center py-8">Belum ada paket langganan</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Nama</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Harga/bulan</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Harga/tahun</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Maks Cabang</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Maks Staff</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Maks Menu</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Fitur</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Aksi</th>
                </tr>
              </thead>
              <tbody>
                {plans.map((plan) => {
                  const features = parseFeatures(plan.features)
                  return (
                    <tr key={plan.id} className="border-b border-gray-100 hover:bg-gray-50">
                      <td className="py-3 px-3">
                        <div className="flex items-center gap-1">
                          <span className="font-medium text-gray-900">{plan.name}</span>
                          {plan.isPopular && (
                            <Star className="w-4 h-4 text-yellow-500 fill-yellow-500" />
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-3 text-gray-700">{formatCurrency(plan.price)}</td>
                      <td className="py-3 px-3 text-gray-700">{formatCurrency(plan.yearlyPrice)}</td>
                      <td className="py-3 px-3 text-gray-700">{plan.maxStores}</td>
                      <td className="py-3 px-3 text-gray-700">{plan.maxStaff}</td>
                      <td className="py-3 px-3 text-gray-700">{plan.maxMenuItems}</td>
                      <td className="py-3 px-3">
                        <div className="flex flex-wrap gap-1">
                          {features.map((f) => (
                            <span key={f} className="badge bg-gray-100 text-gray-700 text-xs">
                              {PLAN_FEATURES[f]?.label || f}
                            </span>
                          ))}
                          {features.length === 0 && <span className="text-gray-400">-</span>}
                        </div>
                      </td>
                      <td className="py-3 px-3">
                        <span className={`badge ${plan.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                          {plan.isActive ? 'Aktif' : 'Nonaktif'}
                        </span>
                      </td>
                      <td className="py-3 px-3">
                        <div className="flex items-center gap-1">
                          <button onClick={() => openEdit(plan)} className="btn-ghost text-xs p-1.5">
                            <Pencil className="w-4 h-4" />
                          </button>
                          <button onClick={() => handleDelete(plan)} className="btn-ghost text-xs p-1.5 text-red-500 hover:bg-red-50">
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white rounded-xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">{editing ? 'Edit Paket' : 'Tambah Paket'}</h3>
              <button onClick={() => setShowModal(false)}>
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <form onSubmit={handleSave} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Nama Paket</label>
                <input
                  type="text"
                  className="input-field"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Deskripsi</label>
                <textarea
                  className="input-field"
                  rows={3}
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Harga/bulan (IDR)</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.price}
                    onChange={(e) => setForm({ ...form, price: Number(e.target.value) })}
                    min={0}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Harga/tahun (IDR)</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.yearlyPrice}
                    onChange={(e) => setForm({ ...form, yearlyPrice: Number(e.target.value) })}
                    min={0}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Maks Cabang</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.maxStores}
                    onChange={(e) => setForm({ ...form, maxStores: Number(e.target.value) })}
                    min={1}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Maks Staff</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.maxStaff}
                    onChange={(e) => setForm({ ...form, maxStaff: Number(e.target.value) })}
                    min={1}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Maks Menu Items</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.maxMenuItems}
                    onChange={(e) => setForm({ ...form, maxMenuItems: Number(e.target.value) })}
                    min={1}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Maks Orders (0 = unlimited)</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.maxOrders}
                    onChange={(e) => setForm({ ...form, maxOrders: Number(e.target.value) })}
                    min={0}
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Fitur</label>
                <div className="grid grid-cols-2 gap-2">
                  {Object.entries(PLAN_FEATURES).map(([key, feat]) => (
                    <label key={key} className="flex items-center gap-2 text-sm cursor-pointer">
                      <input
                        type="checkbox"
                        checked={form.features.includes(key)}
                        onChange={() => toggleFeature(key)}
                        className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                      />
                      {feat.label}
                    </label>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Urutan Tampil</label>
                  <input
                    type="number"
                    className="input-field"
                    value={form.sortOrder}
                    onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) })}
                    min={0}
                  />
                </div>
                <div className="flex items-end pb-1">
                  <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input
                      type="checkbox"
                      checked={form.isPopular}
                      onChange={(e) => setForm({ ...form, isPopular: e.target.checked })}
                      className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                    />
                    Tandai sebagai Populer
                  </label>
                </div>
              </div>
              <div className="flex gap-2 justify-end pt-2">
                <button type="button" onClick={() => setShowModal(false)} className="btn-secondary">
                  Batal
                </button>
                <button type="submit" disabled={saving} className="btn-primary flex items-center gap-2">
                  {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                  {saving ? 'Menyimpan...' : 'Simpan'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
