"use client";

import { useEffect, useState } from "react";
import { Banknote, TrendingUp, ShoppingBag, Receipt, Calendar, RefreshCw } from "lucide-react";
import { financeApi } from "@/lib/api";

interface ProductSale {
  product_name: string;
  total_quantity: number;
  total_revenue: number;
}

interface DailySale {
  date: string;
  order_count: number;
  revenue: number;
}

interface FinanceData {
  total_revenue: number;
  active_revenue: number;
  product_sales: ProductSale[];
  daily_sales: DailySale[];
}

export default function AdminFinancePage() {
  const [data, setData] = useState<FinanceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [mounted, setMounted] = useState(false);

  const fetchStats = async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    else setLoading(true);

    try {
      const res = await financeApi.getStats();
      setData(res.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    setMounted(true);
    fetchStats();
  }, []);

  if (!mounted) {
    return (
      <div className="text-center py-20">
        <div className="w-8 h-8 border-4 border-primary/30 border-t-primary rounded-full animate-spin mx-auto mb-4" />
        <p className="text-muted-foreground">Yükleniyor...</p>
      </div>
    );
  }

  const totalCompletedOrders = data?.daily_sales.reduce((sum, d) => sum + Number(d.order_count), 0) || 0;
  const avgOrderValue = totalCompletedOrders > 0 ? (data?.total_revenue || 0) / totalCompletedOrders : 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Finansal Raporlar</h1>
          <p className="text-muted-foreground mt-1">İşletmenizin ciro ve satış istatistiklerini izleyin.</p>
        </div>
        <button
          onClick={() => fetchStats(true)}
          disabled={refreshing || loading}
          className="flex items-center gap-2 bg-muted text-foreground px-4 py-2 rounded-xl text-sm font-semibold hover:bg-accent transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`} />
          Yenile
        </button>
      </div>

      {loading ? (
        <div className="text-center py-20">
          <div className="w-8 h-8 border-4 border-primary/30 border-t-primary rounded-full animate-spin mx-auto mb-4" />
          <p className="text-muted-foreground">Yükleniyor...</p>
        </div>
      ) : data ? (
        <>
          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-card border border-border/50 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-emerald/10 flex items-center justify-center text-emerald">
                <Banknote className="w-6 h-6" />
              </div>
              <div>
                <p className="text-xs text-muted-foreground font-medium">Toplam Hasılat (Kasa)</p>
                <h3 className="text-2xl font-bold text-foreground mt-1">₺{data.total_revenue.toFixed(2)}</h3>
              </div>
            </div>

            <div className="bg-card border border-border/50 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-amber/10 flex items-center justify-center text-amber">
                <Receipt className="w-6 h-6" />
              </div>
              <div>
                <p className="text-xs text-muted-foreground font-medium">Açık Adisyonlar (Masalar)</p>
                <h3 className="text-2xl font-bold text-foreground mt-1">₺{data.active_revenue.toFixed(2)}</h3>
              </div>
            </div>

            <div className="bg-card border border-border/50 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-blue/10 flex items-center justify-center text-blue">
                <ShoppingBag className="w-6 h-6" />
              </div>
              <div>
                <p className="text-xs text-muted-foreground font-medium">Toplam Sipariş</p>
                <h3 className="text-2xl font-bold text-foreground mt-1">{totalCompletedOrders} Adet</h3>
              </div>
            </div>

            <div className="bg-card border border-border/50 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-purple/10 flex items-center justify-center text-purple">
                <TrendingUp className="w-6 h-6" />
              </div>
              <div>
                <p className="text-xs text-muted-foreground font-medium">Ort. Sipariş Tutarı</p>
                <h3 className="text-2xl font-bold text-foreground mt-1">₺{avgOrderValue.toFixed(2)}</h3>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Top Selling Products */}
            <div className="bg-card border border-border/50 rounded-2xl p-6">
              <h2 className="text-lg font-bold mb-4">Ürün Satış Detayları</h2>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                  <thead>
                    <tr className="text-muted-foreground border-b border-border/50 pb-2">
                      <th className="py-2 font-semibold">Ürün Adı</th>
                      <th className="py-2 text-right font-semibold">Satılan Adet</th>
                      <th className="py-2 text-right font-semibold">Toplam Ciro</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.product_sales.length === 0 ? (
                      <tr>
                        <td colSpan={3} className="py-4 text-center text-muted-foreground">
                          Henüz tamamlanmış satış bulunmuyor.
                        </td>
                      </tr>
                    ) : (
                      data.product_sales.map((p, idx) => (
                        <tr key={idx} className="border-b border-border/30 hover:bg-muted/10">
                          <td className="py-3 font-medium">{p.product_name}</td>
                          <td className="py-3 text-right">{p.total_quantity}</td>
                          <td className="py-3 text-right font-semibold text-emerald">
                            ₺{Number(p.total_revenue).toFixed(2)}
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Daily Breakdown */}
            <div className="bg-card border border-border/50 rounded-2xl p-6">
              <h2 className="text-lg font-bold mb-4">Günlük Ciro Raporu</h2>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                  <thead>
                    <tr className="text-muted-foreground border-b border-border/50 pb-2">
                      <th className="py-2 font-semibold">Tarih</th>
                      <th className="py-2 text-right font-semibold">Sipariş Sayısı</th>
                      <th className="py-2 text-right font-semibold">Ciro</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.daily_sales.length === 0 ? (
                      <tr>
                        <td colSpan={3} className="py-4 text-center text-muted-foreground">
                          Henüz tamamlanmış satış bulunmuyor.
                        </td>
                      </tr>
                    ) : (
                      data.daily_sales.map((d, idx) => (
                        <tr key={idx} className="border-b border-border/30 hover:bg-muted/10">
                          <td className="py-3 font-medium flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-muted-foreground" />
                            {new Date(d.date).toLocaleDateString("tr-TR", {
                              day: "numeric",
                              month: "long",
                              year: "numeric",
                            })}
                          </td>
                          <td className="py-3 text-right">{d.order_count}</td>
                          <td className="py-3 text-right font-bold text-emerald">
                            ₺{Number(d.revenue).toFixed(2)}
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </>
      ) : (
        <div className="text-center py-20 text-muted-foreground">İstatistikler yüklenemedi.</div>
      )}
    </div>
  );
}
