import React, { useEffect, useState } from "react";
import moment from "moment";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  retrieveAllSettingsAPI,
  createOrUpdateAllSettingsAPI,
  retrieveSummaryAPI,
} from "Src/services/settingService";

import { calculateNetTotal, calculateManagementDiscount } from "Utils/utils";
import PhotoUpload from "Components/PhotoUpload";
import {
  getUserDetailsByIdAPI,
  updateUserDetailsAPI,
} from "Src/services/userService";
import LogoUpload from "Components/logoUpload";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import EditPolicyPdfUpload from "Components/EditPolicyPdfUpload";
import { FileText } from "lucide-react";
import CustomSelect2 from "Components/CustomSelect2";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as yup from "yup";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import SunEditor from "suneditor-react";
import "suneditor/dist/css/suneditor.min.css";
import MkdSDK from "Utils/MkdSDK";

const ListMemberSettingPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const userId = localStorage.getItem("user");
  const companyName = localStorage.getItem("companyName");

  // Unified settings state
  const [userSettings, setUserSettings] = useState({
    // User profile settings
    id: parseInt(userId),
    company_name: companyName || "",
    company_logo: null,
    license_company_logo: null,
    edit_policy_link: "",
    office_email: "",

    // Project settings
    deposit_percent: 50,
    contract_agreement: "",
    survey: {
      weeks: 8,
      day: "Monday",
    },
    routine_submission_date: {
      weeks: 1,
      day: "Monday",
    },
    estimated_delivery: {
      weeks: 1,
      day: "Friday",
    },

    // Management settings
    management_value: "",
    management_value_type: "",
    artist_deadline: "",
    engineer_deadline: "",
    artist_engineer_deadline: "",
    voiceover_eight_count: "",
    song_eight_count: "",
    tracking_eight_count: "",
    auto_approve: 0,
  });

  // Additional UI state
  const [activeTab, setActiveTab] = useState("general");
  const [focusedInput, setFocusedInput] = React.useState({
    startDate: null,
    endDate: null,
  });
  const [dates, setDates] = React.useState({
    startDate: null,
    endDate: null,
  });
  const [summary, setSummary] = useState({
    totalDiscount: 0,
    totalTotal: 0,
    totalExpenses: 0,
    netTotal: 0,
    managementDiscount: 0,
  });

  const [settings, setSettings] = React.useState([]);
  const [managementValue, setManagementValue] = React.useState("");
  const [managementValueType, setManagementValueType] = React.useState("");
  const [artistDeadline, setArtistDeadline] = React.useState("");
  const [engineerDeadline, setEngineerDeadline] = React.useState("");
  const [artistEngineerDeadline, setArtistEngineerDeadline] =
    React.useState("");
  const [voiceoverEightCount, setVoiceoverEightCount] = React.useState("");
  const [songEightCount, setSongEightCount] = React.useState("");
  const [trackingEightCount, setTrackingEightCount] = React.useState("");
  const [autoApprove, setAutoApprove] = React.useState(0);

  const [startDate, setStartDate] = React.useState("");
  const [endDate, setEndDate] = React.useState("");
  const [totalDiscount, setTotalDiscount] = React.useState(0);
  const [totalTotal, setTotalTotal] = React.useState(0);
  const [totalExpenses, setTotalExpenses] = React.useState(0);
  const [netTotal, setNetTotal] = React.useState(0);
  const [managementDiscount, setManagementDiscount] = React.useState(0);
  const [photoUrl, setPhotoUrl] = React.useState(null);
  const [licenseLogo, setLicenseLogo] = React.useState(null);
  const [edit_policy, setEditPolicy] = React.useState("");
  const [officeEmail, setOfficeEmail] = React.useState("");
  const [depositPercent, setDepositPercent] = useState(50);
  const [surveySettings, setSurveySettings] = useState({
    weeks: 8,
    day: "Monday",
  });
  const [routineSettings, setRoutineSettings] = useState({
    weeks: 1,
    day: "Monday",
  });
  const [deliverySettings, setDeliverySettings] = useState({
    weeks: 1,
    day: "Friday",
  });

  const buttonList = {
    complex: [
      ["undo", "redo"],
      ["font", "fontSize", "formatBlock"],
      ["bold", "underline", "italic", "strike", "subscript", "superscript"],
      ["removeFormat"],
      ["fontColor", "hiliteColor"],
      ["indent", "outdent"],
      ["align", "horizontalRule", "list", "table"],
      ["link"],
      ["fullScreen", "showBlocks", "codeView"],
      ["preview"],
    ],
  };

  const [contractAgreement, setContractAgreement] = useState("");
  const [editorInstance, setEditorInstance] = useState(null);

  const handleManagementValueChange = (e) => {
    setManagementValue(e.target.value);
  };

  const handleManagementValueTypeChange = (value) => {
    setManagementValueType(value);
  };

  const handleArtistDeadlineChange = (e) => {
    setArtistDeadline(e.target.value);
  };

  const handleEngineerDeadlineChange = (e) => {
    setEngineerDeadline(e.target.value);
  };

  const handleArtistEngineerDeadlineChange = (e) => {
    setArtistEngineerDeadline(e.target.value);
  };

  const handleVoiceoverEightCountChange = (e) => {
    setVoiceoverEightCount(e.target.value);
  };

  const handleSongEightCountChange = (e) => {
    setSongEightCount(e.target.value);
  };

  const handleTrackingEightCountChange = (e) => {
    setTrackingEightCount(e.target.value);
  };

  const handleAutoApproveChange = (value) => {
    setAutoApprove(value);
  };

  const retrieveSummary = async () => {
    try {
      if (startDate && endDate) {
        const result = await retrieveSummaryAPI({
          start_date: moment(startDate).format("YYYY-MM-DD"),
          end_date: moment(endDate).format("YYYY-MM-DD"),
        });
        if (!result.error) {
          let total = result.list[0].total_total
            ? Number(result.list[0].total_total)
            : 0;
          let discount = result.list[0].total_discount
            ? Number(result.list[0].total_discount)
            : 0;
          let expenses = result.list[0].total_expenses
            ? Number(result.list[0].total_expenses)
            : 0;
          setTotalDiscount(discount);
          setTotalTotal(total);
          setTotalExpenses(expenses);
          let totalWithDiscount = total - discount;
          let mgtDiscountObj = calculateManagementDiscount(
            settings,
            totalWithDiscount
          );
          let managementDiscount = mgtDiscountObj.managementDiscountVal;
          let netTotal = calculateNetTotal(
            totalWithDiscount,
            managementDiscount,
            expenses
          );
          setManagementDiscount(managementDiscount);
          setNetTotal(netTotal);
        }
      } else {
        showToast(
          globalDispatch,
          "Please select start date and end date",
          4000
        );
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const retrieveAllSettings = async () => {
    try {
      const result = await retrieveAllSettingsAPI();
      if (!result.error) {
        setSettings(result.list);
        // set all settings that matches with SETTING_KEYS
        if (result.list.length > 0) {
          result.list.forEach((row) => {
            if (row.setting_key === "management_value") {
              setManagementValue(row.setting_value);
            }
            if (row.setting_key === "management_value_type") {
              setManagementValueType(row.setting_value);
            }
            if (row.setting_key === "artist_deadline") {
              setArtistDeadline(row.setting_value);
            }
            if (row.setting_key === "engineer_deadline") {
              setEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "artist_engineer_deadline") {
              setArtistEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "voiceover_eight_count") {
              setVoiceoverEightCount(row.setting_value);
            }
            if (row.setting_key === "song_eight_count") {
              setSongEightCount(row.setting_value);
            }
            if (row.setting_key === "tracking_eight_count") {
              setTrackingEightCount(row.setting_value);
            }
            if (row.setting_key === "auto_approve") {
              setAutoApprove(row.setting_value);
            }
          });
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getOfficeEmail = async (userId) => {
    try {
      const res = await getUserDetailsByIdAPI(userId);
      if (!res.error) {
        setEditPolicy(res.model?.edit_policy_link || "");
        setOfficeEmail(res.model?.office_email || "");
      }
    } catch (error) {}
  };

  useEffect(() => {
    getOfficeEmail(userId);
    // Load project settings if they exist
    if (userId) {
      (async function () {
        try {
          const res = await getUserDetailsByIdAPI(userId);
          if (!res.error) {
            setDepositPercent(res.model?.deposit_percent || 50);
            setContractAgreement(res.model?.contract_agreement || "");

            // Parse JSON strings if they exist, otherwise use defaults
            const surveyData = res.model?.survey
              ? JSON.parse(res.model.survey)
              : { weeks: 8, day: "Monday" };
            const routineData = res.model?.routine_submission_date
              ? JSON.parse(res.model.routine_submission_date)
              : { weeks: 1, day: "Monday" };
            const deliveryData = res.model?.estimated_delivery
              ? JSON.parse(res.model.estimated_delivery)
              : { weeks: 1, day: "Friday" };

            setSurveySettings(surveyData);
            setRoutineSettings(routineData);
            setDeliverySettings(deliveryData);
          }
        } catch (error) {
          console.error("Error parsing settings:", error);
        }
      })();
    }
  }, []);

  const updateEmailOffice = async (e, payload) => {
    e.preventDefault();
    try {
      // const result = await uploadS3FilesAPI(formData);
      const res = await updateUserDetailsAPI(payload);
      if (!res.error) {
        setOfficeEmail(payload.office_email);
        showToast(globalDispatch, "Office Email Updated");
      }
    } catch (error) {
      showToast(globalDispatch, "Office Email Updated", 4000, "error");
    }
  };

  const createOrUpdateAllSettings = async () => {
    try {
      const payload = {
        settings: [
          {
            setting_key: "management_value",
            setting_value: managementValue ?? 0,
          },
          {
            setting_key: "management_value_type",
            setting_value: managementValueType ?? "%",
          },
          {
            setting_key: "artist_deadline",
            setting_value: artistDeadline ?? 3,
          },
          {
            setting_key: "engineer_deadline",
            setting_value: engineerDeadline ?? 3,
          },
          {
            setting_key: "artist_engineer_deadline",
            setting_value: artistEngineerDeadline ?? 3,
          },
          {
            setting_key: "voiceover_eight_count",
            setting_value: voiceoverEightCount ?? 4,
          },
          {
            setting_key: "song_eight_count",
            setting_value: songEightCount ?? 8,
          },
          {
            setting_key: "tracking_eight_count",
            setting_value: trackingEightCount ?? 4,
          },
          {
            setting_key: "auto_approve",
            setting_value: autoApprove ?? 0,
          },
        ],
      };
      const result = await createOrUpdateAllSettingsAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        await retrieveAllSettings();
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "setting",
      },
    });

    (async function () {
      await retrieveAllSettings();
    })();
  }, []);

  console.log(edit_policy);

  const handlePhotoUpload = async (formData) => {
    try {
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        let attachmentsArr = JSON.parse(result.attachments);
        const payload = {
          id: parseInt(userId),
          company_logo: attachmentsArr[0],
          company_name: companyName,
          office_email: officeEmail,
          license_company_logo: licenseLogo,
          edit_policy_link: edit_policy,
          deposit_percent: depositPercent,
          survey: JSON.stringify(surveySettings),
          routine_submission_date: JSON.stringify(routineSettings),
          estimated_delivery: JSON.stringify(deliverySettings),
        };
        const photoResult = await updateUserDetailsAPI(payload);

        if (!photoResult.error) {
          setPhotoUrl(attachmentsArr[0]);
          showToast(globalDispatch, "Company Logo has been updated", 5000);
          // dispatch({
          //   type: 'SET_PROFILE',
          //   payload: {
          //     photo: attachmentsArr[0],
          //     companyName: companyName,
          //   },
          // });
          // window.location.reload();
        } else {
          showToast(
            globalDispatch,
            "Company Logo Update Failed",
            3000,
            "error"
          );
          return;
        }
      } else {
        showToast(globalDispatch, "Company Logo Update Failed", 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const handlePhotoUploadLicense = async (formData) => {
    try {
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        let attachmentsArr = JSON.parse(result.attachments);
        const payload = {
          id: parseInt(userId),
          company_logo: photoUrl,
          company_name: companyName,
          office_email: officeEmail,
          license_company_logo: attachmentsArr[0],
          edit_policy_link: edit_policy,
        };
        const photoResult = await updateUserDetailsAPI(payload);

        if (!photoResult.error) {
          setLicenseLogo(attachmentsArr[0]);
          showToast(
            globalDispatch,
            "License Company Logo has been updated",
            5000
          );
          // dispatch({
          //   type: 'SET_PROFILE',
          //   payload: {
          //     photo: attachmentsArr[0],
          //     companyName: companyName,
          //   },
          // });
          // window.location.reload();
        } else {
          showToast(
            globalDispatch,
            "License Company Logo Update Failed",
            3000,
            "error"
          );
          return;
        }
      } else {
        showToast(globalDispatch, "Company Logo Update Failed", 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const handleEditPolicyUpload = async (formData) => {
    try {
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        let attachmentsArr = JSON.parse(result.attachments);
        const payload = {
          id: parseInt(userId),
          company_logo: photoUrl,
          company_name: companyName,
          office_email: officeEmail,
          license_company_logo: licenseLogo,
          edit_policy_link: attachmentsArr[0],
        };
        const photoResult = await updateUserDetailsAPI(payload);

        if (!photoResult.error) {
          setEditPolicy(attachmentsArr[0]);
          showToast(globalDispatch, "Edit Policy has been updated", 5000);
          // dispatch({
          //   type: 'SET_PROFILE',
          //   payload: {
          //     photo: attachmentsArr[0],
          //     companyName: companyName,
          //   },
          // });
          // window.location.reload();
        } else {
          showToast(globalDispatch, "Edit Policy Update Failed", 3000, "error");
          return;
        }
      } else {
        showToast(globalDispatch, "Company Logo Update Failed", 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const SubscriptionType = localStorage.getItem("UserSubscription");

  React.useEffect(() => {
    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("member_photo", result.model?.company_logo);
            localStorage.setItem(
              "license_logo",
              result.model?.license_company_logo
            );
            setPhotoUrl(result?.model?.company_logo);
            setLicenseLogo(result.model?.license_company_logo);
            localStorage.setItem("photo", result?.model?.photo);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  console.log(edit_policy);

  const getSunEditorInstance = (sunEditor) => {
    setEditorInstance(sunEditor);
  };

  const updateProjectSettings = async () => {
    try {
      const payload = {
        id: parseInt(userId),
        deposit_percent: depositPercent,
        contract_agreement: contractAgreement,
        survey: JSON.stringify(surveySettings),
        routine_submission_date: JSON.stringify(routineSettings),
        estimated_delivery: JSON.stringify(deliverySettings),
        license_company_logo: licenseLogo,
        company_logo: photoUrl,
        company_name: companyName,
        office_email: officeEmail,
        edit_policy_link: edit_policy,
      };

      const res = await updateUserDetailsAPI(payload);
      if (!res.error) {
        showToast(
          globalDispatch,
          "Project settings updated successfully",
          4000
        );
      }
    } catch (error) {
      showToast(
        globalDispatch,
        "Failed to update project settings",
        4000,
        "error"
      );
    }
  };

  // Unified update function for all settings
  const updateSettings = async (updates) => {
    try {
      const updatedSettings = {
        ...userSettings,
        ...updates,
      };

      // Create payload with all required fields
      const payload = {
        id: parseInt(userId),
        company_name: updatedSettings.company_name,
        company_logo: updatedSettings.company_logo,
        office_email: updatedSettings.office_email,
        license_company_logo: updatedSettings.license_company_logo,
        edit_policy_link: updatedSettings.edit_policy_link,
        deposit_percent: updatedSettings.deposit_percent,
        contract_agreement: updatedSettings.contract_agreement,
        // Only stringify these specific fields
        survey: JSON.stringify(updatedSettings.survey),
        routine_submission_date: JSON.stringify(
          updatedSettings.routine_submission_date
        ),
        estimated_delivery: JSON.stringify(updatedSettings.estimated_delivery),
        // Management settings
        management_value: updatedSettings.management_value,
        management_value_type: updatedSettings.management_value_type,
        artist_deadline: updatedSettings.artist_deadline,
        engineer_deadline: updatedSettings.engineer_deadline,
        artist_engineer_deadline: updatedSettings.artist_engineer_deadline,
        voiceover_eight_count: updatedSettings.voiceover_eight_count,
        song_eight_count: updatedSettings.song_eight_count,
        tracking_eight_count: updatedSettings.tracking_eight_count,
        auto_approve: updatedSettings.auto_approve,
      };

      const res = await updateUserDetailsAPI(payload);

      if (!res.error) {
        setUserSettings(updatedSettings);
        showToast(globalDispatch, "Settings updated successfully", 4000);
        return true;
      } else {
        showToast(globalDispatch, "Failed to update settings", 4000, "error");
        return false;
      }
    } catch (error) {
      showToast(globalDispatch, "Error updating settings", 4000, "error");
      console.error("Error updating settings:", error);
      return false;
    }
  };

  const handleCreateManager = async (e) => {
    e.preventDefault();
    const managerName = e.target.elements.managerName.value;
    const email = e.target.elements.email.value;

    if (!managerName || !email) {
      showToast(globalDispatch, "Please fill in all fields", 4000, "error");
      return;
    }

    try {
      const sdk = new MkdSDK();
      const response = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/user/manager/create",
        { name: managerName, email },
        "POST"
      );

      if (!response.error) {
        showToast(globalDispatch, "Manager created successfully", 4000);
      } else {
        showToast(globalDispatch, response.message, 4000, "error");
      }
    } catch (error) {
      console.error("Error creating manager:", error);
      showToast(globalDispatch, "Failed to create manager", 4000, "error");
    }
  };

  return (
    <div className="p-4 mx-auto max-w-screen md:p-6 2xl:p-10">
      <div className="mb-6">
        <h2 className="font-semibold text-white text-title-md2">Settings</h2>
      </div>

      <div className="rounded border border-strokedark bg-boxdark">
        <div className="flex flex-wrap border-b border-strokedark">
          <button
            onClick={() => setActiveTab("general")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "general"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            General Settings
          </button>

          <button
            onClick={() => setActiveTab("email")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "email"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            Email Settings
          </button>

          <button
            onClick={() => setActiveTab("logos")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "logos"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            Logo Settings
          </button>

          <button
            onClick={() => setActiveTab("policy")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "policy"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            Edit Policy
          </button>

          <button
            onClick={() => setActiveTab("projects")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "projects"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            Projects
          </button>

          {parseInt(SubscriptionType) !== 2 && (
            <button
              onClick={() => setActiveTab("management")}
              className={`px-6 py-3 text-sm font-medium transition-colors ${
                activeTab === "management"
                  ? "bg-primary text-white"
                  : "text-white hover:bg-meta-4"
              }`}
            >
              Management & Discount
            </button>
          )}

          <button
            onClick={() => setActiveTab("manager")}
            className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === "manager"
                ? "bg-primary text-white"
                : "text-white hover:bg-meta-4"
            }`}
          >
            Manager Access
          </button>
        </div>

        {/* Tab Content - In same container as tabs */}
        {activeTab === "general" && (
          <div className="p-6">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2 2xl:grid-cols-3">
              {parseInt(SubscriptionType) !== 2 && (
                <>
                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Management Value
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={managementValue}
                      onChange={handleManagementValueChange}
                      placeholder="Management Value"
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                    />
                  </div>

                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Management Value Type
                    </label>
                    <CustomSelect2
                      label="Management Value Type"
                      value={managementValueType}
                      onChange={(value) =>
                        handleManagementValueTypeChange(value)
                      }
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-primary focus:outline-none"
                    >
                      <option value="">--Select--</option>
                      <option value="%">%</option>
                      <option value="$">$</option>
                    </CustomSelect2>
                  </div>

                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Artist Deadline
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={artistDeadline}
                      onChange={handleArtistDeadlineChange}
                      placeholder="Artist Deadline"
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                    />
                  </div>

                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Engineer Deadline
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={engineerDeadline}
                      onChange={handleEngineerDeadlineChange}
                      placeholder="Engineer Deadline"
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                    />
                  </div>

                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Artist/Engineer Deadline
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={artistEngineerDeadline}
                      onChange={handleArtistEngineerDeadlineChange}
                      placeholder="Artist/Engineer Deadline"
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                    />
                  </div>

                  <div className="w-full">
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Auto Approve
                    </label>
                    <CustomSelect2
                      label="Auto Approve"
                      value={autoApprove}
                      onChange={(value) => handleAutoApproveChange(value)}
                      className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-primary focus:outline-none"
                    >
                      <option value="">--Select--</option>
                      <option value="1">Yes</option>
                      <option value="0">No</option>
                    </CustomSelect2>
                  </div>
                </>
              )}
            </div>

            <button
              onClick={createOrUpdateAllSettings}
              className="mt-6 inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
            >
              Update Settings
            </button>
          </div>
        )}

        {activeTab === "email" && (
          <div className="p-6">
            <div className="w-full md:w-1/2">
              <label className="mb-2.5 block text-sm font-medium text-white">
                Office Email
              </label>
              <input
                type="email"
                value={officeEmail || ""}
                onChange={(e) => setOfficeEmail(e.target.value)}
                placeholder="Office Email"
                className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
              />

              <button
                onClick={(e) =>
                  updateEmailOffice(e, {
                    office_email: officeEmail,
                    id: userId,
                    company_name: companyName,
                    company_logo: photoUrl,
                    license_company_logo: licenseLogo,
                    edit_policy_link: edit_policy,
                    deposit_percent: depositPercent,
                    survey: JSON.stringify(surveySettings),
                    routine_submission_date: JSON.stringify(routineSettings),
                    estimated_delivery: JSON.stringify(deliverySettings),
                  })
                }
                className="mt-6 inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
              >
                Update Email
              </button>
            </div>
          </div>
        )}

        {activeTab === "logos" && (
          <div className="p-6">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Profile Photo
                </label>
                {photoUrl && (
                  <div className="mb-4">
                    <img
                      src={photoUrl}
                      alt="Profile"
                      className="object-cover w-24 h-24 rounded-full"
                    />
                  </div>
                )}
                <PhotoUpload
                  maxFileSize={2}
                  setFileUpload={handlePhotoUpload}
                  className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white"
                />
              </div>

              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  License Logo
                </label>
                {licenseLogo && (
                  <div className="mb-4">
                    <img
                      src={licenseLogo}
                      alt="License Logo"
                      className="object-contain w-auto h-24"
                    />
                  </div>
                )}
                <LogoUpload
                  maxFileSize={2}
                  setFileUpload={handlePhotoUploadLicense}
                  className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white"
                />
              </div>
            </div>
          </div>
        )}

        {activeTab === "policy" && (
          <div className="p-6">
            <div className="w-full">
              <label className="mb-2.5 block text-sm font-medium text-white">
                Edit Policy PDF
              </label>
              {edit_policy && (
                <div className="mb-4">
                  <a
                    href={edit_policy}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center text-primary hover:underline"
                  >
                    <FileText className="mr-2 w-4 h-4" />
                    Current Policy PDF
                  </a>
                </div>
              )}
              <EditPolicyPdfUpload
                maxFileSize={2}
                setFileUpload={handleEditPolicyUpload}
                className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white"
              />
            </div>
          </div>
        )}

        {activeTab === "projects" && (
          <div className="p-6">
            <div className="mb-6">
              <h4 className="text-xl font-semibold text-white">
                Project Settings
              </h4>
              <p className="mt-1 text-sm text-gray-400">
                Set default values for new projects and invoices
              </p>
            </div>

            <div className="space-y-6 max-w-2xl">
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Default Deposit Percentage
                </label>
                <div className="flex w-full max-w-[200px] items-center">
                  <input
                    type="number"
                    min="0"
                    max="100"
                    value={depositPercent}
                    onChange={(e) => setDepositPercent(Number(e.target.value))}
                    className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                  />
                  <span className="ml-2 text-white">%</span>
                </div>
              </div>

              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Contract Agreement
                </label>
                <div className="flex flex-col gap-4">
                  <textarea
                    className="h-[70px] w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                    value={contractAgreement}
                    onChange={(e) => setContractAgreement(e.target.value)}
                  />
                </div>
              </div>

              <div className="grid gap-6 md:grid-cols-2">
                <div>
                  <label className="mb-2.5 block text-sm font-medium text-white">
                    Survey Timing
                  </label>
                  <div className="flex gap-4 items-center">
                    <div className="flex items-center">
                      <input
                        type="number"
                        min="1"
                        value={surveySettings.weeks}
                        onChange={(e) =>
                          setSurveySettings((prev) => ({
                            ...prev,
                            weeks: Number(e.target.value),
                          }))
                        }
                        className="w-20 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                      />
                      <span className="ml-2 text-white">weeks before</span>
                    </div>
                    <CustomSelect2
                      value={surveySettings.day}
                      onChange={(value) =>
                        setSurveySettings((prev) => ({ ...prev, day: value }))
                      }
                      className="w-32 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-primary focus:outline-none"
                    >
                      <option value="Monday">Monday</option>
                      <option value="Tuesday">Tuesday</option>
                      <option value="Wednesday">Wednesday</option>
                      <option value="Thursday">Thursday</option>
                      <option value="Friday">Friday</option>
                      <option value="Saturday">Saturday</option>
                      <option value="Sunday">Sunday</option>
                    </CustomSelect2>
                  </div>
                </div>

                <div>
                  <label className="mb-2.5 block text-sm font-medium text-white">
                    Routine Submission
                  </label>
                  <div className="flex gap-4 items-center">
                    <div className="flex items-center">
                      <input
                        type="number"
                        min="1"
                        value={routineSettings.weeks}
                        onChange={(e) =>
                          setRoutineSettings((prev) => ({
                            ...prev,
                            weeks: Number(e.target.value),
                          }))
                        }
                        className="w-20 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                      />
                      <span className="ml-2 text-white">weeks before</span>
                    </div>
                    <CustomSelect2
                      value={routineSettings.day}
                      onChange={(value) =>
                        setRoutineSettings((prev) => ({ ...prev, day: value }))
                      }
                      className="w-32 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-primary focus:outline-none"
                    >
                      <option value="Monday">Monday</option>
                      <option value="Tuesday">Tuesday</option>
                      <option value="Wednesday">Wednesday</option>
                      <option value="Thursday">Thursday</option>
                      <option value="Friday">Friday</option>
                      <option value="Saturday">Saturday</option>
                      <option value="Sunday">Sunday</option>
                    </CustomSelect2>
                  </div>
                </div>

                <div>
                  <label className="mb-2.5 block text-sm font-medium text-white">
                    Estimated Delivery
                  </label>
                  <div className="flex gap-4 items-center">
                    <div className="flex items-center">
                      <input
                        type="number"
                        min="1"
                        value={deliverySettings.weeks}
                        onChange={(e) =>
                          setDeliverySettings((prev) => ({
                            ...prev,
                            weeks: Number(e.target.value),
                          }))
                        }
                        className="w-20 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                      />
                      <span className="ml-2 text-white">weeks after</span>
                    </div>
                    <CustomSelect2
                      value={deliverySettings.day}
                      onChange={(value) =>
                        setDeliverySettings((prev) => ({ ...prev, day: value }))
                      }
                      className="w-32 rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-primary focus:outline-none"
                    >
                      <option value="Monday">Monday</option>
                      <option value="Tuesday">Tuesday</option>
                      <option value="Wednesday">Wednesday</option>
                      <option value="Thursday">Thursday</option>
                      <option value="Friday">Friday</option>
                      <option value="Saturday">Saturday</option>
                      <option value="Sunday">Sunday</option>
                    </CustomSelect2>
                  </div>
                </div>
              </div>

              <button
                onClick={updateProjectSettings}
                className="mt-6 inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
              >
                Save Project Settings
              </button>
            </div>
          </div>
        )}

        {activeTab === "management" && parseInt(SubscriptionType) !== 2 && (
          <div className="p-6">
            <div className="mb-6">
              <h4 className="text-xl font-semibold text-white">
                Management & Discount Search
              </h4>
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Start Date
                </label>
                <SingleDatePicker
                  id="startDate"
                  date={dates.startDate ? moment(dates.startDate) : null}
                  onDateChange={(date) => {
                    setDates((prev) => ({ ...prev, startDate: date }));
                    setStartDate(date ? date.format("YYYY-MM-DD") : null);
                  }}
                  focused={focusedInput.startDate}
                  onFocusChange={({ focused }) =>
                    setFocusedInput((prev) => ({ ...prev, startDate: focused }))
                  }
                  numberOfMonths={1}
                  isOutsideRange={() => false}
                  displayFormat="MM-DD-YYYY"
                  placeholder="Select Start Date"
                  readOnly={true}
                  customInputIcon={null}
                  noBorder={true}
                  block
                />
              </div>

              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  End Date
                </label>
                <SingleDatePicker
                  id="endDate"
                  date={dates.endDate ? moment(dates.endDate) : null}
                  onDateChange={(date) => {
                    setDates((prev) => ({ ...prev, endDate: date }));
                    setEndDate(date ? date.format("YYYY-MM-DD") : null);
                  }}
                  focused={focusedInput.endDate}
                  onFocusChange={({ focused }) =>
                    setFocusedInput((prev) => ({ ...prev, endDate: focused }))
                  }
                  numberOfMonths={1}
                  isOutsideRange={() => false}
                  displayFormat="MM-DD-YYYY"
                  placeholder="Select End Date"
                  readOnly={true}
                  customInputIcon={null}
                  noBorder={true}
                  block
                />
              </div>

              <div className="flex gap-3 items-end">
                <button
                  onClick={retrieveSummary}
                  className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Search
                </button>
                <button
                  onClick={() => {
                    setStartDate("");
                    setEndDate("");
                    setTotalDiscount(0);
                    setTotalTotal(0);
                    setTotalExpenses(0);
                    setNetTotal(0);
                    setManagementDiscount(0);
                  }}
                  className="inline-flex items-center justify-center rounded-md bg-danger px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Clear
                </button>
              </div>
            </div>
          </div>
        )}

        {activeTab === "manager" && (
          <div className="p-6">
            <div className="mb-6">
              <h4 className="text-xl font-semibold text-white">
                Create Manager Access
              </h4>
              <p className="mt-1 text-sm text-gray-400">
                Create a manager login account that can access your company's
                dashboard. You can use the same email address as your member
                login.
              </p>
            </div>

            <form onSubmit={handleCreateManager} className="max-w-md">
              <div className="mb-4">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Manager's Name
                </label>
                <input
                  type="text"
                  name="managerName"
                  placeholder="Enter manager's name"
                  className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                />
              </div>

              <div className="mb-4">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Email Address
                </label>
                <input
                  type="email"
                  name="email"
                  placeholder="Enter email address"
                  className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                />
              </div>

              <button
                type="submit"
                className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
              >
                Create Manager Access
              </button>
            </form>
          </div>
        )}
      </div>
    </div>
  );
};

export default ListMemberSettingPage;
