import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useState, useEffect } from "react";
import { Plus, Trash2 } from "Assets/svgs";
import moment from "moment";
import CustomSelect2 from "Components/CustomSelect2";
import { SingleDatePicker } from "react-dates";

const NewInvoiceModal = ({
  isOpen,
  onClose,
  userDetails,
  clients,
  producers,
  mixTypes,
  onCreateInvoice,
  loading,
}) => {
  const [selectedClientId, setSelectedClientId] = useState("");
  const [newClientData, setNewClientData] = useState({
    program: "",
    email: "",
  });
  const [invoiceDates, setInvoiceDates] = useState({
    invoiceDate: moment().format("YYYY-MM-DD"),
    dueDate: moment().add(30, "days").format("YYYY-MM-DD"),
  });
  const [invoiceData, setInvoiceData] = useState({
    items: [],
    depositAmount: 0,
    depositPercentage: 50,
    notes: "",
    termsAndConditions: "",
  });
  const [focusedInput, setFocusedInput] = useState({});
  const [isQuote, setIsQuote] = useState(false);

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

  const handleRemoveItem = (indexToRemove) => {
    setInvoiceData((prev) => ({
      ...prev,
      items: prev.items.filter((_, index) => index !== indexToRemove),
    }));
  };

  const handleItemChange = (index, field, value) => {
    setInvoiceData((prev) => ({
      ...prev,
      items: prev.items.map((item, i) =>
        i === index ? { ...item, [field]: value } : item
      ),
    }));
  };

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

    const surveyDue = moment(mixDate).subtract(14, "days").format("YYYY-MM-DD");
    const routineDue = moment(mixDate).subtract(7, "days").format("YYYY-MM-DD");
    const completion = moment(mixDate).add(14, "days").format("YYYY-MM-DD");

    setInvoiceData((prev) => ({
      ...prev,
      items: prev.items.map((item, i) =>
        i === index
          ? {
              ...item,
              musicSurveyDue: surveyDue,
              routineSubmissionDue: routineDue,
              estimatedCompletion: completion,
            }
          : item
      ),
    }));
  };

  if (!isOpen) return null;

  return (
    <div className="custom-overflow fixed inset-0 z-[52] flex h-full w-full items-center justify-center overflow-y-auto px-4 py-8 backdrop-blur-sm">
      <div className="shadow-default relative w-full max-w-[1200px] rounded border border-strokedark bg-boxdark p-4 sm:p-8 dark:border-strokedark dark:bg-boxdark">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-strokedark pb-4 dark:border-strokedark">
          <h3 className="text-2xl font-semibold text-white dark:text-white">
            Create New Invoice
          </h3>
          <button
            onClick={onClose}
            className="text-white hover:text-white dark:text-gray-400 dark:hover:text-white"
          >
            <FontAwesomeIcon icon="close" className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <div className="mt-6 max-h-[calc(100vh-200px)] overflow-y-auto">
          {/* Producer Information */}
          {userDetails && (
            <div className="mb-8 grid grid-cols-2 gap-6 rounded-lg border border-stroke/50 p-6">
              <div className="flex items-start gap-4">
                {userDetails.photo && (
                  <img
                    src={userDetails.photo}
                    alt="Producer"
                    className="h-16 w-16 rounded-full object-cover"
                  />
                )}
                <div>
                  <h3 className="text-xl font-semibold text-white">
                    {userDetails.first_name} {userDetails.last_name}
                  </h3>
                  <p className="text-bodydark">{userDetails.email}</p>
                  <p className="text-bodydark">{userDetails.company_name}</p>
                  <p className="text-bodydark">{userDetails.office_email}</p>
                </div>
              </div>
              <div className="flex justify-end">
                {userDetails.company_logo && (
                  <img
                    src={userDetails.company_logo}
                    alt="Company Logo"
                    className="h-20 object-contain"
                  />
                )}
              </div>
            </div>
          )}

          {/* Client Selection */}
          <div className="mb-8 border-b border-stroke/50 pb-8">
            <h3 className="mb-4 text-xl font-semibold text-white">
              Client Information
            </h3>
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Select Existing Client
                </label>
                <CustomSelect2
                  value={selectedClientId}
                  onChange={(value) => setSelectedClientId(value)}
                  options={clients.map((client) => ({
                    value: client.client_id,
                    label: client.client_program,
                  }))}
                  label="Select Client"
                />
              </div>

              <div>
                <p className="mb-2.5 font-medium text-white">- OR -</p>
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  New Client Program Name
                </label>
                <input
                  type="text"
                  value={newClientData.program}
                  onChange={(e) =>
                    setNewClientData((prev) => ({
                      ...prev,
                      program: e.target.value,
                    }))
                  }
                  disabled={selectedClientId}
                  className="w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-5 py-3 text-white"
                  placeholder="Enter program name"
                />
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  New Client Email
                </label>
                <input
                  type="email"
                  value={newClientData.email}
                  onChange={(e) =>
                    setNewClientData((prev) => ({
                      ...prev,
                      email: e.target.value,
                    }))
                  }
                  disabled={selectedClientId}
                  className="w-full rounded border-[1.5px] border-stroke/50 bg-form-input px-5 py-3 text-white"
                  placeholder="Enter email address"
                />
              </div>
            </div>
          </div>

          {/* Invoice Items */}
          <div className="mb-8">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-xl font-semibold text-white">
                Invoice Items
              </h3>
              <button
                onClick={handleAddItem}
                className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 font-medium text-white hover:bg-opacity-90"
              >
                <Plus className="h-5 w-5" />
                Add Row
              </button>
            </div>
            {/* Invoice Items Table */}
            <div className="custom-overflow min-h-[140px] overflow-x-auto">
              {/* ... Table content (same as before) ... */}
            </div>
          </div>

          {/* Deposit Section */}
          <div className="mt-6 grid grid-cols-2 gap-6">
            <div>
              <label className="mb-2 block text-white">Deposit Type</label>
              <CustomSelect2
                value={invoiceData.depositAmount ? "amount" : "percentage"}
                onChange={(value) => {
                  if (value === "amount") {
                    setInvoiceData((prev) => ({
                      ...prev,
                      depositPercentage: 0,
                    }));
                  } else {
                    setInvoiceData((prev) => ({ ...prev, depositAmount: 0 }));
                  }
                }}
                options={[
                  { value: "percentage", label: "Percentage" },
                  { value: "amount", label: "Fixed Amount" },
                ]}
              />
            </div>
            <div>
              <label className="mb-2 block text-white">
                {invoiceData.depositAmount
                  ? "Deposit Amount"
                  : "Deposit Percentage"}
              </label>
              <input
                type="number"
                value={
                  invoiceData.depositAmount || invoiceData.depositPercentage
                }
                onChange={(e) => {
                  const value = parseFloat(e.target.value);
                  if (invoiceData.depositAmount) {
                    setInvoiceData((prev) => ({
                      ...prev,
                      depositAmount: value,
                    }));
                  } else {
                    setInvoiceData((prev) => ({
                      ...prev,
                      depositPercentage: value,
                    }));
                  }
                }}
                className="w-full rounded-lg border border-stroke bg-transparent px-4 py-2 text-white"
                min="0"
                max={invoiceData.depositAmount ? undefined : 100}
              />
            </div>
          </div>

          {/* Notes and Terms */}
          <div className="mt-6 grid grid-cols-1 gap-6">
            <div>
              <label className="mb-2 block text-white">Notes</label>
              <textarea
                value={invoiceData.notes}
                onChange={(e) =>
                  setInvoiceData((prev) => ({ ...prev, notes: e.target.value }))
                }
                className="w-full rounded-lg border border-stroke bg-transparent px-4 py-2 text-white"
                rows="3"
                placeholder="Add any additional notes..."
              />
            </div>
            <div>
              <label className="mb-2 block text-white">
                Terms and Conditions
              </label>
              <textarea
                value={invoiceData.termsAndConditions}
                onChange={(e) =>
                  setInvoiceData((prev) => ({
                    ...prev,
                    termsAndConditions: e.target.value,
                  }))
                }
                className="w-full rounded-lg border border-stroke bg-transparent px-4 py-2 text-white"
                rows="3"
                placeholder="Add terms and conditions..."
              />
            </div>
          </div>

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

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

export default NewInvoiceModal;
