import React, { useState, useEffect, useContext } from "react";
import { useParams } from "react-router-dom";
import MkdSDK from "../utils/MkdSDK";
import { GlobalContext } from "../globalContext";
import moment from "moment";
import { ClipLoader } from "react-spinners";

const ViewInvoicePage = () => {
  const { id } = useParams();
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const [loading, setLoading] = useState(true);
  const [invoice, setInvoice] = useState(null);
  const [userDetails, setUserDetails] = useState(null);

  useEffect(() => {
    const fetchInvoiceDetails = async () => {
      try {
        setLoading(true);
        const sdk = new MkdSDK();
        const result = await sdk.getInvoiceById(id);
        setInvoice(result);

        if (result?.invoice?.user_id) {
          const userResult = await sdk.getUserDetails(result.invoice.user_id);
          setUserDetails(userResult);
        }
      } catch (error) {
        console.error("Error fetching invoice:", error);
        globalDispatch({
          type: "SHOW_TOAST",
          payload: {
            text: "Failed to fetch invoice details",
            type: "error",
          },
        });
      } finally {
        setLoading(false);
      }
    };

    fetchInvoiceDetails();
  }, [id]);

  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <ClipLoader color="#fff" size={30} />
      </div>
    );
  }

  if (!invoice) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-danger">Invoice Not Found</h2>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen w-full flex-col rounded-md bg-gray-800 p-5 text-white">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-stroke pb-4">
        <div className="flex items-center gap-2">
          <h6 className="whitespace-normal text-xl font-normal">Invoice:</h6>
          <h6 className="whitespace-normal text-xl font-normal">
            #{invoice.invoice.id}
          </h6>
          <span
            className={`ml-4 rounded px-2.5 py-0.5 text-sm font-medium ${
              invoice.invoice.status === "paid"
                ? "bg-success/10 text-success"
                : invoice.invoice.status === "pending"
                ? "bg-warning/10 text-warning"
                : "bg-danger/10 text-danger"
            }`}
          >
            {invoice.invoice.status}
          </span>
          {invoice.invoice.payment_status && (
            <span
              className={`ml-2 rounded px-2.5 py-0.5 text-sm font-medium ${
                invoice.invoice.payment_status === "succeeded"
                  ? "bg-success/10 text-success"
                  : "bg-warning/10 text-warning"
              }`}
            >
              {invoice.invoice.payment_status.replace(/_/g, " ")}
            </span>
          )}
        </div>
        <p className="text-sm text-bodydark2">
          Created: {moment(invoice.invoice.create_at).format("MMM DD, YYYY")}
        </p>
      </div>

      {/* Client Details */}
      <div className="mt-8">
        <h6 className="mb-4 text-base font-normal">Client Details:</h6>
        <div className="grid grid-cols-2 gap-6">
          <div>
            <p className="text-sm text-bodydark2">Name</p>
            <p className="mt-1">{invoice.invoice.client_name}</p>
          </div>
          <div>
            <p className="text-sm text-bodydark2">Email</p>
            <p className="mt-1">{invoice.invoice.client_email}</p>
          </div>
          <div>
            <p className="text-sm text-bodydark2">Program</p>
            <p className="mt-1">{invoice.invoice.program}</p>
          </div>
          <div>
            <p className="text-sm text-bodydark2">Invoice Date</p>
            <p className="mt-1">
              {moment(invoice.invoice.invoice_date).format("MMM DD, YYYY")}
            </p>
          </div>
        </div>
      </div>

      {/* Notes */}
      <div className="mt-8">
        <h6 className="mb-4 text-base font-normal">Notes:</h6>
        <div className="grid grid-cols-2 gap-6">
          <div>
            <p className="text-sm text-bodydark2">Producer Notes</p>
            <p className="mt-1 whitespace-pre-wrap">
              {invoice.invoice.notes || "No producer notes"}
            </p>
          </div>
          <div>
            <p className="text-sm text-bodydark2">Client Notes</p>
            <p className="mt-1 whitespace-pre-wrap">
              {invoice.invoice.feedback_notes || "No client notes"}
            </p>
          </div>
        </div>
      </div>

      {/* Invoice Items Table */}
      <div className="mt-8 rounded-sm border border-stroke bg-meta-4">
        <div className="border-b border-stroke p-4">
          <h6 className="text-base font-normal">Invoice Items</h6>
        </div>
        <div className="p-4">
          <div className="overflow-x-auto">
            <table className="w-full table-auto">
              <thead>
                <tr className="border-b border-stroke">
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Mix Date
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Team Name
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Division
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Survey Due
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Submission Due
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Est. Completion
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-white">
                    Amount
                  </th>
                </tr>
              </thead>
              <tbody>
                {invoice.items?.map((item) => (
                  <tr
                    key={item.id}
                    className="border-b border-stroke/50 hover:bg-primary/5"
                  >
                    <td className="whitespace-nowrap px-4 py-3">
                      {moment(item.mix_date).format("MM/DD/YYYY")}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      {item.team_name}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      {item.division}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      {moment(item.music_survey_due).format("MM/DD/YYYY")}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      {moment(item.routine_submission_due).format("MM/DD/YYYY")}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      {moment(item.estimated_completion).format("MM/DD/YYYY")}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-right">
                      ${parseFloat(item.total).toFixed(2)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Payment History */}
      <div className="mt-8 rounded-sm border border-stroke bg-meta-4">
        <div className="border-b border-stroke p-4">
          <h6 className="text-base font-normal">Payment History</h6>
        </div>
        <div className="p-4">
          <div className="overflow-x-auto">
            <table className="w-full table-auto">
              <thead>
                <tr className="border-b border-stroke">
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Date
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Method
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                    Status
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-white">
                    Amount
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-white">
                    Fee
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-white">
                    Total
                  </th>
                </tr>
              </thead>
              <tbody>
                {invoice.payments?.map((payment) => (
                  <tr
                    key={payment.id}
                    className="border-b border-stroke/50 hover:bg-primary/5"
                  >
                    <td className="whitespace-nowrap px-4 py-3">
                      {moment(payment.create_at).format("MM/DD/YYYY")}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 capitalize">
                      {payment.payment_method}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3">
                      <span
                        className={`rounded px-2 py-1 text-xs font-medium ${
                          payment.status === "succeeded"
                            ? "bg-success/10 text-success"
                            : "bg-warning/10 text-warning"
                        }`}
                      >
                        {payment.status.replace(/_/g, " ")}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-right">
                      ${parseFloat(payment.amount).toFixed(2)}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-right">
                      ${parseFloat(payment.stripe_fee).toFixed(2)}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-right">
                      ${parseFloat(payment.total_charged).toFixed(2)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Payment Summary */}
      <div className="mt-8 rounded-sm border border-stroke bg-meta-4">
        <div className="border-b border-stroke p-4">
          <h6 className="text-base font-normal">Payment Summary</h6>
        </div>
        <div className="p-4">
          <div className="flex flex-col gap-2">
            <div className="flex justify-between">
              <span className="text-bodydark2">Subtotal:</span>
              <span>
                ${parseFloat(invoice.invoice.subtotal || 0).toFixed(2)}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-bodydark2">
                Deposit ({invoice.invoice.deposit_percentage}%):
              </span>
              <span>
                ${parseFloat(invoice.invoice.deposit_amount || 0).toFixed(2)}
              </span>
            </div>
            <div className="flex justify-between border-t border-stroke pt-2 font-semibold">
              <span>Total:</span>
              <span>${parseFloat(invoice.invoice.total || 0).toFixed(2)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Signature Section */}
      {!invoice.invoice.signature ? (
        <div className="mt-8 rounded-sm border border-stroke bg-meta-4 p-4">
          <p className="text-center text-bodydark2">Invoice not signed yet</p>
        </div>
      ) : (
        <div className="mt-8 rounded-sm border border-stroke bg-meta-4">
          <div className="border-b border-stroke p-4">
            <h6 className="text-base font-normal">Client Signature</h6>
          </div>
          <div className="p-4">
            <div className="flex gap-8">
              <div>
                <p className="text-sm text-bodydark2">Signed By</p>
                <p className="mt-1">{invoice.invoice.client_name}</p>
              </div>
              <div>
                <p className="text-sm text-bodydark2">Initials</p>
                <p className="mt-1">
                  {invoice.invoice.initials || "Not provided"}
                </p>
              </div>
            </div>
            <div className="mt-4">
              <img
                src={`https://equalityrecords.s3.amazonaws.com/${invoice.invoice.signature}`}
                alt="Client Signature"
                className="max-h-20 object-contain"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ViewInvoicePage;
