"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Ticket, Plus, Trash2, Loader2, AlertCircle } from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

type Coupon = {
  id: string
  code: string
  discount: number
  active: boolean
  expiresAt: string | null
}

export default function CouponsPage() {
  const [coupons, setCoupons] = useState<Coupon[]>([])
  const [loading, setLoading] = useState(true)

  async function fetchCoupons() {
    try {
      const res = await api.get("/admin/coupons")
      setCoupons(res.data)
    } catch (error) {
      console.error("Failed to fetch coupons", error)
    } finally {
      setLoading(false)
    }
  }

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

  async function toggleStatus(id: string, currentStatus: boolean) {
    try {
      await api.patch(`/admin/coupons/${id}`, { active: !currentStatus })
      fetchCoupons()
    } catch (error) {
      console.error("Failed to toggle status", error)
    }
  }

  async function deleteCoupon(id: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to delete this promo code?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try {
      await api.delete(`/admin/coupons/${id}`)
      fetchCoupons()
    } catch (error) {
      console.error("Failed to delete coupon", error)
    }
  }

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 bg-green-100 text-green-600 rounded-xl flex items-center justify-center">
            <Ticket className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-2xl font-bold tracking-tight">Promo Codes</h1>
            <p className="text-gray-500">Manage discount codes and promotional campaigns.</p>
          </div>
        </div>
        <Link
          href="/admin/coupons/create"
          className="bg-black text-white px-4 py-2 text-sm font-medium rounded-xl hover:opacity-90 transition shadow-sm flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          Create Promo Code
        </Link>
      </div>

      <div className="bg-white rounded-3xl border shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <Loader2 className="w-8 h-8 animate-spin text-zinc-900 mb-4" />
            <span className="text-zinc-500 font-semibold text-sm">Loading promo codes...</span>
          </div>
        ) : coupons.length === 0 ? (
          <div className="text-center py-20 flex flex-col items-center">
            <Ticket className="text-zinc-300 w-16 h-16 mb-4" />
            <h3 className="text-xl font-bold text-zinc-900">No promo codes active</h3>
            <p className="text-zinc-500 mt-1 max-w-sm text-sm">
              Create your first promo code to start running discounts and campaigns.
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-zinc-100 text-xs font-black uppercase tracking-widest text-zinc-400 bg-zinc-50/50">
                  <th className="px-6 py-4">Code</th>
                  <th className="px-6 py-4">Discount</th>
                  <th className="px-6 py-4">Status</th>
                  <th className="px-6 py-4">Expires At</th>
                  <th className="px-6 py-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-100">
                {coupons.map((coupon) => (
                  <tr key={coupon.id} className="hover:bg-zinc-50 transition-colors">
                    <td className="px-6 py-4">
                      <span className="inline-flex items-center gap-2 px-3 py-1 bg-zinc-100 border border-zinc-200 rounded-lg text-sm font-mono font-bold text-zinc-900">
                        {coupon.code}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-sm font-black text-green-600">{coupon.discount}% OFF</span>
                    </td>
                    <td className="px-6 py-4">
                      <button
                        onClick={() => toggleStatus(coupon.id, coupon.active)}
                        className={`px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest transition-colors ${
                          coupon.active
                            ? "bg-green-100 text-green-700 hover:bg-green-200"
                            : "bg-zinc-100 text-zinc-500 hover:bg-zinc-200"
                        }`}
                      >
                        {coupon.active ? "Active" : "Inactive"}
                      </button>
                    </td>
                    <td className="px-6 py-4 text-sm text-zinc-500 font-medium">
                      {coupon.expiresAt ? new Date(coupon.expiresAt).toLocaleDateString() : "Never"}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <button
                        onClick={() => deleteCoupon(coupon.id)}
                        className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        title="Delete Promo Code"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  )
}
