import React, { useState, useEffect } from "react";
import { GlobalContext, showToast } from "Src/globalContext";
import CustomSelect2 from "Components/CustomSelect2";
import moment from "moment";
import { ArrowLeft, Plus, Trash2 } from "lucide-react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import MkdSDK from "Utils/MkdSDK";
import { SingleDatePicker } from "react-dates";

const EditInvoiceComponent = ({
  id,
  onClose,
  userDetails,
  clients,
  mixTypes,
  onSubmit,
  onResend,
}) => {
  const [invoiceData, setInvoiceData] = useState({
    notes: "",
    termsAndConditions: "",
    depositAmount: 0,
    depositPercentage: 30,
    items: [],
  });
  const [focusedInput, setFocusedInput] = React.useState({
    date: null,
    dueDate: null,
    musicSurveyDue: {},
    submission: {},
    estimatedCompletion: {},
  });
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [selectedClientId, setSelectedClientId] = useState("");
  const [loading, setLoading] = useState(true);
  const [invoiceDates, setInvoiceDates] = useState({
    invoiceDate: new Date().toISOString().split("T")[0],
    dueDate: "",
  });

  const [isQuote, setIsQuote] = useState(false);

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

    const date = moment(mixDate);

    // Parse settings
    const surveySettings = userDetails?.survey
      ? JSON.parse(userDetails.survey)
      : { weeks: 8, day: "Monday" };
    const routineSettings = userDetails?.routine_submission_date
      ? JSON.parse(userDetails.routine_submission_date)
      : { weeks: 1, day: "Monday" };
    const deliverySettings = userDetails?.estimated_delivery
      ? JSON.parse(userDetails.estimated_delivery)
      : { weeks: 1, day: "Friday" };

    // 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,
      };
    });
  };

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

        setSelectedClientId(result.invoice.client_id?.toString() || "");

        const formattedData = {
          notes: result.invoice.notes || "",
          termsAndConditions: result.invoice.terms_and_conditions || "",
          depositAmount: parseFloat(result.invoice.deposit_amount) || 0,
          depositPercentage:
            parseFloat(result.invoice.deposit_percentage) || 30,
          items: result.items.map((item) => ({
            id: item.id,
            mixDate: moment(item.mix_date).format("YYYY-MM-DD"),
            producer: item.producer || "",
            mixType: item.description?.split(" - ")[1] || "",
            teamName: item.team_name,
            division: item.division,
            musicSurveyDue: moment(item.music_survey_due).format("YYYY-MM-DD"),
            routineSubmissionDue: moment(item.routine_submission_due).format(
              "YYYY-MM-DD"
            ),
            estimatedCompletion: moment(item.estimated_completion).format(
              "YYYY-MM-DD"
            ),
            price: parseFloat(item.price) || 0,
            quantity: item.quantity || 1,
            amount: parseFloat(item.total) || 0,
          })),
        };

        setInvoiceData(formattedData);

        setInvoiceDates({
          invoiceDate: moment(result.invoice.invoice_date).format("YYYY-MM-DD"),
          dueDate: result.invoice.due_date
            ? moment(result.invoice.due_date).format("YYYY-MM-DD")
            : "",
        });
      } catch (error) {
        console.error("Error fetching invoice:", error);
        showToast(globalDispatch, "Failed to fetch invoice details", "error");
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchInvoiceDetails();
    }
  }, [id]);

  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);
      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];

      if (field === "teamName") {
        if (value !== "" || !newItems[index].teamName.startsWith("Team ")) {
          newItems[index].teamName = value;
        }
      } else if (field === "division") {
        if (value !== "" || newItems[index].division !== "TBD") {
          newItems[index].division = value;
        }
      } else {
        newItems[index][field] = value;
      }

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

      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 handleUpdateInvoice = async () => {
    if (!selectedClientId) {
      showToast(globalDispatch, "Please select a client", "error");
      return;
    }

    onSubmit({
      selectedClientId,
      invoiceDates,
      invoiceData,
      isQuote,
    });
  };

  return (
    <div className="rounded-lg bg-boxdark p-6">
      {/* Header with back button */}
      <div className="mb-6 flex items-center justify-between">
        <button
          onClick={onClose}
          className="flex items-center gap-2 text-white hover:text-primary"
        >
          <ArrowLeft className="h-5 w-5" />
          Back to Invoices
        </button>
        <h2 className="text-2xl font-bold text-white">Edit Invoice #{id}</h2>
        <button
          onClick={onResend}
          disabled={loading}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 font-medium text-white hover:bg-opacity-90"
        >
          <FontAwesomeIcon icon="paper-plane" className="h-4 w-4" />
          Resend Link
        </button>
      </div>

      {/* Client Information */}
      <div className="mb-3 pb-2">
        <h3 className="mb-2 text-base font-semibold text-white">
          Client Information
        </h3>
        <div className="flex items-center gap-4">
          <div className="w-1/3">
            <select
              value={selectedClientId || ""}
              onChange={(e) => setSelectedClientId(e.target.value)}
              className="h-8 w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-3 py-1 text-sm text-white"
              disabled
            >
              <option value="">Select Client</option>
              {clients.map((client) => (
                <option key={client.client_id} value={client.client_id}>
                  {client.client_program}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Invoice Dates Section */}
      <div className="mb-3 flex items-center justify-start pb-3">
        <div className="flex items-center justify-normal gap-3">
          <div>
            <label className="mb-1.5 block font-medium text-white">
              Invoice Date
            </label>
            <input
              type="date"
              value={invoiceDates.invoiceDate}
              onChange={(e) =>
                setInvoiceDates((prev) => ({
                  ...prev,
                  invoiceDate: e.target.value,
                }))
              }
              className="h-8 w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-5 py-1.5 text-[12px] text-white"
            />
          </div>
        </div>
      </div>

      {/* Invoice Items */}
      <div className="mb-3">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-base font-semibold text-white">Invoice Items</h3>
        </div>
        <div className="custom-overflow min-h-[140px] overflow-x-auto">
          <table className="relative w-full table-auto">
            <thead className="bg-meta-4">
              <tr>
                <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">
                  Producer
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                  Mix Type
                </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 / Submission Due / Est. Completion
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                  Price
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="text-white">
              {invoiceData.items.map((item, index) => (
                <tr
                  key={index}
                  className="border-b border-stroke/50 text-[12px] hover:bg-primary/5"
                >
                  <td className="row-date2 whitespace-nowrap px-4 py-3">
                    <SingleDatePicker
                      id={`mixDate_${index}`}
                      date={item.mixDate ? moment(item.mixDate) : null}
                      onDateChange={(date) => {
                        handleItemChange(
                          index,
                          "mixDate",
                          date ? date.format("YYYY-MM-DD") : null
                        );
                        calculateDates(
                          date ? date.format("YYYY-MM-DD") : null,
                          index
                        );
                      }}
                      focused={focusedInput[`mixDate_${index}`]}
                      onFocusChange={({ focused }) =>
                        setFocusedInput((prev) => ({
                          ...prev,
                          [`mixDate_${index}`]: focused,
                        }))
                      }
                      numberOfMonths={1}
                      isOutsideRange={() => false}
                      displayFormat="MM-DD-YYYY"
                      placeholder="Select Mix Date"
                      readOnly={true}
                      customInputIcon={null}
                      noBorder={true}
                      block
                      className="w-full rounded border border-stroke/50"
                    />
                  </td>
                  <td className="whitespace-nowrap px-4 py-3">
                    <input
                      type="text"
                      defaultValue={
                        userDetails?.first_name + " " + userDetails?.last_name
                      }
                      disabled={true}
                      className="w-full min-w-[120px] rounded border-[1.5px] border-stroke/50 bg-transparent px-2 py-1 text-[12px] text-white"
                    />
                  </td>
                  <td className="whitespace-nowrap px-4 py-3">
                    <CustomSelect2
                      textClass="!text-[12px]"
                      value={item.mixType}
                      onChange={(value) => {
                        handleItemChange(index, "mixType", value);
                        const selectedMixType = mixTypes.find(
                          (mt) => mt.id === parseInt(value)
                        );
                        if (selectedMixType) {
                          handleItemChange(
                            index,
                            "price",
                            selectedMixType.price
                          );
                        }
                      }}
                      className="h-[36px] !w-[120px] rounded border-[1.5px] border-stroke/50 bg-transparent px-5 py-3 !text-[12px] outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:focus:border-primary"
                    >
                      <option value="">Select Mix Type</option>
                      {mixTypes.map((mixType) => (
                        <option key={mixType.id} value={mixType.id}>
                          {mixType.name} - ${mixType.price}
                        </option>
                      ))}
                    </CustomSelect2>
                  </td>
                  <td className="whitespace-nowrap px-4 py-3">
                    <input
                      type="text"
                      value={item.teamName}
                      onChange={(e) =>
                        handleItemChange(index, "teamName", e.target.value)
                      }
                      onFocus={(e) => {
                        if (e.target.value.startsWith("Team ")) {
                          handleItemChange(index, "teamName", "");
                        }
                      }}
                      className="w-full min-w-[120px] rounded border-[1.5px] border-stroke/50 bg-transparent px-2 py-1 text-[12px] text-white"
                    />
                  </td>
                  <td className="whitespace-nowrap px-4 py-3">
                    <input
                      type="text"
                      value={item.division}
                      onChange={(e) =>
                        handleItemChange(index, "division", e.target.value)
                      }
                      onFocus={(e) => {
                        if (e.target.value === "TBD") {
                          handleItemChange(index, "division", "");
                        }
                      }}
                      className="w-full min-w-[120px] rounded border-[1.5px] border-stroke/50 bg-transparent px-2 py-1 text-[12px] text-white"
                    />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex flex-col gap-2">
                      <div className="row-date flex flex-row items-center justify-between gap-1">
                        <label className="mb-1 whitespace-nowrap text-xs text-gray-400">
                          Sur Due
                        </label>
                        <SingleDatePicker
                          id={`musicSurveyDue_${index}`}
                          date={
                            item.musicSurveyDue
                              ? moment(item.musicSurveyDue)
                              : null
                          }
                          onDateChange={(date) =>
                            handleItemChange(
                              index,
                              "musicSurveyDue",
                              date ? date.format("YYYY-MM-DD") : null
                            )
                          }
                          focused={focusedInput[`musicSurveyDue_${index}`]}
                          onFocusChange={({ focused }) =>
                            setFocusedInput((prev) => ({
                              ...prev,
                              [`musicSurveyDue_${index}`]: focused,
                            }))
                          }
                          numberOfMonths={1}
                          isOutsideRange={() => false}
                          displayFormat="MM-DD-YYYY"
                          placeholder="Select Due Date"
                          readOnly={true}
                          customInputIcon={null}
                          noBorder={true}
                          block
                          className="w-full rounded border border-stroke/50"
                        />
                      </div>
                      <div className="row-date flex flex-row items-center justify-between gap-1">
                        <label className="mb-1 whitespace-nowrap text-xs text-gray-400">
                          Sub Due
                        </label>
                        <SingleDatePicker
                          id={`routineSubmissionDue_${index}`}
                          date={
                            item.routineSubmissionDue
                              ? moment(item.routineSubmissionDue)
                              : null
                          }
                          onDateChange={(date) =>
                            handleItemChange(
                              index,
                              "routineSubmissionDue",
                              date ? date.format("YYYY-MM-DD") : null
                            )
                          }
                          focused={
                            focusedInput[`routineSubmissionDue_${index}`]
                          }
                          onFocusChange={({ focused }) =>
                            setFocusedInput((prev) => ({
                              ...prev,
                              [`routineSubmissionDue_${index}`]: focused,
                            }))
                          }
                          numberOfMonths={1}
                          isOutsideRange={() => false}
                          displayFormat="MM-DD-YYYY"
                          placeholder="Select Due Date"
                          readOnly={true}
                          customInputIcon={null}
                          noBorder={true}
                          block
                          className="w-full rounded border border-stroke/50"
                        />
                      </div>
                      <div className="row-date flex flex-row items-center justify-between gap-1">
                        <label className="mb-1 whitespace-nowrap text-xs text-gray-400">
                          Est. Comp
                        </label>
                        <SingleDatePicker
                          id={`estimatedCompletion_${index}`}
                          date={
                            item.estimatedCompletion
                              ? moment(item.estimatedCompletion)
                              : null
                          }
                          onDateChange={(date) =>
                            handleItemChange(
                              index,
                              "estimatedCompletion",
                              date ? date.format("YYYY-MM-DD") : null
                            )
                          }
                          focused={focusedInput[`estimatedCompletion_${index}`]}
                          onFocusChange={({ focused }) =>
                            setFocusedInput((prev) => ({
                              ...prev,
                              [`estimatedCompletion_${index}`]: focused,
                            }))
                          }
                          numberOfMonths={1}
                          isOutsideRange={() => false}
                          displayFormat="MM-DD-YYYY"
                          placeholder="Select Completion Date"
                          readOnly={true}
                          customInputIcon={null}
                          noBorder={true}
                          block
                          className="w-full rounded border border-stroke/50"
                        />
                      </div>
                    </div>
                  </td>
                  <td className="row-date whitespace-nowrap px-4 py-3">
                    <input
                      type="number"
                      value={item.price}
                      onChange={(e) =>
                        handleItemChange(
                          index,
                          "price",
                          parseFloat(e.target.value)
                        )
                      }
                      className="w-24 rounded border border-stroke/50 bg-transparent px-2 py-1 text-white"
                      min="0"
                      placeholder="$0.00"
                    />
                  </td>
                  <td className="whitespace-nowrap px-4 py-3">
                    <button
                      onClick={() => handleRemoveItem(index)}
                      className="p-1 text-danger hover:text-danger/80"
                    >
                      <Trash2 className="h-5 w-5" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="mt-2 flex justify-end">
          <button
            onClick={handleAddItem}
            className="flex items-center gap-2 rounded bg-primary px-4 py-1 text-sm font-medium text-white hover:bg-boxdark/80"
          >
            <Plus className="h-5 w-5" />
            Add Row
          </button>
        </div>
      </div>

      {/* Deposit and Terms Section */}
      <div className="mt-6 grid grid-cols-3 gap-6">
        {/* Left Column - Deposit Settings */}
        <div className="space-y-2">
          <h3 className="text-base font-semibold text-white">
            Deposit Settings
          </h3>
          <div className="space-y-2">
            <div>
              <label className="mb-1.5 block text-sm text-white">Type</label>
              <select
                value={
                  invoiceData.depositPercentage > 0 ? "percentage" : "amount"
                }
                onChange={(e) => {
                  const isAmount = e.target.value === "amount";
                  setInvoiceData((prev) => ({
                    ...prev,
                    depositAmount: isAmount ? 0 : 0,
                    depositPercentage: isAmount
                      ? 0
                      : prev.depositPercentage ||
                        userDetails?.deposit_percent ||
                        30,
                  }));
                }}
                className="h-9 w-full rounded border border-stroke bg-transparent px-3 py-1 text-sm text-white"
              >
                <option value="amount">Fixed Amount</option>
                <option value="percentage">Percentage</option>
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm text-white">
                {invoiceData.depositPercentage > 0
                  ? "Percentage (%)"
                  : "Amount ($)"}
              </label>
              <input
                type="number"
                value={
                  invoiceData.depositPercentage > 0
                    ? invoiceData.depositPercentage
                    : invoiceData.depositAmount
                }
                onChange={(e) => {
                  const value = parseFloat(e.target.value);
                  const isPercentage = invoiceData.depositPercentage > 0;
                  setInvoiceData((prev) => ({
                    ...prev,
                    depositAmount: isPercentage ? 0 : value,
                    depositPercentage: isPercentage ? value : 0,
                  }));
                }}
                placeholder={
                  invoiceData.depositPercentage > 0
                    ? `Default: ${userDetails?.deposit_percent || 30}%`
                    : "Enter amount"
                }
                className="h-9 w-full rounded border border-stroke bg-transparent px-3 py-1 text-sm text-white"
                min="0"
                max={invoiceData.depositPercentage > 0 ? 100 : undefined}
              />
            </div>
          </div>
        </div>

        {/* Middle and Right Columns - Notes and Terms */}
        <div className="col-span-2 space-y-2">
          <h3 className="text-base font-semibold text-white">Notes & Terms</h3>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1.5 block text-sm text-white">Notes</label>
              <textarea
                value={invoiceData.notes}
                onChange={(e) =>
                  setInvoiceData((prev) => ({ ...prev, notes: e.target.value }))
                }
                className="h-[110px] w-full rounded border border-stroke bg-transparent px-3 py-2 text-sm text-white"
                rows="4"
                placeholder="Add any additional notes..."
              />
            </div>
            <div>
              <label className="mb-1.5 block text-sm text-white">
                Terms and Conditions
              </label>
              <textarea
                value={invoiceData.termsAndConditions}
                onChange={(e) =>
                  setInvoiceData((prev) => ({
                    ...prev,
                    termsAndConditions: e.target.value,
                  }))
                }
                className="h-[110px] w-full rounded border border-stroke bg-transparent px-3 py-2 text-sm text-white"
                rows="4"
                placeholder={
                  userDetails?.contract_agreement
                    ? "Terms and conditions loaded from your settings"
                    : "Add terms and conditions..."
                }
              />
            </div>
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="mt-6 flex justify-end gap-4">
        <button
          onClick={onClose}
          className="rounded-lg border border-stroke bg-opacity-80 px-6 py-2 text-bodydark"
        >
          Cancel
        </button>

        <button
          onClick={() => {
            setIsQuote(false);
            handleUpdateInvoice();
          }}
          disabled={loading}
          className="rounded-lg bg-primary px-6 py-2 text-white hover:bg-opacity-90 disabled:opacity-50"
        >
          {loading ? "Updating..." : "Update Invoice"}
        </button>
      </div>
    </div>
  );
};

export default EditInvoiceComponent;
