import React, { useState, useEffect, useContext } from "react";
import { GlobalContext } from "../../globalContext";
import moment from "moment";
import MkdSDK from "../../utils/MkdSDK";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { ClipLoader } from "react-spinners";

const ViewInvoiceModal = ({ isOpen, onClose, invoiceId }) => {
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const [loading, setLoading] = useState(true);
  const [invoice, setInvoice] = useState(null);
  const [userDetails, setUserDetails] = useState(null);

  useEffect(() => {
    const fetchInvoiceDetails = async () => {
      if (!invoiceId) return;

      try {
        setLoading(true);
        const sdk = new MkdSDK();
        const result = await sdk.getInvoiceById(invoiceId);
        setInvoice(result);

        if (result?.user_id) {
          const userResult = await sdk.getUserDetails(result.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);
      }
    };

    if (isOpen) {
      fetchInvoiceDetails();
    }
  }, [invoiceId, isOpen]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto overflow-x-hidden">
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal Content */}
      <div className="relative max-h-[90vh] w-full max-w-6xl overflow-y-auto rounded-lg border border-strokedark bg-boxdark">
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute right-4 top-4 rounded-full p-1 text-white hover:bg-meta-4"
        >
          <XMarkIcon className="h-6 w-6" />
        </button>

        {loading ? (
          <div className="flex h-64 items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
        ) : !invoice ? (
          <div className="flex h-64 items-center justify-center">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-danger">
                Invoice Not Found
              </h2>
            </div>
          </div>
        ) : (
          <div className="p-6">
            {/* Header Section */}
            <div className="mb-6 flex items-center justify-between border-b border-strokedark pb-6">
              <div>
                <h2 className="text-2xl font-bold text-white">
                  Invoice #{invoice.id}
                </h2>
                <p className="mt-1 text-sm text-bodydark2">
                  Created on {moment(invoice.created_at).format("MMM DD, YYYY")}
                </p>
              </div>
              <div>
                <span
                  className={`inline-block rounded px-3 py-1 text-sm font-medium ${
                    invoice.status === "paid"
                      ? "bg-success/10 text-success"
                      : invoice.status === "pending"
                      ? "bg-warning/10 text-warning"
                      : invoice.status === "overdue"
                      ? "bg-danger/10 text-danger"
                      : "bg-primary/10 text-primary"
                  }`}
                >
                  {invoice.status}
                </span>
              </div>
            </div>

            {/* Producer Information */}
            {userDetails && (
              <div className="mb-6 rounded-sm border border-stroke bg-meta-4 p-6">
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div className="flex items-center gap-4">
                    {userDetails.photo && (
                      <img
                        src={userDetails.photo}
                        alt="Producer"
                        className="h-16 w-16 rounded-full object-cover"
                      />
                    )}
                    <div>
                      <h3 className="text-lg font-semibold text-white">
                        {userDetails.first_name} {userDetails.last_name}
                      </h3>
                      <p className="text-sm text-bodydark2">
                        {userDetails.email}
                      </p>
                      <p className="text-sm text-bodydark2">
                        {userDetails.phone}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center justify-end">
                    {userDetails.company_logo && (
                      <img
                        src={userDetails.company_logo}
                        alt="Company Logo"
                        className="h-20 object-contain"
                      />
                    )}
                  </div>
                </div>
              </div>
            )}

            {/* Client Information */}
            <div className="mb-6 rounded-sm border border-stroke bg-boxdark p-6">
              <h3 className="mb-4 text-lg font-semibold text-white">
                Client Details
              </h3>
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <p className="text-sm text-bodydark2">Client Name</p>
                  <p className="text-white">{invoice.client_name}</p>
                </div>
                <div>
                  <p className="text-sm text-bodydark2">Email</p>
                  <p className="text-white">{invoice.client_email}</p>
                </div>
                <div>
                  <p className="text-sm text-bodydark2">Program</p>
                  <p className="text-white">{invoice.program}</p>
                </div>
                <div>
                  <p className="text-sm text-bodydark2">Phone</p>
                  <p className="text-white">{invoice.client_phone}</p>
                </div>
              </div>
            </div>

            {/* Invoice Items */}
            <div className="mb-6 rounded-sm border border-stroke bg-boxdark p-6">
              <h3 className="mb-4 text-lg font-semibold text-white">
                Invoice Items
              </h3>
              <div className="overflow-x-auto">
                <table className="w-full table-auto">
                  <thead className="bg-meta-4">
                    <tr>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Mix Date
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Team Name
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Division
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Mix Type
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Survey Due
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Submission Due
                      </th>
                      <th className="p-2.5 text-left text-sm font-medium text-white">
                        Est. Completion
                      </th>
                      <th className="p-2.5 text-right text-sm font-medium text-white">
                        Amount
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {invoice.items?.map((item, index) => (
                      <tr key={index} className="border-b border-strokedark">
                        <td className="p-2.5 text-white">
                          {moment(item.mix_date).format("MMM DD, YYYY")}
                        </td>
                        <td className="p-2.5 text-white">{item.team_name}</td>
                        <td className="p-2.5 text-white">{item.division}</td>
                        <td className="p-2.5 text-white">{item.mix_type}</td>
                        <td className="p-2.5 text-white">
                          {moment(item.music_survey_due).format("MMM DD, YYYY")}
                        </td>
                        <td className="p-2.5 text-white">
                          {moment(item.routine_submission_due).format(
                            "MMM DD, YYYY"
                          )}
                        </td>
                        <td className="p-2.5 text-white">
                          {moment(item.estimated_completion).format(
                            "MMM DD, YYYY"
                          )}
                        </td>
                        <td className="p-2.5 text-right text-white">
                          ${parseFloat(item.amount).toFixed(2)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Payment Information */}
            <div className="mb-6 rounded-sm border border-stroke bg-boxdark p-6">
              <h3 className="mb-4 text-lg font-semibold text-white">
                Payment Details
              </h3>
              <div className="space-y-3">
                <div className="flex justify-between border-b border-strokedark pb-3">
                  <span className="text-bodydark2">Subtotal:</span>
                  <span className="text-white">
                    ${parseFloat(invoice.subtotal || 0).toFixed(2)}
                  </span>
                </div>
                <div className="flex justify-between border-b border-strokedark pb-3">
                  <span className="text-bodydark2">
                    Deposit ({invoice.deposit_percentage}%):
                  </span>
                  <span className="text-white">
                    ${parseFloat(invoice.deposit_amount || 0).toFixed(2)}
                  </span>
                </div>
                <div className="flex justify-between pt-3">
                  <span className="text-lg font-semibold text-white">
                    Total:
                  </span>
                  <span className="text-lg font-semibold text-white">
                    ${parseFloat(invoice.total || 0).toFixed(2)}
                  </span>
                </div>
              </div>
            </div>

            {/* Notes and Terms */}
            {(invoice.notes || invoice.terms_and_conditions) && (
              <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                {invoice.notes && (
                  <div className="rounded-sm border border-stroke bg-boxdark p-6">
                    <h3 className="mb-4 text-lg font-semibold text-white">
                      Notes
                    </h3>
                    <p className="whitespace-pre-wrap text-bodydark2">
                      {invoice.notes}
                    </p>
                  </div>
                )}
                {invoice.terms_and_conditions && (
                  <div className="rounded-sm border border-stroke bg-boxdark p-6">
                    <h3 className="mb-4 text-lg font-semibold text-white">
                      Terms and Conditions
                    </h3>
                    <p className="whitespace-pre-wrap text-bodydark2">
                      {invoice.terms_and_conditions}
                    </p>
                  </div>
                )}
              </div>
            )}

            {/* Signature Section */}
            {invoice.signature && (
              <div className="mt-6 rounded-sm border border-stroke bg-boxdark p-6">
                <h3 className="mb-4 text-lg font-semibold text-white">
                  Signature
                </h3>
                <div className="flex items-center gap-6">
                  <div>
                    <p className="mb-2 text-sm text-bodydark2">Signed by</p>
                    <p className="text-white">{invoice.client_name}</p>
                  </div>
                  <div>
                    <p className="mb-2 text-sm text-bodydark2">Date</p>
                    <p className="text-white">
                      {moment(invoice.signature_date).format("MMM DD, YYYY")}
                    </p>
                  </div>
                  <div>
                    <p className="mb-2 text-sm text-bodydark2">Initial</p>
                    <p className="text-white">{invoice.initial}</p>
                  </div>
                </div>
                <div className="mt-4">
                  <img
                    src={`https://equalityrecords.s3.amazonaws.com/${invoice.signature}`}
                    alt="Client Signature"
                    className="max-h-20 object-contain"
                  />
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default ViewInvoiceModal;
