import { useState, useMemo } from "react";
import { AssetRecord, FilterState } from "@/types/portfolio-analytics";
import { formatCurrency } from "@/lib/common";

interface PortfolioTableProps {
  data: AssetRecord[];
  filters: FilterState;
  pageSize?: number;
}

export function PortfolioTable({
  data,
  filters,
  pageSize = 50,
}: PortfolioTableProps) {
  const [currentPage, setCurrentPage] = useState(1);

  const paginatedData = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return data.slice(start, start + pageSize);
  }, [data, currentPage, pageSize]);

  const totalPages = Math.ceil(data.length / pageSize);

  const handleDownload = async () => {
    const requestBody: any = { reportType: "excel" };
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== null && (Array.isArray(value) ? value.length > 0 : true)) {
        requestBody[key] = value;
      }
    });

    const res = await fetch("/api/reports/performance/portfolio", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify(requestBody),
    });

    if (res.ok) {
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `portfolio-analytics-${new Date().toISOString().split("T")[0]}.xlsx`;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };

  return (
    <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
      <div className="border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-600">
            Displaying{" "}
            {data.length === 0 ? 0 : (currentPage - 1) * pageSize + 1}-
            {Math.min(currentPage * pageSize, data.length)} of {data.length}{" "}
            results.
          </p>
          <button
            onClick={handleDownload}
            className="inline-flex items-center gap-2 rounded-lg border border-[#428B4D]/40 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white transition"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
            Download Excel
          </button>
        </div>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200 bg-gray-50">
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Asset Class
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Bank
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Date
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Asset Type
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Purchase Currency
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Geography
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Industry
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Sector
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Purchase Value Rc
              </th>
              <th className="px-6 py-3 text-left font-semibold text-gray-700">
                Value
              </th>
            </tr>
          </thead>
          <tbody>
            {paginatedData.length > 0 ? (
              paginatedData.map((record, i) => (
                <tr key={i} className="border-b border-gray-200 hover:bg-gray-50">
                  <td className="px-6 py-4 text-gray-900">{record.assetClass}</td>
                  <td className="px-6 py-4 text-gray-500">{record.bank || "-"}</td>
                  <td className="px-6 py-4 text-gray-900">{record.date}</td>
                  <td className="px-6 py-4 text-gray-900">{record.assetType}</td>
                  <td className="px-6 py-4 text-gray-900">
                    {record.purchaseCurrency || "-"}
                  </td>
                  <td className="px-6 py-4 text-gray-500">{record.geography || ""}</td>
                  <td className="px-6 py-4 text-gray-500">{record.industry || ""}</td>
                  <td className="px-6 py-4 text-gray-500">{record.sector || ""}</td>
                  <td className="px-6 py-4 text-gray-900">
                    {formatCurrency(record.purchaseValueRc, record.purchaseCurrency)}
                  </td>
                  <td className="px-6 py-4 text-gray-900">{record.value}</td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={10} className="px-6 py-8 text-center text-gray-500">
                  No data available
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="border-t border-gray-200 px-6 py-4 flex items-center justify-between">
          <button
            onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
            disabled={currentPage === 1}
            className="px-4 py-2 rounded-lg border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 transition"
          >
            Previous
          </button>
          <span className="text-sm text-gray-600">
            Page {currentPage} of {totalPages}
          </span>
          <button
            onClick={() => setCurrentPage((p) => Math.min(p + 1, totalPages))}
            disabled={currentPage === totalPages}
            className="px-4 py-2 rounded-lg border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 transition"
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
}
