import React, { useState } 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 { SingleDatePicker } from "react-dates";

const CreateInvoiceComponent = ({
  onClose,
  userDetails,
  clients,
  mixTypes,
  loading,
  onSubmit,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [selectedClientId, setSelectedClientId] = useState("");
  const [producers, setProducers] = useState([]);
  const [focusedInput, setFocusedInput] = React.useState({
    date: null,
    dueDate: null,
    musicSurveyDue: {},
    submission: {},
    estimatedCompletion: {},
  });
  const [newClientData, setNewClientData] = useState({
    program: "",
    email: "",
  });
  const [invoiceItems, setInvoiceItems] = useState([]);
  const [invoiceDates, setInvoiceDates] = useState({
    invoiceDate: new Date().toISOString().split("T")[0],
    dueDate: "",
  });

  console.log(invoiceItems);
  const [invoiceData, setInvoiceData] = useState({
    notes: "",
    termsAndConditions:
      userDetails?.contract_agreement
        ?.replace(/<[^>]*>/g, "")
        .replace(/&nbsp;/g, " ") || "",
    depositAmount: 0,
    depositPercentage: userDetails?.deposit_percent || 30,
    items: [
      {
        mixDate: "",
        producer: "",
        mixType: "",
        teamName: "Team 1",
        division: "TBD",
        musicSurveyDue: "",
        routineSubmissionDue: "",
        estimatedCompletion: "",
        price: 0,
        quantity: 1,
      },
    ],
  });
  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,
      };
    });
  };

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

  console.log(invoiceData);

  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 handleCreateInvoice = async () => {
    if (!selectedClientId && (!newClientData.program || !newClientData.email)) {
      showToast(
        globalDispatch,
        "Please select a client or enter new client details",
        "error"
      );
      return;
    }
    console.log("jsjsj");

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

  return (
    <div className="p-6 rounded-lg bg-boxdark">
      {/* Header with back button */}
      <div className="flex justify-between items-center mb-6">
        <button
          onClick={onClose}
          className="flex gap-2 items-center text-white hover:text-primary"
        >
          <ArrowLeft className="w-5 h-5" />
          Back to Invoices
        </button>
        <h2 className="text-2xl font-bold text-white">New Invoice</h2>
      </div>

      {/* Client Information */}
      <div className="pb-2 mb-3">
        <h3 className="mb-2 text-base font-semibold text-white">
          Client Information
        </h3>
        <div className="flex gap-4 items-center">
          <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"
            >
              <option value="">Select Existing Client</option>
              {clients.map((client) => (
                <option key={client.client_id} value={client.client_id}>
                  {client.client_program}
                </option>
              ))}
            </select>
          </div>

          <div className="flex items-center">
            <span className="text-sm font-medium text-bodydark2">OR</span>
          </div>

          <div className="w-1/3">
            <input
              type="text"
              value={newClientData.program}
              onChange={(e) =>
                setNewClientData((prev) => ({
                  ...prev,
                  program: e.target.value,
                }))
              }
              disabled={selectedClientId}
              className="h-8 w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-3 py-1 text-sm text-white"
              placeholder="New Client Program Name"
            />
          </div>

          <div className="w-1/3">
            <input
              type="email"
              value={newClientData.email}
              onChange={(e) =>
                setNewClientData((prev) => ({
                  ...prev,
                  email: e.target.value,
                }))
              }
              disabled={selectedClientId}
              className="h-8 w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-3 py-1 text-sm text-white"
              placeholder="New Client Email"
            />
          </div>
        </div>
      </div>

      {/* Invoice Dates Section */}
      <div className="flex justify-start items-center pb-3 mb-3">
        <div className="flex gap-3 items-center justify-normal">
          <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>
            <label className="mb-1.5 block font-medium text-white">
              Invoice Due Date
            </label>
            <input
              type="date"
              value={invoiceDates.invoiceDueDate}
              onChange={(e) =>
                setInvoiceDates((prev) => ({
                  ...prev,

                  invoiceDueDate: 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="flex justify-between items-center mb-4">
          <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-xs font-medium tracking-wider text-left text-white uppercase">
                  Mix Date
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Producer
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Mix Type
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Team Name
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Division
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Survey Due / Submission Due / Est. Completion
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  Price
                </th>
                <th className="px-4 py-3 text-xs font-medium tracking-wider text-left text-white uppercase">
                  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="px-4 py-3 whitespace-nowrap row-date2">
                    <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="px-4 py-3 whitespace-nowrap">
                    <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="px-4 py-3 whitespace-nowrap">
                    <CustomSelect2
                      textClass="!text-[12px]"
                      value={item.mixType}
                      onChange={(value) => {
                        handleItemChange(index, "mixType", value);
                        // Set price based on selected mix type
                        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="px-4 py-3 whitespace-nowrap">
                    <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="px-4 py-3 whitespace-nowrap">
                    <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="flex flex-row gap-1 justify-between items-center row-date">
                        <label className="mb-1 text-xs text-gray-400 whitespace-nowrap">
                          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="flex flex-row gap-1 justify-between items-center row-date">
                        <label className="mb-1 text-xs text-gray-400 whitespace-nowrap">
                          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="flex flex-row gap-1 justify-between items-center row-date">
                        <label className="mb-1 text-xs text-gray-400 whitespace-nowrap">
                          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="px-4 py-3 whitespace-nowrap row-date">
                    <input
                      type="number"
                      value={item.price}
                      onChange={(e) =>
                        handleItemChange(
                          index,
                          "price",
                          parseFloat(e.target.value)
                        )
                      }
                      className="px-2 py-1 w-24 text-white bg-transparent rounded border border-stroke/50"
                      min="0"
                      placeholder="$0.00"
                    />
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <button
                      onClick={() => handleRemoveItem(index)}
                      className="p-1 text-danger hover:text-danger/80"
                    >
                      <Trash2 className="w-5 h-5" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="flex justify-end mt-2">
          <button
            onClick={handleAddItem}
            className="flex gap-2 items-center px-4 py-1 text-sm font-medium text-white rounded bg-primary hover:bg-primary/80"
          >
            <Plus className="w-5 h-5" />
            Add Row
          </button>
        </div>
      </div>

      {/* Deposit and Terms Section */}
      <div className="grid grid-cols-3 gap-6 mt-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="px-3 py-1 w-full h-9 text-sm text-white bg-transparent rounded border border-stroke"
              >
                <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="px-3 py-1 w-full h-9 text-sm text-white bg-transparent rounded border border-stroke"
                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="flex gap-4 justify-end mt-6">
        <button
          onClick={onClose}
          className="px-6 py-2 bg-opacity-80 rounded-lg border border-stroke text-bodydark"
        >
          Cancel
        </button>

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

export default CreateInvoiceComponent;
