import React, { useState, useEffect, useContext } from "react";
import { AuthContext } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { updateRequest, createRequest } from "Src/context/Global/GlobalActions";
import MkdSDK from "Utils/MkdSDK";
import {
  Plus,
  FileText,
  Download,
  Trash2,
  ArrowLeft,
  Pencil,
} from "lucide-react";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import moment from "moment";
import { ClipLoader } from "react-spinners";
import { getAllClientsAPI } from "Src/services/clientService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import CustomSelect2 from "Components/CustomSelect2";
import { useNavigate } from "react-router-dom";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

import { EyeIcon } from "Assets/svgs";
import CreateInvoiceComponent from "Components/Invoice/CreateInvoiceComponent";
import EditInvoiceComponent from "Components/Invoice/EditInvoiceComponent";

const InvoicePage = () => {
  const { state: authState, dispatch: authDispatch } =
    React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [showNewInvoice, setShowNewInvoice] = useState(false);
  const [editInvoiceId, setEditInvoiceId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [invoices, setInvoices] = useState([]);
  const [userDetails, setUserDetails] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageCount, setPageCount] = useState(1);
  const [dataTotal, setDataTotal] = useState(0);
  const pageSize = 10;
  const sdk = new MkdSDK();

  // New invoice form state
  const [invoiceData, setInvoiceData] = useState({
    invoiceNumber: "",
    date: new Date().toISOString().split("T")[0],
    dueDate: "",
    clientId: "",
    clientEmail: "",
    clientName: "",
    programName: "",
    isNewClient: false,
    depositAmount: 0,
    depositPercentage: 30,
    notes: "",
    termsAndConditions: "",
    items: [
      {
        mixDate: "",
        producer: "",
        mixType: "",
        teamName: "Team 1",
        division: "TBD",
        musicSurveyDue: "",
        routineSubmissionDue: "",
        estimatedCompletion: "",
        price: 0,
        quantity: 1,
      },
    ],
    subtotal: 0,
    tax: 0,
    total: 0,
  });

  const [focusedInput, setFocusedInput] = React.useState({
    date: null,
    dueDate: null,
    musicSurveyDue: {},
    submission: {},
    estimatedCompletion: {},
  });

  const [dates, setDates] = React.useState({
    date: null,
    dueDate: null,
    musicSurveyDue: {},
    submission: {},
    estimatedCompletion: {},
  });

  const [clients, setClients] = useState([]);
  console.log(clients);
  const [selectedClientId, setSelectedClientId] = useState(null);
  const [newClientData, setNewClientData] = useState({
    program: "",
    email: "",
  });
  const [invoiceDates, setInvoiceDates] = useState({
    invoiceDate: new Date().toISOString().split("T")[0],
    dueDate: "",
  });
  const [producers, setProducers] = useState([]);
  const [mixPackages, setMixPackages] = useState({});
  const [isQuote, setIsQuote] = useState(false);
  const [mixTypes, setMixTypes] = useState([]);

  const [userSettings, setUserSettings] = useState({
    survey: { weeks: 8, day: "Monday" },
    routine_submission_date: { weeks: 1, day: "Monday" },
    estimated_delivery: { weeks: 1, day: "Friday" },
    contract_agreement: "",
  });

  const navigate = useNavigate();
  console.log(invoices, editInvoiceId);

  const calculateDates = (mixDate, index) => {
    if (!mixDate) return;

    const date = moment(mixDate);

    // Parse settings
    const surveySettings = userSettings.survey;
    const routineSettings = userSettings.routine_submission_date;
    const deliverySettings = userSettings.estimated_delivery;

    // Function to find the previous occurrence of a day
    const findPreviousDay = (date, targetDay) => {
      const days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
      ];
      const targetDayIndex = days.indexOf(targetDay);
      let currentDate = moment(date);

      while (currentDate.day() !== targetDayIndex) {
        currentDate.subtract(1, "days");
      }
      return currentDate;
    };

    // Calculate survey date (backwards from mix date)
    const surveyDate = findPreviousDay(
      moment(mixDate).subtract(surveySettings.weeks, "weeks"),
      surveySettings.day
    );

    // Calculate routine submission date (backwards from mix date)
    const submissionDate = findPreviousDay(
      moment(mixDate).subtract(routineSettings.weeks, "weeks"),
      routineSettings.day
    );

    // Calculate estimated completion date (forward from mix date)
    const completionDate = findPreviousDay(
      moment(mixDate).add(deliverySettings.weeks, "weeks"),
      deliverySettings.day
    );

    // Update invoiceData with calculated dates
    setInvoiceData((prev) => {
      const newItems = [...prev.items];
      newItems[index] = {
        ...newItems[index],
        mixDate: mixDate,
        musicSurveyDue: surveyDate.format("YYYY-MM-DD"),
        routineSubmissionDue: submissionDate.format("YYYY-MM-DD"),
        estimatedCompletion: completionDate.format("YYYY-MM-DD"),
      };
      return {
        ...prev,
        items: newItems,
      };
    });

    // Update date pickers state to match
    setDates((prevDates) => ({
      ...prevDates,
      musicSurveyDue: { ...prevDates.musicSurveyDue, [index]: surveyDate },
      submission: { ...prevDates.submission, [index]: submissionDate },
      estimatedCompletion: {
        ...prevDates.estimatedCompletion,
        [index]: completionDate,
      },
    }));
  };

  const getUserDetails = async (userId) => {
    try {
      const result = await getUserDetailsByIdAPI(userId);
      if (!result.error) {
        setUserDetails(result.model);

        // Parse settings from the result
        const surveyData = result.model?.survey
          ? JSON.parse(result.model.survey)
          : { weeks: 8, day: "Monday" };
        const routineData = result.model?.routine_submission_date
          ? JSON.parse(result.model.routine_submission_date)
          : { weeks: 1, day: "Monday" };
        const deliveryData = result.model?.estimated_delivery
          ? JSON.parse(result.model.estimated_delivery)
          : { weeks: 1, day: "Friday" };

        setUserSettings({
          survey: surveyData,
          routine_submission_date: routineData,
          estimated_delivery: deliveryData,
          contract_agreement: result.model?.contract_agreement || "",
        });

        // Update invoice data with contract agreement
        setInvoiceData((prev) => ({
          ...prev,
          termsAndConditions:
            result.model?.contract_agreement || prev.termsAndConditions,
        }));
      }
    } catch (error) {
      console.error("Error fetching user details:", error);
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text: "Failed to fetch company details",
          type: "error",
        },
      });
    }
  };

  const fetchAvailableClients = async () => {
    console.log("fetching clients");
    try {
      const sdk = new MkdSDK();
      const result = await getAllClientsAPI();
      console.log("result", result);
      if (!result.error) {
        setClients(result.list);
      }
    } catch (error) {
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text: "Failed to fetch clients",
          type: "error",
        },
      });
    }
  };

  const getAllMixTypes = async () => {
    try {
      const result = await getAllMixTypeAPI();
      if (!result.error) {
        if (result.list.length > 0) {
          setMixTypes(result.list);
        }
      }
    } catch (error) {
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text: "Failed to fetch mix types",
          type: "error",
        },
      });
    }
  };

  useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: { path: "invoices" },
    });
    fetchInvoices();

    // Fetch user details when component mounts
    const userId = localStorage.getItem("user");
    if (userId) {
      getUserDetails(userId);
    }

    fetchAvailableClients();
    getAllMixTypes();
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch producers
        const producersResult = await sdk.callRestAPI(
          "v3/api/custom/equality_record/producers",
          "GET"
        );
        if (!producersResult.error) {
          setProducers(producersResult.list);

          // Create mix packages object based on producers
          const packages = {};
          producersResult.list.forEach((producer) => {
            packages[producer.id] = producer.mixPackages || [];
          });
          setMixPackages(packages);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
        globalDispatch({
          type: "SHOW_TOAST",
          payload: {
            text: "Failed to fetch required data",
            type: "error",
          },
        });
      }
    };

    fetchData();
  }, []);

  const fetchInvoices = async () => {
    try {
      setLoading(true);
      const sdk = new MkdSDK();
      const result = await sdk.getInvoices(currentPage, pageSize);
      setInvoices(result.invoices || []);
      setPageCount(result.num_pages || 1);
      setDataTotal(result.total || 0);
    } catch (error) {
      console.error("Error fetching invoices:", error);
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text: "Failed to fetch invoices",
          type: "error",
        },
      });
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateInvoice = async (formData) => {
    try {
      setLoading(true);

      // Prepare payload for update
      const payload = {
        client_id: formData.selectedClientId
          ? parseInt(formData.selectedClientId)
          : undefined,

        invoice_date: formData.invoiceDates.invoiceDate,
        due_date: formData.invoiceDates.dueDate,
        notes: formData.invoiceData.notes,
        terms_and_conditions: formData.invoiceData.termsAndConditions,
        deposit_amount: formData.invoiceData.depositAmount,
        deposit_percentage: formData.invoiceData.depositPercentage,

        //   items: formData.invoiceData.items.map((item) => ({
        //     mix_date: item.mixDate,
        //     producer_id: item.producer,
        //     mix_type_id: item.mixType,
        //     team_name: item.teamName,
        //     division: item.division,
        //     music_survey_due: item.musicSurveyDue,
        //     routine_submission_due: item.routineSubmissionDue,
        //     estimated_completion: item.estimatedCompletion,
        //     total: item.price,
        //   })

        // ),
      };

      console.log("formData", formData);

      formData.invoiceData.items.forEach(async (item) => {
        console.log("item", item);
        if (item.id) {
          // Update existing items
          await updateRequest(
            globalDispatch,
            authDispatch,
            "invoice_item",
            item.id,
            {
              team_name: item.teamName,
              division: item.division,
              music_survey_due: item.musicSurveyDue,
              routine_submission_due: item.routineSubmissionDue,
              estimated_completion: item.estimatedCompletion,
              price: item.price,
              mix_date: item.mixDate,
              producer: item.producer,
              quantity: item.quantity,
              description: `Mix Package - ${item.mixType}`,
            },
            false
          );
        } else {
          // Create new items
          await createRequest(
            globalDispatch,
            authDispatch,
            "invoice_item",
            {
              invoice_id: editInvoiceId,
              team_name: item.teamName,
              division: item.division,
              music_survey_due: item.musicSurveyDue,
              routine_submission_due: item.routineSubmissionDue,
              estimated_completion: item.estimatedCompletion,
              price: item.price,
              mix_date: item.mixDate,
              producer: item.producer,
              quantity: item.quantity,
              description: `Mix Package - ${item.mixType}`,
            },
            false
          );
        }
      });

      const result = await updateRequest(
        globalDispatch,
        authDispatch,
        "invoice",
        editInvoiceId,
        payload
      );

      if (!result.error) {
        setEditInvoiceId(null);
        fetchInvoices();
      }
    } catch (error) {
      console.error("Error updating invoice:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddItem = () => {
    setInvoiceData((prev) => {
      const nextTeamNumber = prev.items.length + 1;
      return {
        ...prev,
        items: [
          ...prev.items,
          {
            mixDate: "",
            producer: "",
            mixType: "",
            teamName: `Team ${nextTeamNumber}`,
            division: "TBD",
            musicSurveyDue: "",
            routineSubmissionDue: "",
            estimatedCompletion: "",
            price: 0,
            quantity: 1,
          },
        ],
      };
    });
  };

  const handleRemoveItem = (indexToRemove) => {
    setInvoiceData((prev) => {
      const newItems = prev.items.filter((_, index) => index !== indexToRemove);
      // Renumber team names
      const updatedItems = newItems.map((item, index) => {
        if (item.teamName.startsWith("Team ")) {
          return { ...item, teamName: `Team ${index + 1}` };
        }
        return item;
      });
      return { ...prev, items: updatedItems };
    });
  };

  const handleItemChange = (index, field, value) => {
    setInvoiceData((prev) => {
      const newItems = [...prev.items];

      // Special handling for teamName field
      if (field === "teamName") {
        // Only update if the value is different from the default format
        if (value !== "" || !newItems[index].teamName.startsWith("Team ")) {
          newItems[index].teamName = value;
        }
      }
      // Special handling for division field
      else if (field === "division") {
        // Only update if the value is different from "TBD"
        if (value !== "" || newItems[index].division !== "TBD") {
          newItems[index].division = value;
        }
      }
      // Handle all other fields normally
      else {
        newItems[index][field] = value;
      }

      // Calculate amount if price or quantity changes
      if (field === "quantity" || field === "price") {
        newItems[index].amount =
          (newItems[index].quantity || 0) * (newItems[index].price || 0);
      }

      // Calculate subtotal and total
      const subtotal = newItems.reduce(
        (sum, item) => sum + (item.amount || 0),
        0
      );
      const total = subtotal + subtotal * (prev.tax / 100);

      return {
        ...prev,
        items: newItems,
        subtotal,
        total,
      };
    });
  };

  const handleCreateInvoice = async ({
    selectedClientId,
    newClientData,
    invoiceDates,
    invoiceData,
    isQuote,
  }) => {
    console.log("invoiceData", invoiceData);
    try {
      setLoading(true);

      // Validate client information
      if (
        !selectedClientId &&
        (!newClientData.program || !newClientData.email)
      ) {
        globalDispatch({
          type: "SHOW_TOAST",
          payload: {
            text: "Please select a client or enter new client details",
            type: "error",
          },
        });
        return;
      }

      // Get client details
      let clientDetails = null;
      if (selectedClientId) {
        clientDetails = clients.find(
          (c) => c.client_id === parseInt(selectedClientId)
        );
      }

      const payload = {
        clientId: selectedClientId ? parseInt(selectedClientId) : undefined,
        clientEmail: selectedClientId
          ? clientDetails.client_email
          : newClientData.email,
        clientName: selectedClientId
          ? clientDetails.client_full_name
          : undefined,
        programName: selectedClientId
          ? clientDetails.client_program
          : newClientData.program,
        invoiceDate: invoiceDates.invoiceDate,
        dueDate: invoiceDates.dueDate,
        items: invoiceData.items.map((item) => ({
          description: `Mix Package - ${item.mixType}`,
          quantity: item.quantity,
          price: item.price,
          mixDate: item.mixDate,
          producer: localStorage.getItem("user"),
          teamName: item.teamName,
          division: item.division,
          musicSurveyDue: item.musicSurveyDue,
          routineSubmissionDue: item.routineSubmissionDue,
          estimatedCompletion: item.estimatedCompletion,
        })),
        depositAmount: invoiceData.depositAmount || undefined,
        depositPercentage: invoiceData.depositPercentage || undefined,
        notes: invoiceData.notes,
        termsAndConditions: invoiceData.termsAndConditions,
      };

      const sdk = new MkdSDK();
      const result = await sdk.createInvoice(payload);

      const invoiceDetails = await sdk.callRawAPI(
        `/v3/api/custom/equality_record/subscription/invoice/${result.invoice_id}`,
        {},
        "GET"
      );

      if (!invoiceDetails.error) {
        // Send email to client
        const emailPayload = {
          from: "myeq@equalityrecords.com",
          to: invoiceDetails.invoice.client_email,
          subject: isQuote
            ? "New Quote Available - Action Required"
            : "New Invoice Available - Action Required",
          body: `
            <p>Hello${
              invoiceDetails.invoice.client_name
                ? ` ${invoiceDetails.invoice.client_name}`
                : ""
            },</p>
            
            <p>A new ${isQuote ? "quote" : "invoice"} has been created for ${
            invoiceDetails.invoice.program
          }.</p>
            
            <p>To view and process your ${
              isQuote ? "quote" : "invoice"
            }, please click the link below:</p>
            
            <p><a href="https://equalityrecords.com/invoice/${
              invoiceDetails.invoice.id
            }/${
            invoiceDetails.invoice.access_token
          }" style="display: inline-block; padding: 10px 20px; background-color: #3B82F6; color: white; text-decoration: none; border-radius: 5px;">View ${
            isQuote ? "Quote" : "Invoice"
          }</a></p>
            
            <p>You will be guided through the following steps:</p>
            <ol>
              <li>Review and agree to Terms of Service</li>
              <li>Complete/verify your information</li>
              <li>Review and sign Service Agreement</li>
              <li>Review ${isQuote ? "quote" : "invoice"} details</li>
              ${
                !isQuote
                  ? "<li>Process payment (deposit or full amount)</li>"
                  : ""
              }
            </ol>
            
            <p>Please complete all steps to ${
              isQuote ? "confirm the quote" : "process your payment"
            }.</p>
            
            <p><strong>Important Notes:</strong></p>
            <ul>
              <li>The link will expire in 30 days</li>
              <li>You can pay via credit card or arrange for check payment</li>
              <li>All electronic payments will include processing fees</li>
            </ul>
            
            <p>If you have any questions, please don't hesitate to contact us.</p>
            
            <p>Thank you for your business!</p>
            <p>${userDetails?.company_name || ""}</p>
          `,
        };

        const emailResult = await sendEmailAPIV3(emailPayload);

        if (emailResult.error) {
          showToast(
            globalDispatch,
            "Invoice created but email notification failed",
            4000,
            "warning"
          );
        }

        setShowNewInvoice(false);
        fetchInvoices();
        globalDispatch({
          type: "SHOW_TOAST",
          payload: {
            text: isQuote
              ? "Quote created successfully"
              : "Invoice created successfully",
            type: "success",
          },
        });

        // Reset form
        setSelectedClientId(null);
        setNewClientData({ program: "", email: "" });
        setInvoiceDates({
          invoiceDate: new Date().toISOString().split("T")[0],
          dueDate: "",
        });
      }
    } catch (error) {
      console.error("Error creating invoice:", error);
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text: `Failed to create ${isQuote ? "quote" : "invoice"}`,
          type: "error",
        },
      });
    } finally {
      setLoading(false);
    }
  };

  const handleResendLink = async (invoiceId) => {
    try {
      const sdk = new MkdSDK();

      // First get the invoice details to get client email
      const invoiceDetails = await sdk.callRawAPI(
        `/v3/api/custom/equality_record/subscription/invoice/${invoiceId}`,
        {},
        "GET"
      );

      console.log("invoiceDetails", invoiceDetails);

      if (!invoiceDetails.error) {
        // Send email with token in the link
        const emailPayload = {
          from: "myeq@equalityrecords.com",
          to: invoiceDetails.invoice.client_email,
          subject: invoiceDetails.invoice.is_quote
            ? "Quote Available - Action Required"
            : "Invoice Available - Action Required",
          body: `
              <p>Hello${
                invoiceDetails.invoice.client_name
                  ? ` ${invoiceDetails.invoice.client_name}`
                  : ""
              },</p>
              
              <p>Your ${invoiceDetails?.is_quote ? "quote" : "invoice"} for ${
            invoiceDetails.program
          } is ready for your review.</p>
              
              <p>To view and process your ${
                invoiceDetails.is_quote ? "quote" : "invoice"
              }, please click the link below:</p>
              
              <p><a href="https://equalityrecords.com/invoice/${invoiceId}/${
            invoiceDetails?.invoice?.access_token
          }" style="display: inline-block; padding: 10px 20px; background-color: #3B82F6; color: white; text-decoration: none; border-radius: 5px;">View ${
            invoiceDetails.is_quote ? "Quote" : "Invoice"
          }</a></p>
              
              <p>You will be guided through the following steps:</p>
              <ol>
                <li>Review and agree to Terms of Service</li>
                <li>Complete/verify your information</li>
                <li>Review and sign Service Agreement</li>
                <li>Review ${
                  invoiceDetails.is_quote ? "quote" : "invoice"
                } details</li>
                ${
                  !invoiceDetails.is_quote
                    ? "<li>Process payment (deposit or full amount)</li>"
                    : ""
                }
              </ol>
              
              <p>Please complete all steps to ${
                invoiceDetails.is_quote
                  ? "confirm the quote"
                  : "process your payment"
              }.</p>
              
              <p><strong>Important Notes:</strong></p>
              <ul>
          
                <li>You can pay via credit card or arrange for check payment</li>
                <li>All electronic payments will include processing fees</li>
              </ul>
              
              <p>If you have any questions, please don't hesitate to contact us.</p>
              
              <p>Thank you for your business!</p>
              <p>${userDetails?.company_name || ""}</p>
            `,
        };

        const emailResult = await sendEmailAPIV3(emailPayload);

        if (emailResult.error) {
          showToast(
            globalDispatch,
            "Failed to send email notification",
            "error"
          );
        } else {
          showToast(
            globalDispatch,
            "Invoice link resent successfully",
            "success"
          );
        }
      } else {
        showToast(globalDispatch, "Failed to get invoice details", "error");
      }
    } catch (error) {
      showToast(globalDispatch, "Failed to resend invoice link", "error");
    }
  };

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

      // Pre-fill the invoice data
      setInvoiceData({
        items: result.items.map((item) => ({
          mixDate: item.mix_date,
          producer: item.producer_id,
          mixType: item.mix_type_id,
          teamName: item.team_name,
          division: item.division,
          musicSurveyDue: item.music_survey_due,
          routineSubmissionDue: item.routine_submission_due,
          estimatedCompletion: item.estimated_completion,
          price: item.total,
        })),
        notes: result.invoice.notes,
        termsAndConditions: result.invoice.terms_and_conditions,
        depositAmount: result.invoice.deposit_amount,
        depositPercentage: result.invoice.deposit_percentage,
      });

      // Set client data
      setSelectedClientId(result.invoice.client_id);
      setNewClientData({
        program: result.invoice.program,
        email: result.invoice.client_email,
      });

      // Set dates
      setInvoiceDates({
        invoiceDate: moment(result.invoice.invoice_date).format("YYYY-MM-DD"),
        dueDate: moment(result.invoice.due_date).format("YYYY-MM-DD"),
      });

      setEditInvoiceId(invoiceId);
    } catch (error) {
      console.error("Error fetching invoice details:", error);
      showToast(globalDispatch, "Failed to fetch invoice details", "error");
    } finally {
      setLoading(false);
    }
  };

  console.log(showNewInvoice);
  return (
    <div className="p-4 mx-auto max-w-screen md:p-6 2xl:p-10">
      {showNewInvoice ? (
        <CreateInvoiceComponent
          onClose={() => {
            window.confirm("Are you sure you want to close this invoice?") &&
              setShowNewInvoice(false);
          }}
          onSubmit={handleCreateInvoice}
          userDetails={userDetails}
          clients={clients}
          mixTypes={mixTypes}
          loading={loading}
        />
      ) : editInvoiceId ? (
        <EditInvoiceComponent
          id={editInvoiceId}
          onClose={() => {
            window.confirm("Are you sure you want to close this invoice?") &&
              setEditInvoiceId(null);
          }}
          onSubmit={handleUpdateInvoice}
          onResend={() => handleResendLink(editInvoiceId)}
          clients={clients}
          mixTypes={mixTypes}
        />
      ) : (
        <>
          <div className="mb-5 rounded border shadow-default border-stroke/50 bg-boxdark">
            <div className="flex justify-between items-center px-4 py-5 mb-6 md:px-6 2xl:px-9">
              <div>
                <h2 className="text-2xl font-bold text-white">Invoices</h2>
                <p className="mt-1 text-lg text-bodydark">
                  Manage your invoices
                </p>
              </div>
              <button
                onClick={() => {
                  setEditInvoiceId(null);
                  setShowNewInvoice(!showNewInvoice);
                }}
                className="flex gap-2 items-center px-4 py-2 font-medium text-white rounded-lg bg-primary hover:bg-opacity-90"
              >
                <Plus className="w-5 h-5" />
                New Invoice
              </button>
            </div>
          </div>
          <div className="rounded border shadow-default border-strokedark bg-boxdark">
            {/* Header Section */}
            <div className="flex justify-between items-center px-4 border-b border-strokedark md:px-6 2xl:px-9">
              <h4 className="my-3 text-2xl font-semibold text-white">
                Invoices
              </h4>
            </div>

            <div className="p-4 md:p-6 2xl:p-10">
              <div className="custom-overflow text-[12p min-h-[140px] overflow-x-auto">
                <table className="w-full table-auto">
                  <thead className="bg-meta-4">
                    <tr>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                        Invoice ID
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                        Client Name
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                        Program
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                        Email
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-right uppercase text-bodydark1">
                        Total
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-right uppercase text-bodydark1">
                        Deposit
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-center uppercase text-bodydark1">
                        Status
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                        Created
                      </th>
                      <th className="px-4 py-3 text-xs font-medium tracking-wider text-center uppercase text-bodydark1">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  {!loading && invoices.length > 0 ? (
                    <tbody className="text-white">
                      {invoices.map((invoice) => (
                        <tr
                          key={invoice.id}
                          className="text-xs border-b cursor-pointer border-strokedark hover:bg-primary/5"
                          onClick={() =>
                            navigate(`/member/invoice/${invoice.id}`)
                          }
                        >
                          <td className="px-4 py-4 whitespace-nowrap">
                            #{invoice.id}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            {invoice.client_name}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            {invoice.program}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            {invoice.client_email}
                          </td>
                          <td className="px-4 py-4 text-right whitespace-nowrap">
                            ${parseFloat(invoice.total).toFixed(2)}
                          </td>
                          <td className="px-4 py-4 text-right whitespace-nowrap">
                            <div>
                              ${parseFloat(invoice.deposit_amount).toFixed(2)}
                              <span className="ml-1 text-xs text-bodydark2">
                                ({invoice.deposit_percentage}%)
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <div className="flex justify-center">
                              <span
                                className={`inline-block rounded px-2.5 py-0.5 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>
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            {moment(new Date(invoice.create_at)).format(
                              "MMM DD, YYYY"
                            )}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <div className="flex gap-2 justify-center items-center">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleEditInvoice(invoice.id);
                                }}
                                className="bg-primary px-3 py-1.5 text-sm font-medium text-white hover:bg-opacity-90"
                              >
                                Edit
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  ) : loading ? (
                    <tbody>
                      <tr>
                        <td colSpan={9} className="text-center">
                          <div className="flex h-[140px] items-center justify-center">
                            <ClipLoader color="#fff" size={30} />
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  ) : (
                    <tbody>
                      <tr>
                        <td colSpan={9} className="text-center">
                          <div className="flex h-[140px] items-center justify-center">
                            <span className="text-bodydark">
                              No invoices found
                            </span>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  )}
                </table>
              </div>

              {/* Pagination */}
              {pageCount > 1 && (
                <div className="flex justify-between items-center px-4 py-5">
                  <div className="flex gap-4 items-center">
                    <button
                      onClick={() =>
                        setCurrentPage((prev) => Math.max(prev - 1, 1))
                      }
                      disabled={currentPage === 1}
                      className="flex justify-center items-center px-4 py-2 text-white rounded bg-primary hover:bg-opacity-90 disabled:bg-opacity-50"
                    >
                      Previous
                    </button>
                    <button
                      onClick={() =>
                        setCurrentPage((prev) => Math.min(prev + 1, pageCount))
                      }
                      disabled={currentPage === pageCount}
                      className="flex justify-center items-center px-4 py-2 text-white rounded bg-primary hover:bg-opacity-90 disabled:bg-opacity-50"
                    >
                      Next
                    </button>
                  </div>
                  <span className="text-sm text-bodydark2">
                    Page {currentPage} of {pageCount} ({dataTotal} total)
                  </span>
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default InvoicePage;
