"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/auth";
import { BarChart3 } from "lucide-react";
import { format } from "date-fns";
import { id } from "date-fns/locale";

const API = process.env.NEXT_PUBLIC_API_URL ;

interface Order {
  id: number;
  invoice_no?: string;
  invoice_id?: string;
  game_name?: string;
  product?: { product_name: string };
  price?: number;
  total_price?: number;
  fulfill_status: string;
  created_at: string;
  user_input?: string;
}

export default function TransactionsPage() {
  const { token } = useAuth();
  const [data, setData] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [status, setStatus] = useState("");
  const [search, setSearch] = useState("");

  useEffect(() => {
    if (!token) return;
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), limit: "10" });
    if (status) params.set("status", status);
    fetch(`${API}/api/user/transactions?${params}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(r => r.json())
      .then(res => {
        if (res.success) {
          setData(res.data || []);
          setTotalPages(res.pagination?.totalPages || 1);
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [token, page, status]);

  const filtered = search
    ? data.filter(t => 
        (t.invoice_no?.toLowerCase().includes(search.toLowerCase()) || t.invoice_id?.toLowerCase().includes(search.toLowerCase())) || 
        (t.product?.product_name?.toLowerCase().includes(search.toLowerCase()))
      )
    : data;

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "success": return "bg-green-500/10 text-green-400 border border-green-500/20";
      case "pending": return "bg-yellow-500/10 text-yellow-400 border border-yellow-500/20";
      case "processing": return "bg-blue-500/10 text-blue-400 border border-blue-500/20";
      case "failed": return "bg-red-500/10 text-red-400 border border-red-500/20";
      default: return "bg-white/5 text-white border border-white/10";
    }
  };

  const getStatusText = (status: string) => {
    switch (status.toLowerCase()) {
      case "success": return "Sukses";
      case "pending": return "Menunggu";
      case "processing": return "Proses";
      case "failed": return "Gagal";
      default: return status;
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-heading text-lg font-bold text-white mb-1">Riwayat Transaksi</h1>
        <p className="text-xs text-muted">Menampilkan data riwayat transaksi yang telah Kamu lakukan selama periode yang dipilih.</p>
      </div>

      {/* Filters Container */}
      <div className="bg-dark-surface rounded-xl p-5 border border-dark-border shadow-sm">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-3">
          <div>
            <label className="text-[10px] font-medium text-muted block mb-1.5">Status</label>
            <select 
              value={status} 
              onChange={e => { setStatus(e.target.value); setPage(1); }} 
              className="w-full bg-white/5 border border-dark-border focus:border-primary text-white text-xs rounded-lg px-3 py-2.5 outline-none transition-colors appearance-none"
            >
              <option value="">Semua</option>
              <option value="pending">Menunggu</option>
              <option value="processing">Dalam Proses</option>
              <option value="success">Sukses</option>
              <option value="failed">Gagal</option>
            </select>
          </div>
          <div>
            <label className="text-[10px] font-medium text-muted block mb-1.5">Status Pembayaran</label>
            <select className="w-full bg-white/5 border border-dark-border focus:border-primary text-white text-xs rounded-lg px-3 py-2.5 outline-none transition-colors appearance-none">
              <option value="">Semua</option>
            </select>
          </div>
          <div>
            <label className="text-[10px] font-medium text-muted block mb-1.5">Tanggal Mulai</label>
            <input type="date" className="w-full bg-white/5 border border-dark-border focus:border-primary text-white text-xs rounded-lg px-3 py-2 outline-none transition-colors [color-scheme:dark]" defaultValue="2026-04-25" />
          </div>
          <div>
            <label className="text-[10px] font-medium text-muted block mb-1.5">Tanggal Akhir</label>
            <input type="date" className="w-full bg-white/5 border border-dark-border focus:border-primary text-white text-xs rounded-lg px-3 py-2 outline-none transition-colors [color-scheme:dark]" defaultValue="2026-04-26" />
          </div>
        </div>
        
        <div>
          <label className="text-[10px] font-medium text-muted block mb-1.5">Cari</label>
          <input
            type="text"
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="#Invoice, @User Input"
            className="w-full md:w-1/2 bg-white/5 border border-dark-border focus:border-primary text-white text-xs rounded-lg px-3 py-2.5 outline-none transition-colors"
          />
        </div>
      </div>

      {/* Export buttons */}
      <div className="flex items-center justify-end gap-2">
        <button className="px-4 py-2 rounded-full border border-dark-border text-xs font-medium text-muted hover:text-white transition-colors bg-dark-surface shadow-sm hover:border-primary/50">
          Unduh CSV
        </button>
        <button className="px-4 py-2 rounded-full border border-dark-border text-xs font-medium text-muted hover:text-white transition-colors bg-dark-surface shadow-sm hover:border-primary/50">
          Unduh XLSX
        </button>
        <select className="px-4 py-2 rounded-full border border-dark-border text-xs font-medium text-muted hover:text-white transition-colors bg-dark-surface shadow-sm outline-none appearance-none cursor-pointer">
          <option>10 Entri</option>
          <option>25 Entri</option>
          <option>50 Entri</option>
        </select>
      </div>

      {/* Table — Desktop */}
      <div className="hidden md:block bg-dark-surface rounded-xl border border-dark-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm whitespace-nowrap">
            <thead className="bg-white/[0.02] text-xs text-muted font-medium border-b border-dark-border">
              <tr>
                <th className="px-4 py-3 font-medium">Invoice</th>
                <th className="px-4 py-3 font-medium">Item</th>
                <th className="px-4 py-3 font-medium">User Input</th>
                <th className="px-4 py-3 font-medium">Harga</th>
                <th className="px-4 py-3 font-medium">Tanggal</th>
                <th className="px-4 py-3 font-medium text-center">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-dark-border">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center text-muted text-xs">Memuat data...</td>
                </tr>
              ) : filtered.length > 0 ? (
                filtered.map((trx) => {
                  const d = new Date(trx.created_at);
                  const dateStr = !isNaN(d.getTime()) ? format(d, "dd/MM/yyyy HH:mm", { locale: id }) : "-";
                  const invoice = trx.invoice_no || trx.invoice_id || "-";
                  const price = trx.price || trx.total_price || 0;
                  return (
                    <tr key={trx.id} className="hover:bg-white/[0.02] transition-colors">
                      <td className="px-4 py-3 text-white text-xs font-medium">{invoice}</td>
                      <td className="px-4 py-3 text-white text-xs">{trx.product?.product_name || trx.game_name || "-"}</td>
                      <td className="px-4 py-3 text-white text-xs">{trx.user_input || "-"}</td>
                      <td className="px-4 py-3 text-white text-xs">Rp {price.toLocaleString("id-ID")}</td>
                      <td className="px-4 py-3 text-muted text-xs">{dateStr}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`inline-block px-2.5 py-0.5 rounded text-[10px] font-bold ${getStatusColor(trx.fulfill_status)}`}>
                          {getStatusText(trx.fulfill_status)}
                        </span>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center">
                    <BarChart3 size={32} className="mx-auto mb-2 opacity-20 text-muted" />
                    <p className="text-xs font-medium text-white mb-0.5">Data tidak ditemukan!</p>
                    <p className="text-[10px] text-muted">Tidak ada aktifitas data.</p>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Mobile Card View */}
      <div className="md:hidden space-y-2">
        {loading ? (
          <div className="text-center py-12 text-muted text-xs">Memuat data...</div>
        ) : filtered.length > 0 ? (
          filtered.map((trx) => {
            const d = new Date(trx.created_at);
            const dateStr = !isNaN(d.getTime()) ? format(d, "dd MMM yyyy, HH:mm", { locale: id }) : "-";
            const invoice = trx.invoice_no || trx.invoice_id || "-";
            const price = trx.price || trx.total_price || 0;
            return (
              <div key={trx.id} className="bg-dark-surface rounded-xl border border-dark-border p-3.5">
                <div className="flex items-center justify-between gap-2 mb-1.5">
                  <div className="flex items-center gap-2 min-w-0">
                    <p className="text-xs font-bold text-white truncate">{invoice}</p>
                    <span className={`inline-block px-2 py-0.5 rounded text-[8px] font-bold shrink-0 ${getStatusColor(trx.fulfill_status)}`}>
                      {getStatusText(trx.fulfill_status)}
                    </span>
                  </div>
                  <p className="text-xs font-bold text-white shrink-0">Rp{price.toLocaleString("id-ID")}</p>
                </div>
                <p className="text-[10px] text-muted truncate">{trx.product?.product_name || trx.game_name || "-"}</p>
                <div className="flex items-center justify-between mt-1">
                  <p className="text-[10px] text-muted/60">{dateStr}</p>
                  {trx.user_input && <p className="text-[10px] text-muted">ID: {trx.user_input}</p>}
                </div>
              </div>
            );
          })
        ) : (
          <div className="text-center py-12">
            <BarChart3 size={32} className="mx-auto mb-2 opacity-20 text-muted" />
            <p className="text-xs font-medium text-white mb-0.5">Data tidak ditemukan!</p>
            <p className="text-[10px] text-muted">Tidak ada aktifitas data.</p>
          </div>
        )}
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between text-[10px] sm:text-xs text-muted">
        <span>Hal {page} / {totalPages}</span>
        <div className="flex items-center gap-2">
          <button disabled={page <= 1} onClick={() => setPage(p => p - 1)} className="px-3 py-1.5 rounded-full border border-dark-border bg-dark-surface hover:bg-white/5 hover:text-white disabled:opacity-50 transition-colors text-xs">
            Sebelumnya
          </button>
          <button disabled={page >= totalPages} onClick={() => setPage(p => p + 1)} className="px-3 py-1.5 rounded-full border border-dark-border bg-dark-surface hover:bg-white/5 hover:text-white disabled:opacity-50 transition-colors text-xs">
            Selanjutnya
          </button>
        </div>
      </div>
    </div>
  );
}
