'use client'

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

type Voucher = {
  id: string
  code: string
  discountType: 'PERCENTAGE' | 'FIXED'
  discountValue: number
  maxUses: number
  usedCount: number
  isActive: boolean
  expiresAt: string | null
  createdAt: string
}

export default function VouchersAdmin() {
  const [vouchers, setVouchers] = useState<Voucher[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [formData, setFormData] = useState({
    code: '',
    discountType: 'PERCENTAGE',
    discountValue: '',
    maxUses: '100',
    expiresAt: ''
  })
  const [isSubmitting, setIsSubmitting] = useState(false)
  const router = useRouter()

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

  const fetchVouchers = async () => {
    try {
      const res = await fetch('/api/vouchers')
      if (res.ok) {
        setVouchers(await res.json())
      }
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    try {
      const res = await fetch('/api/vouchers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          discountValue: Number(formData.discountValue),
          expiresAt: formData.expiresAt || null
        })
      })

      if (res.ok) {
        setShowModal(false)
        setFormData({ code: '', discountType: 'PERCENTAGE', discountValue: '', maxUses: '100', expiresAt: '' })
        fetchVouchers()
        alert('Voucher berhasil ditambahkan')
      } else {
        const err = await res.json()
        alert(`Gagal: ${err.error}`)
      }
    } catch (error) {
      alert('Terjadi kesalahan')
    } finally {
      setIsSubmitting(false)
    }
  }

  const toggleStatus = async (v: Voucher) => {
    try {
      await fetch('/api/vouchers', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...v, isActive: !v.isActive })
      })
      fetchVouchers()
    } catch (error) {
      alert('Gagal mengubah status')
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Yakin ingin menghapus voucher ini?')) return
    try {
      await fetch(`/api/vouchers?id=${id}`, { method: 'DELETE' })
      fetchVouchers()
    } catch (error) {
      alert('Gagal menghapus')
    }
  }

  if (loading) return <div style={{ color: '#fff', padding: '24px' }}>Loading...</div>

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h1 style={{ fontSize: '24px', fontWeight: 'bold', color: '#f1f5f9' }}>Voucher & Promo</h1>
          <p style={{ color: '#94a3b8' }}>Kelola kode diskon untuk pelanggan</p>
        </div>
        <button 
          onClick={() => setShowModal(true)}
          className="btn btn-primary"
          style={{ padding: '10px 20px' }}
        >
          + Tambah Voucher
        </button>
      </div>

      <div className="card" style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', color: '#f1f5f9' }}>
          <thead>
            <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.1)', textAlign: 'left' }}>
              <th style={{ padding: '16px' }}>KODE</th>
              <th style={{ padding: '16px' }}>DISKON</th>
              <th style={{ padding: '16px' }}>TERPAKAI</th>
              <th style={{ padding: '16px' }}>KADALUARSA</th>
              <th style={{ padding: '16px' }}>STATUS</th>
              <th style={{ padding: '16px' }}>AKSI</th>
            </tr>
          </thead>
          <tbody>
            {vouchers.map(v => (
              <tr key={v.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                <td style={{ padding: '16px', fontWeight: 'bold', color: '#3b82f6' }}>{v.code}</td>
                <td style={{ padding: '16px' }}>
                  {v.discountType === 'PERCENTAGE' 
                    ? `${v.discountValue}%` 
                    : `Rp ${Number(v.discountValue).toLocaleString('id-ID')}`}
                </td>
                <td style={{ padding: '16px' }}>
                  <span style={{ 
                    color: v.usedCount >= v.maxUses ? '#ef4444' : '#10b981' 
                  }}>
                    {v.usedCount} / {v.maxUses === 0 ? '∞' : v.maxUses}
                  </span>
                </td>
                <td style={{ padding: '16px', color: '#94a3b8' }}>
                  {v.expiresAt ? new Date(v.expiresAt).toLocaleDateString('id-ID') : 'Selamanya'}
                </td>
                <td style={{ padding: '16px' }}>
                  <button 
                    onClick={() => toggleStatus(v)}
                    style={{
                      background: v.isActive ? '#10b98120' : '#ef444420',
                      color: v.isActive ? '#10b981' : '#ef4444',
                      border: `1px solid ${v.isActive ? '#10b98150' : '#ef444450'}`,
                      padding: '4px 12px',
                      borderRadius: '100px',
                      fontSize: '12px',
                      fontWeight: 600,
                      cursor: 'pointer'
                    }}
                  >
                    {v.isActive ? 'Aktif' : 'Nonaktif'}
                  </button>
                </td>
                <td style={{ padding: '16px' }}>
                  <button 
                    onClick={() => handleDelete(v.id)}
                    style={{ background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', fontSize: '18px' }}
                    title="Hapus"
                  >
                    🗑️
                  </button>
                </td>
              </tr>
            ))}
            {vouchers.length === 0 && (
              <tr>
                <td colSpan={6} style={{ padding: '32px', textAlign: 'center', color: '#64748b' }}>
                  Belum ada voucher
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {showModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: '24px' }}>
          <div className="card" style={{ width: '100%', maxWidth: '500px', padding: '32px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
              <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#fff' }}>Tambah Voucher</h2>
              <button onClick={() => setShowModal(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: '20px' }}>✕</button>
            </div>

            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <div>
                <label style={{ display: 'block', marginBottom: '8px', color: '#94a3b8', fontSize: '14px' }}>Kode Voucher *</label>
                <input 
                  type="text" 
                  className="input" 
                  required
                  placeholder="Contoh: PROMO2026"
                  value={formData.code}
                  onChange={e => setFormData({...formData, code: e.target.value.toUpperCase()})}
                  style={{ textTransform: 'uppercase' }}
                />
              </div>

              <div style={{ display: 'flex', gap: '16px' }}>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', marginBottom: '8px', color: '#94a3b8', fontSize: '14px' }}>Tipe Diskon *</label>
                  <select 
                    className="input"
                    value={formData.discountType}
                    onChange={e => setFormData({...formData, discountType: e.target.value as any})}
                  >
                    <option value="PERCENTAGE">Persentase (%)</option>
                    <option value="FIXED">Nominal Tetap (Rp)</option>
                  </select>
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', marginBottom: '8px', color: '#94a3b8', fontSize: '14px' }}>Nilai Diskon *</label>
                  <input 
                    type="number" 
                    className="input" 
                    required
                    placeholder={formData.discountType === 'PERCENTAGE' ? "Contoh: 10" : "Contoh: 5000"}
                    value={formData.discountValue}
                    onChange={e => setFormData({...formData, discountValue: e.target.value})}
                  />
                </div>
              </div>

              <div>
                <label style={{ display: 'block', marginBottom: '8px', color: '#94a3b8', fontSize: '14px' }}>Batas Klaim (Max Uses)</label>
                <input 
                  type="number" 
                  className="input" 
                  placeholder="0 untuk tanpa batas"
                  value={formData.maxUses}
                  onChange={e => setFormData({...formData, maxUses: e.target.value})}
                />
              </div>

              <div>
                <label style={{ display: 'block', marginBottom: '8px', color: '#94a3b8', fontSize: '14px' }}>Tanggal Kadaluarsa (Opsional)</label>
                <input 
                  type="date" 
                  className="input" 
                  value={formData.expiresAt}
                  onChange={e => setFormData({...formData, expiresAt: e.target.value})}
                />
              </div>

              <button 
                type="submit" 
                className="btn btn-primary" 
                style={{ padding: '14px', marginTop: '8px' }}
                disabled={isSubmitting}
              >
                {isSubmitting ? 'Menyimpan...' : 'Simpan Voucher'}
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
