"use client";

import { useState, useEffect } from "react";
import { useTranslations, useLocale } from "next-intl";
import { instance } from "@/config/axios";
import { toast } from "react-hot-toast";

interface BillingRecord {
  uuid: string;
  amount: number;
  currency: string;
  status: string;
  payment_method: string;
  paid_at: string;
  created_at: string;
  invoice_url: string | null;
}

interface BillingHistoryResponse {
  payments: BillingRecord[];
  pagination: {
    current_page: number;
    per_page: number;
    total: number;
    total_pages: number;
  };
}

export default function Subscription() {
  const t = useTranslations("individual.subscription");
  const locale = useLocale();
  const [currentPage, setCurrentPage] = useState(1);
  const [billingHistory, setBillingHistory] = useState<BillingRecord[]>([]);
  const [pagination, setPagination] = useState({
    current_page: 1,
    per_page: 10,
    total: 0,
    total_pages: 1,
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isDownloading, setIsDownloading] = useState<string | null>(null);

  const itemsPerPage = 10;

  // Fetch billing history
  useEffect(() => {
    const fetchBillingHistory = async () => {
      setIsLoading(true);
      try {
        const response = await instance.get<{ data: BillingHistoryResponse }>(
          `/v1/individual/billing?page=${currentPage}&limit=${itemsPerPage}`
        );

        if (response.data?.data) {
          setBillingHistory(response.data.data.payments);
          setPagination(response.data.data.pagination);
        }
      } catch (error) {
        console.error("Failed to fetch billing history:", error);
        toast.error(t("billingLoadError"));
      } finally {
        setIsLoading(false);
      }
    };

    fetchBillingHistory();
  }, [currentPage]);

  const totalPages = pagination.total_pages;
  const startIndex = (currentPage - 1) * itemsPerPage;

  const getStatusBadgeStyles = (status: string) => {
    const statusLower = status.toLowerCase();
    if (statusLower === "completed" || statusLower === "paid") {
      return "bg-green-100 text-green-600";
    } else if (statusLower === "pending") {
      return "bg-yellow-100 text-yellow-600";
    } else if (statusLower === "failed" || statusLower === "canceled") {
      return "bg-red-100 text-red-600";
    }
    return "bg-gray-100 text-gray-600";
  };

  const getStatusLabel = (status: string) => {
    const statusLower = status.toLowerCase();
    if (statusLower === "completed") return t("completed");
    if (statusLower === "pending") return t("pending");
    if (statusLower === "failed") return t("failed");
    return status;
  };

  const handleDownloadInvoice = async (record: BillingRecord) => {
    if (!record.invoice_url) {
      toast.error(t("invoiceNotAvailable"));
      return;
    }

    setIsDownloading(record.uuid);
    try {
      const response = await instance.get(record.invoice_url);
      window.open(response.data.url, "_blank");
    } catch (error) {
      console.error("Failed to download invoice:", error);
      toast.error(t("downloadFailed"));
    } finally {
      setIsDownloading(null);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString(locale === "es" ? "es-ES" : "en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  };

  const formatAmount = (amount: number, currency: string) => {
    return new Intl.NumberFormat(locale === "es" ? "es-ES" : "en-US", {
      style: "currency",
      currency: currency.toUpperCase(),
    }).format(amount);
  };

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, "...", totalPages - 1, totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 2, "...", totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(
          1,
          "...",
          currentPage - 1,
          currentPage,
          currentPage + 1,
          "...",
          totalPages
        );
      }
    }
    return pages;
  };

  return (
    <main className="pt-20 pb-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Page Header */}
          <div className="mb-8">
            <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900">
              {t("title")}
            </h1>
            <p className="mt-1 text-sm text-gray-500">
              {t("subtitle")}
            </p>
          </div>

          {/* Billing History Card */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
            <div className="p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">
                {t("billingHistory")}
              </h2>

              {/* Table */}
              <div className="overflow-x-auto border border-gray-200 rounded-lg">
                <table className="w-full border-collapse">
                  <thead>
                    <tr className="border-b border-gray-200 bg-gray-50">
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 w-16 border-r border-gray-200">
                        {t("no")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("date")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("plan")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("amount")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("status")}
                      </th>
                      <th className="text-center py-3 px-4 text-sm font-medium text-gray-500 w-32">
                        {t("action")}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {isLoading ? (
                      <tr>
                        <td colSpan={6} className="py-8 text-center text-gray-500">
                          {t("loadingBillingHistory")}
                        </td>
                      </tr>
                    ) : billingHistory.length === 0 ? (
                      <tr>
                        <td colSpan={6} className="py-8 text-center text-gray-500">
                          {t("noBillingHistory")}
                        </td>
                      </tr>
                    ) : (
                      billingHistory.map((record, index) => (
                        <tr
                          key={record.uuid}
                          className="border-b border-gray-200 last:border-0 hover:bg-gray-50/50 transition"
                        >
                          <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                            {startIndex + index + 1}
                          </td>
                          <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                            {formatDate(record.paid_at || record.created_at)}
                          </td>
                          <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                            {t("perScreening")}
                          </td>
                          <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                            {formatAmount(record.amount, record.currency)}
                          </td>
                          <td className="py-4 px-4 border-r border-gray-200">
                            <span
                              className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${getStatusBadgeStyles(
                                record.status
                              )}`}
                            >
                              <span className="w-1.5 h-1.5 rounded-full bg-current"></span>
                              {getStatusLabel(record.status)}
                            </span>
                          </td>
                          <td className="py-4 px-4">
                            <div className="flex items-center justify-center">
                              <button
                                onClick={() => handleDownloadInvoice(record)}
                                disabled={!record.invoice_url || isDownloading === record.uuid}
                                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                              >
                                {isDownloading === record.uuid ? (
                                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                  </svg>
                                ) : (
                                  <svg
                                    className="w-4 h-4"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                    strokeWidth={2}
                                  >
                                    <path
                                      strokeLinecap="round"
                                      strokeLinejoin="round"
                                      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                                    />
                                  </svg>
                                )}
                                {t("invoice")}
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Pagination */}


            {totalPages > 1 && (


            <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100">
              {/* Previous Button */}
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
              >
                <svg
                  className="w-4 h-4"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M15 19l-7-7 7-7"
                  />
                </svg>
                {t("previous")}
              </button>

              {/* Page Numbers */}
              <div className="hidden sm:flex items-center gap-1">
                {getPageNumbers().map((page, index) =>
                  page === "..." ? (
                    <span
                      key={`ellipsis-${index}`}
                      className="px-3 py-2 text-sm text-gray-500"
                    >
                      ...
                    </span>
                  ) : (
                    <button
                      key={page}
                      onClick={() => setCurrentPage(page as number)}
                      className={`w-9 h-9 flex items-center justify-center text-sm font-medium rounded-lg transition ${
                        currentPage === page
                          ? "bg-gray-100 text-gray-900"
                          : "text-gray-600 hover:bg-gray-50"
                      }`}
                    >
                      {page}
                    </button>
                  )
                )}
              </div>

              {/* Next Button */}
              <button
                onClick={() =>
                  setCurrentPage((p) => Math.min(totalPages, p + 1))
                }
                disabled={currentPage === totalPages}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
              >
                {t("next")}
                <svg
                  className="w-4 h-4"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M9 5l7 7-7 7"
                  />
                </svg>
              </button>
            </div>
            )}
          </div>
        </div>
    </main>
  );
}
