"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import {
  FileText,
  Plus,
  Loader2,
  CheckCircle2,
  Package,
  Clock,
  ArrowRight,
  TrendingUp,
  AlertTriangle
} from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

export default function PurchasesPage() {
  const [purchases, setPurchases] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [processingId, setProcessingId] = useState<string | null>(null)

  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalRecords, setTotalRecords] = useState(0)

  async function fetchPurchases() {
    try {
      setLoading(true)
      const res = await api.get(`/admin/purchases?page=${page}&limit=20`)
      setPurchases(res.data.data || res.data)
      if (res.data.meta) {
        setTotalPages(res.data.meta.totalPages)
        setTotalRecords(res.data.meta.total)
      }
    } catch (error) {
      console.error("Failed to load purchases", error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchPurchases()
  }, [page])

  async function markAsReceived(id: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to mark this Purchase Order as received? This will permanently add the items to your live inventory stock.", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return

    try {
      setProcessingId(id)
      await api.post(`/admin/purchases/${id}/receive`)
      await fetchPurchases() // Refresh list
    } catch (error) {
      console.error("Failed to receive PO", error)
      Swal.fire({ text: "Failed to process purchase order.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setProcessingId(null)
    }
  }

  // Summary Metrics
  const activePOs = purchases.filter(p => p.status !== 'RECEIVED' && p.status !== 'CANCELLED')
  const totalSpent = purchases.reduce((sum, p) => sum + p.totalCost, 0)
  const totalItemsReceived = purchases.filter(p => p.status === 'RECEIVED').reduce((sum, p) => sum + p.items.reduce((s: number, i: any) => s + i.quantity, 0), 0)

  return (
    <div className="space-y-8 max-w-7xl mx-auto p-2">
      {/* HEADER */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <div className="p-3 bg-zinc-950 text-white rounded-2xl shadow-xl">
              <FileText size={24} />
            </div>
            <h1 className="text-3xl md:text-4xl font-black tracking-tight text-zinc-900">
              Purchase Orders
            </h1>
          </div>
          <p className="text-zinc-500 mt-2 text-sm max-w-md font-medium">
            Manage incoming stock from your suppliers, track purchase orders, and automatically replenish inventory.
          </p>
        </div>

        <Link href="/admin/purchases/create">
          <button className="flex items-center gap-2 px-6 py-3.5 bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-500 hover:to-indigo-500 text-white font-black rounded-2xl transition-all cursor-pointer shadow-lg shadow-indigo-500/25 text-xs uppercase tracking-widest shrink-0 hover:-translate-y-0.5">
            <Plus className="w-4 h-4" />
            Create New P.O.
          </button>
        </Link>
      </div>

      {/* METRICS */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-white border border-zinc-200 rounded-3xl p-6 flex items-center gap-4 shadow-sm">
          <div className="w-12 h-12 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
            <Clock className="w-6 h-6" />
          </div>
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400">Active Orders</p>
            <h3 className="text-2xl font-black text-zinc-900">{activePOs.length}</h3>
          </div>
        </div>

        <div className="bg-white border border-zinc-200 rounded-3xl p-6 flex items-center gap-4 shadow-sm">
          <div className="w-12 h-12 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
            <TrendingUp className="w-6 h-6" />
          </div>
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400">Total Expenditure</p>
            <h3 className="text-2xl font-black text-zinc-900">${totalSpent.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</h3>
          </div>
        </div>

        <div className="bg-white border border-zinc-200 rounded-3xl p-6 flex items-center gap-4 shadow-sm">
          <div className="w-12 h-12 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center shrink-0">
            <Package className="w-6 h-6" />
          </div>
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400">Total Units Received</p>
            <h3 className="text-2xl font-black text-zinc-900">{totalItemsReceived}</h3>
          </div>
        </div>
      </div>

      {/* LIST */}
      <div className="bg-white rounded-3xl border border-zinc-200 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-zinc-50 border-b border-zinc-100 text-[10px] font-black uppercase tracking-widest text-zinc-500">
                <th className="py-4 px-6">Order ID / Date</th>
                <th className="py-4 px-6">Supplier</th>
                <th className="py-4 px-6">Items Summary</th>
                <th className="py-4 px-6">Total Cost</th>
                <th className="py-4 px-6">Status</th>
                <th className="py-4 px-6 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {loading ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Loader2 className="w-8 h-8 animate-spin text-zinc-300 mx-auto mb-3" />
                    <p className="text-xs font-bold uppercase tracking-widest text-zinc-400">Loading Orders...</p>
                  </td>
                </tr>
              ) : purchases.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <FileText className="w-8 h-8 text-zinc-200 mx-auto mb-3" />
                    <p className="text-xs font-bold uppercase tracking-widest text-zinc-400">No Purchase Orders Found</p>
                  </td>
                </tr>
              ) : (
                purchases.map(po => {
                  const isReceived = po.status === 'RECEIVED'
                  const totalUnits = po.items.reduce((s: number, i: any) => s + i.quantity, 0)
                  
                  return (
                    <tr key={po.id} className="hover:bg-zinc-50/50 transition">
                      <td className="py-4 px-6">
                        <div className="font-mono text-xs font-black text-zinc-900 mb-1">
                          #{po.id.slice(-6).toUpperCase()}
                        </div>
                        <div className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider">
                          {new Date(po.createdAt).toLocaleDateString()}
                        </div>
                      </td>
                      
                      <td className="py-4 px-6">
                        <div className="text-sm font-bold text-zinc-900">{po.supplier.name}</div>
                        {po.supplier.email && <div className="text-[10px] text-zinc-500">{po.supplier.email}</div>}
                      </td>

                      <td className="py-4 px-6">
                        <div className="text-xs font-semibold text-zinc-700">
                          {po.items.length} unique variants
                        </div>
                        <div className="text-[10px] text-zinc-500 font-bold uppercase mt-0.5">
                          {totalUnits} Total Units
                        </div>
                      </td>

                      <td className="py-4 px-6 font-mono text-sm font-black text-zinc-900">
                        ${po.totalCost.toFixed(2)}
                      </td>

                      <td className="py-4 px-6">
                        <span className={`inline-flex px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest border ${
                          isReceived 
                            ? 'bg-emerald-50 text-emerald-600 border-emerald-200' 
                            : 'bg-amber-50 text-amber-600 border-amber-200'
                        }`}>
                          {po.status}
                        </span>
                      </td>

                      <td className="py-4 px-6 text-right">
                        {!isReceived && (
                          <button
                            onClick={() => markAsReceived(po.id)}
                            disabled={processingId === po.id}
                            className="inline-flex items-center gap-1.5 px-4 py-2 bg-zinc-900 hover:bg-zinc-800 text-white rounded-xl text-[10px] font-black uppercase tracking-widest transition cursor-pointer disabled:opacity-50"
                          >
                            {processingId === po.id ? (
                              <Loader2 className="w-3.5 h-3.5 animate-spin" />
                            ) : (
                              <CheckCircle2 className="w-3.5 h-3.5" />
                            )}
                            Receive Stock
                          </button>
                        )}
                        
                        {isReceived && (
                          <span className="inline-flex items-center gap-1 text-[10px] font-black text-emerald-500 uppercase tracking-widest bg-emerald-50 px-3 py-2 rounded-xl">
                            <CheckCircle2 className="w-3.5 h-3.5" />
                            Added to Inventory
                          </span>
                        )}
                      </td>
                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>

        {/* PAGINATION */}
        {totalPages > 1 && (
          <div className="flex justify-between items-center p-4 border-t border-zinc-100">
            <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">
              Showing page {page} of {totalPages} ({totalRecords} total)
            </span>
            <div className="flex gap-2">
              <button
                disabled={page === 1}
                onClick={() => setPage(p => p - 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-zinc-50 disabled:opacity-50 transition cursor-pointer shadow-sm"
              >
                Previous
              </button>
              <button
                disabled={page === totalPages}
                onClick={() => setPage(p => p + 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-zinc-50 disabled:opacity-50 transition cursor-pointer shadow-sm"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
