"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 Mutation {
  id: number;
  description: string;
  amount: number;
  balance: number;
  created_at: string;
}

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

  useEffect(() => {
    if (!token) return;
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), limit: "10" });
    if (status) params.set("status", status); // If API supports filtering by status
    
    fetch(`${API}/api/user/mutations?${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]);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-heading text-lg font-bold text-white mb-1">Riwayat Mutasi</h1>
        <p className="text-xs text-muted">Menampilkan data riwayat mutasi 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-1 md:grid-cols-3 gap-4">
          <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="in">Masuk</option>
              <option value="out">Keluar</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>

      {/* 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 */}
      <div className="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-6 py-4 font-medium">Nomor Invoice</th>
                <th className="px-6 py-4 font-medium">Deskripsi</th>
                <th className="px-6 py-4 font-medium">Jumlah</th>
                <th className="px-6 py-4 font-medium">XCredits</th>
                <th className="px-6 py-4 font-medium">XCredits Saat Ini</th>
                <th className="px-6 py-4 font-medium">Tanggal</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-dark-border">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-muted">Memuat data...</td>
                </tr>
              ) : data.length > 0 ? (
                data.map((m) => {
                  let dateStr = "Invalid Date";
                  if (m.created_at) {
                    const d = new Date(m.created_at);
                    if (!isNaN(d.getTime())) {
                      dateStr = format(d, "dd/MM/yyyy HH:mm", { locale: id });
                    } else {
                      dateStr = m.created_at;
                    }
                  } else {
                    dateStr = "-";
                  }
                  
                  return (
                    <tr key={m.id} className="hover:bg-white/[0.02] transition-colors">
                      <td className="px-6 py-4 text-white text-xs">-</td>
                      <td className="px-6 py-4 text-white text-xs">{m.description || "-"}</td>
                      <td className={`px-6 py-4 text-xs font-semibold ${m.amount >= 0 ? "text-green-400" : "text-red-400"}`}>
                        {m.amount >= 0 ? "+" : ""}{m.amount?.toLocaleString("id-ID")}
                      </td>
                      <td className="px-6 py-4 text-white text-xs">-</td>
                      <td className="px-6 py-4 text-white text-xs font-semibold">{m.balance?.toLocaleString("id-ID")}</td>
                      <td className="px-6 py-4 text-muted text-xs">{dateStr}</td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={6} className="px-6 py-16 text-center">
                    <div className="flex flex-col items-center justify-center text-muted">
                      <BarChart3 size={40} className="mb-3 opacity-30" />
                      <p className="text-sm font-medium text-white mb-1">Data tidak ditemukan!</p>
                      <p className="text-xs">Tidak ada aktifitas data.</p>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between text-xs text-muted">
        <span>Menampilkan {data.length} sampai {data.length} dari {data.length} hasil</span>
        <div className="flex items-center gap-2">
          <button disabled={page <= 1} onClick={() => setPage(p => p - 1)} className="px-4 py-2 rounded-full border border-dark-border bg-dark-surface hover:bg-white/5 hover:text-white disabled:opacity-50 transition-colors shadow-sm">
            Sebelumnya
          </button>
          <button disabled={page >= totalPages} onClick={() => setPage(p => p + 1)} className="px-4 py-2 rounded-full border border-dark-border bg-dark-surface hover:bg-white/5 hover:text-white disabled:opacity-50 transition-colors shadow-sm">
            Selanjutnya
          </button>
        </div>
      </div>
    </div>
  );
}
