"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";

const formatCurrency = (amount, currency = "USD") => {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: currency,
  }).format(amount);
};

const urlFormatter = (url) => {
  if (!url.startsWith("http://") && !url.startsWith("https://")) {
    url = "https://" + url;
  }
  return url;
};

const urlCleaner = (url) => {
  if (url.startsWith("http://")) {
    url = url.substr(7);
  } else if (url.startsWith("https://")) {
    url = url.substr(8);
  }
  return url;
};

const formattedDate = (date) =>
  new Date(date).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

export default function PortalSelector() {
  const name = "John Doe";
  const client_id = "12345";
  const email = "johndoe@example.com";

  const [monthlyPayment, setMonthlyPayment] = useState(100);
  const [additionalPayment, setadditionalPayment] = useState(20);
  const [manager, setManager] = useState("Fausto Vasconez");
  const [managerEmail, setManagerEmail] = useState("support@rankrunners.net");
  const [managerPosition, setManagerPosition] = useState(
    "Technical Strategist"
  );
  const [projectArray, setProjectArray] = useState([]);
  const [paymentLogArray, setpaymentLogArray] = useState([]);
  const [totalPayment, setTotalPayment] = useState(0);

  useEffect(() => {
    setTotalPayment(monthlyPayment + additionalPayment);
    // Simulate fetching project and payment log data
    setProjectArray([
      {
        Title: "Project 1",
        URL: "https://example.com",
        "Price Monthly": 100,
        Services: "Service1, Service2",
        "PDF Contract": [],
      },
    ]);
    setpaymentLogArray([
      {
        id: "PAY123",
        created: "2025-01-01",
        amount_paid: 120,
      },
    ]);
  }, []);

  return (
    <div>
      <div className="row dashboard-hero">
        <div className="col dashboard-heading">
          <h2>Welcome, {name}</h2>
          <div className="dashboard-badge-group">
            <div className="dashboard-badge">{client_id}</div>
            <div className="dashboard-badge">{email}</div>
          </div>
        </div>
        <div className="col col-md-5 col-lg-4 col-xl-3">
          <div className="dashboard-hero-payment tg-heading-subheading">
            <h4 className="sub-title text-dark">Active</h4>
            <h2 className="text-start text-dark">
              {formatCurrency(totalPayment)}
            </h2>
            <h5 className="text-start">January 31, 2025</h5>
          </div>
        </div>
      </div>
      <div className="row justify-content-start portal-gap">
        <div className="col-12">
          <div className="portal-card">
            <h2 className="text-dark">Projects</h2>
            {projectArray &&
              projectArray.map((project, index) => (
                <React.Fragment key={project["Title"]}>
                  <div className="table-responsive">
                    <table className="table table-sm dashboard-table">
                      <thead>
                        <tr>
                          <th>{project["Title"]}</th>
                          <th>
                            {project["URL"] && (
                              <Link href={urlFormatter(project["URL"])}>
                                {urlCleaner(project["URL"])}
                              </Link>
                            )}
                            {!project["URL"] && "No URL"}
                          </th>
                          <th>${project["Price Monthly"]}/mo</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td colSpan="2">
                            {project["Services"].replace(/,/g, ", ")}
                          </td>
                          <td>
                            {project["PDF Contract"] &&
                            project["PDF Contract"].length > 0 ? (
                              project["PDF Contract"].map((contract, index) => (
                                <Link
                                  key={index}
                                  href={contract.signedUrl}
                                  target="_blank"
                                >
                                  View PDF Contract
                                </Link>
                              ))
                            ) : (
                              <Link href="#">No PDF Attachment</Link>
                            )}
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  {index < projectArray.length - 1 && (
                    <div className="text-or"></div>
                  )}
                </React.Fragment>
              ))}

            {!projectArray && (
              <div>
                <h3 className="text-center">No Projects</h3>
                <p className="text-center">
                  You currently have no projects. Contact your account manager
                </p>
              </div>
            )}
          </div>
        </div>
        <div className="col col-md-6 col-lg-6 col-xl-7">
          <div className="portal-card">
            <h2 className="text-dark">Account Manager</h2>
            <div className="d-flex justify-content-between">
              <div>Name</div>
              <div>{manager}</div>
            </div>
            <div className="d-flex justify-content-between">
              <div>Position</div>
              <div>{managerPosition}</div>
            </div>
            <div className="d-flex justify-content-between pb-15">
              <div>Email</div>
              <div>{managerEmail}</div>
            </div>
            <Link
              href={`mailto:${managerEmail}`}
              target="_blank"
              className="btn btn-no-arrow"
            >
              Email to Account Manager
            </Link>
          </div>
        </div>
        <div className="col col-md-6 col-lg-6 col-xl-5">
          <div className="portal-card">
            <h2 className="text-dark">Payment</h2>
            <div className="d-flex justify-content-between">
              <div>Amount Due</div>
              <div>{formatCurrency(totalPayment)}</div>
            </div>
            <div className="d-flex justify-content-between">
              <div>Due Date</div>
              <div className="dashboard-icon-parent">January 31, 2025</div>
            </div>
            <div className="d-flex justify-content-between pb-15">
              <div>Payment Method</div>
              <div>Stripe</div>
            </div>
          </div>
        </div>
        <div className="col-12">
          <div className="portal-card">
            <h2 className="text-dark">Active Payment Log</h2>

            {!paymentLogArray && (
              <div>
                <h3 className="text-center">No Payment History</h3>
                <p className="text-center">
                  You don't have any payment history. If you have, please
                  refresh the page or contact your account manager
                </p>
              </div>
            )}
            {paymentLogArray && (
              <div className="table-responsive">
                <table className="table table-sm dashboard-table table-log">
                  <thead>
                    <tr>
                      <th>Payment ID</th>
                      <th>Date</th>
                      <th>Amount Paid (USD)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {paymentLogArray &&
                      paymentLogArray.map((payment) => (
                        <tr key={payment.id}>
                          <td>{payment["id"]}</td>
                          <td>{formattedDate(payment["created"])}</td>
                          <td>{payment["amount_paid"]}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
