/* eslint-disable @typescript-eslint/no-explicit-any */
import { serviceIconMap } from "@/Constant/enums";
import React, { useState, FormEvent, useEffect } from "react";
import { getMasterList } from "../../../../Api/MastersApi";
import HourGlassLoader from "../../../Loader/Loader";
import PickupForm from "../PickupForm";
import { getFormattedAddress } from "../../../../lib/Helper";
import Link from "next/link";
import { bulkOrderFileUpload, downloadSampleBulkOrder, initiateBulkOrder, placeBulkOrder } from "../../../../Api/OrderApi";
import PhoneInputFieldNew from "../../../TextField/PhoneInputFieldNew";
import { toast } from "react-toastify";

interface FormData {
  serviceTypes: any;
  orderId: string;
  pickupMobile: string;
  pickupAltMobile: string;
  deliveryMobile: string;
  deliveryPerson: string;
  blockNumber: any;
  roadNumber: any;
  buildingNumber: any;
  flatNumber: string;
  pickup_date: string,
  pickup_time_slot_id: any,
}

interface OrderFilterFormProps {
  tab: number;
  onSubmit: any;
  setTab: any;
  onClose: any;
  toggleAddressChange: any;
  setRefreshList: any;
  defaultDetails: any;
}

interface ServiceType {
  id: number;
  name: string;
}

const initialFormState: FormData = {
  serviceTypes: null,
  orderId: "",
  pickupMobile: "",
  pickupAltMobile: "",
  deliveryMobile: "",
  deliveryPerson: "",
  blockNumber: null,
  roadNumber: null,
  buildingNumber: null,
  flatNumber: "",
  pickup_date: "",
  pickup_time_slot_id: null,
};

const OrderForm: React.FC<OrderFilterFormProps> = ({ tab, setTab, onClose, toggleAddressChange, setRefreshList, defaultDetails }) => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const addresses = allData?.addresses || [];
  const hasPrimaryAddress = addresses.some((addr: any) => addr.isPrimary === 1);
  const [apiResponse, setApiResponse] = useState<any>({})
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [selectedTime, setSelectedTime] = useState<number>(0);
  const [formData, setFormData] = useState<FormData>(initialFormState);
  const [serviceTypes, setServiceTypes] = useState<any[]>([]);
  const [serviceType, setServiceType] = useState<ServiceType | null>(null);
  const isStep1Disabled = !!defaultDetails?.id;
  useEffect(() => {
    const fetchMasterLists = async () => {
      try {
        setIsLoading(true);
        const [services] = await Promise.all([
          getMasterList("service_type"),
        ]);
        setServiceTypes(services.data || []);
      } catch (err) {
        console.error("Error loading masterlists", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMasterLists();
  }, []);
  useEffect(() => {
    if (defaultDetails?.id) {
      // Autofill form from defaultDetails
      const primaryAddress = defaultDetails?.pickupBuildingId
        ? {
          blockId: defaultDetails?.pickupBlockId,
          roadId: defaultDetails?.pickupRoadId,
          buildingId: defaultDetails?.pickupBuildingId,
          addressLineOne: defaultDetails?.pickupFlatOrOfficeNumber,
          id: defaultDetails?.pickupAddressId,
        }
        : null;

      // Find matching service type
      const selected = serviceTypes.find((s) => s.id === defaultDetails?.serviceTypeId);

      setServiceType(selected || null);

      setFormData((prev) => ({
        ...prev,
        serviceTypes: selected,
        pickupMobile: defaultDetails?.pickupMobileNumber || "",
        pickupAltMobile: defaultDetails?.pickupAlternateNumber || "",
        blockNumber: primaryAddress?.blockId,
        roadNumber: primaryAddress?.roadId,
        buildingNumber: primaryAddress?.buildingId,
        flatNumber: primaryAddress?.addressLineOne,
        pickup_date: defaultDetails?.pickupDate || "",
        pickup_time_slot_id: defaultDetails?.pickupTimeSlotId || null,
      }));

      setSelectedDate(defaultDetails?.pickupDate || null);
      setSelectedTime(defaultDetails?.pickupTimeSlotId || 0);

      // API response from default (skip step 1)
      setApiResponse(defaultDetails);
      setTab(2);
    }
  }, [defaultDetails, serviceTypes, setTab]);

  const handleServiceTypeChange = (serviceName: string) => {
    const selected = serviceTypes.find((s) => s.name === serviceName);
    if (selected) {
      setServiceType(selected);
      setFormData((prev) => ({
        ...prev,
        serviceTypes: selected,
      }));
      setErrors({ ...errors, serviceTypes: "" })
    }
  };

  // const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
  //   const { name, value } = e.target;
  //   setFormData((prev) => ({
  //     ...prev,
  //     [name]: value,
  //   }));
  // };

  // const handleSelectChange = (field: keyof FormData) => (option: any) => {
  //   setFormData((prev) => ({
  //     ...prev,
  //     [field]: option || null,
  //   }));
  // };

  const [errors, setErrors] = useState<Record<string, string>>({}); // <-- store validation errors

  // validate Tab 1 fields
  const validateTab1 = () => {
    const newErrors: Record<string, string> = {};

    if (!serviceType?.id) newErrors.serviceTypes = "Service type is required";
    if (!formData.pickupMobile) {
      newErrors.pickupMobile = "Pickup mobile is required";
    } else if (formData.pickupMobile.replace(/\D/g, "").length < 8) {
      newErrors.pickupMobile = "Enter a valid mobile number";
    }

    if (formData.pickupAltMobile && formData.pickupAltMobile.replace(/\D/g, "").length < 8) {
      newErrors.pickupAltMobile = "Enter a valid alternate number";
    }
    // Pickup Date & Time Validation
    const pickupDate = selectedDate;
    const pickupTime = selectedTime;
    if (!pickupDate) newErrors.pickupDate = "Pickup date is required";
    if (!pickupTime) newErrors.pickupTime = "Pickup time is required";

    if (!hasPrimaryAddress) {
      newErrors.pickupAddress = "Pickup address is required (no primary found)";
    }


    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setRefreshList(true)
    if (tab === 1) {
      if (defaultDetails?.id) {
        setApiResponse(defaultDetails)
        setTab(2)
        return;
      }
      if (!validateTab1()) return;
      const primaryAddress = addresses.find((addr: any) => addr.isPrimary === 1) || null;
      const payload = {
        service_type_id: serviceType?.id,
        pickup_date: selectedDate,
        pickup_time_slot_id: selectedTime,
        pickup_customer_name: `${allData?.firstName} ${allData?.lastName}`,
        pickup_mobile_number: formData.pickupMobile,
        pickup_alternate_number: formData.pickupAltMobile || null,
        pickup_block_id: primaryAddress?.blockId,
        pickup_road_id: primaryAddress?.roadId,
        pickup_building_id: primaryAddress?.buildingId,
        pickup_flat_or_office_number: primaryAddress?.addressLineOne || "",
        pickup_address_id: primaryAddress?.id ?? null,
      };

      try {
        setIsLoading(true);
        const res = await initiateBulkOrder(payload);
        if (res?.status) {
          toast.success(res?.message)
          setApiResponse(res?.data)
          setTab(2)
        }
        else toast.warning(res?.message)
      } catch (err) {
        toast.warning("Error initiating bulk order")
        console.error("Error initiating bulk order", err);
        alert("Failed to initiate order. Please try again.");
      } finally {
        setIsLoading(false);
      }
    } else if (tab === 2) handlePlaceOrder();
  };
  const [file, setFile] = useState<File | null>(null);
  const [fileDownloadLoadder, serFileDownloadLoader] = useState<boolean>(false)
  const [fileUploadLoader, setFileUploadLoader] = useState<boolean>(false)
  const handleDownloadSample = async () => {
    try {
      serFileDownloadLoader(true)
      const blob = await downloadSampleBulkOrder();
      if (blob) {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "bulk_order_sample.xlsx");
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url);
      }
    } catch (err) {
      toast.error("Failed to download sample file");
      console.error(err);
    } finally {
      serFileDownloadLoader(false)
    }
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setFile(e.target.files[0]);
      await handleFileUpload(e.target.files[0]);
    }
    // 👇 Reset input value so same file triggers again
    e.target.value = "";
  };

  const [fileUploadMessage, setFileUploadMessage] = useState<any>({})
  const handleFileUpload = async (fileData: any) => {
    const fileInfo = fileData;
    if (!fileInfo) {
      toast.warning("Please select a file to upload");
      return;
    }
    try {
      const formData = new FormData();
      formData.append("bulk_order_file", fileInfo);
      formData.append("bulk_id", apiResponse?.id)
      setFileUploadLoader(true)
      const res = await bulkOrderFileUpload(formData);
      if (res?.status) {
        setFileUploadMessage(res)
        setRefreshList(true)
        // Swal.fire({
        //   icon: "success",
        //   title: "Upload Successful",
        //   text: res?.message || "File uploaded successfully",
        //   customClass: {
        //     confirmButton: "delybell-primary px-4",
        //   },
        //   confirmButtonText: "OK",
        // });

      } else {
        setFileUploadMessage(res)
        // Swal.fire({
        //   icon: "error",
        //   title: "Upload Failed",
        //   text: res?.message || "Upload failed",
        //   customClass: {
        //     confirmButton: "delybell-primary px-4",
        //   },
        //   confirmButtonText: "OK",
        // });
      }

    } catch (err) {
      toast.error("Error uploading file");
      console.error(err);
    } finally {
      setFileUploadLoader(false)
    }
  };

  const handlePlaceOrder = async () => {
    try {
      setIsLoading(true)
      const res = await placeBulkOrder({ bulk_id: apiResponse?.id });
      if (res?.status) {
        toast.success("Bulk order placed successfully");
        setTab(1); // or reset form as needed
        onClose();
      } else {
        toast.warning(res?.message || "Failed to place order");
      }
    } catch (err) {
      toast.error("Error placing bulk order");
      console.error(err);
    } finally {
      setIsLoading(false)
    }
  };

  return (
    <>
      {isLoading && <HourGlassLoader />}
      {/* {addressChangeModal ? (
        <AddressList toggleAddressChange={toggleAddressChange} />
      ) : ( */}
      <form onSubmit={handleSubmit}>
        {tab === 1 && (
          <div className="row mx-0 filter-row">
            {/* Service Type */}
            <div className="col-lg-12">
              <h5 className="font-15 pb-1">Service Type</h5>
              <div className="step1-package px-0 pe-0">
                {serviceTypes
                  ?.filter((_) => _?.name !== "International")
                  ?.map((service) => {
                    const { icon, color } =
                      serviceIconMap[service.name] || serviceIconMap["Default"];

                    return (
                      <div
                        key={service.id}
                        className="form-check interest-check"
                      >
                        <input
                          className="form-check-input"
                          type="radio"
                          id={`check-${service.name}`}
                          checked={serviceType?.name === service.name}
                          disabled={isStep1Disabled}
                          onChange={() => handleServiceTypeChange(service.name)}
                        />
                        <label
                          className="form-check-label shadow-xl rounded-xl"
                          htmlFor={`check-${service.name}`}
                        >
                          {service.name.charAt(0).toUpperCase() +
                            service.name.slice(1)}
                        </label>
                        <i className="fa fa-check-circle color-white font-18" />
                        <i
                          className={`ri-${icon}-line font-17 ${color}`}
                        />

                      </div>
                    );
                  })}
                {errors.serviceTypes && (
                  <div className="text-danger px-2 error-box mb-2">{errors.serviceTypes}</div>
                )}
              </div>
            </div>
            <PickupForm serviceType={serviceType} errors={errors} setErrors={setErrors} selectedDate={selectedDate} setSelectedDate={setSelectedDate} selectedTime={selectedTime} setSelectedTime={setSelectedTime} disabled={isStep1Disabled} />
            <div className="col-lg-12 mb-2">
              <div className="d-float-center justify-content-start gap-20">
                <h5
                  className="font-14 font-400 pb-1 mb-0 mt-0"
                  style={{ paddingTop: "8px", opacity: "0.6" }}
                >
                  Pickup Address
                </h5>
                {!isStep1Disabled ? (
                  <Link
                    href="#"
                    onClick={toggleAddressChange}
                    className="mb-0 mt-0 pb-1"
                    style={{ paddingTop: "8px" }}
                  >
                    <i className="fa fa-edit position-unset" />
                  </Link>
                ) : ''}
              </div>
              <div className="bulk-address-block">
                <span className="font-600">
                  {/* <i className="fa fa-map-marker position-unset mt-n2" /> */}
                  <i className="ri-map-pin-line position-unset mt-n2" />
                  {/* <Image
                          className="order-icons img-fluid me-1"
                          src="/images/icons/location.svg"
                          alt="Box Icon"
                          width={18}
                          height={18}
                        /> */}{" "}
                  {/* Flat-1545, Building-78745 Road-4578, Block-987 */}
                  {getFormattedAddress()}
                </span>
                {errors?.pickupAddress && <div className="text-danger mt-1">{errors?.pickupAddress}</div>}
              </div>
            </div>
            {/* Pickup Mobile */}
            <div className="mb-4 col-lg-6">
              <h5
                className="font-14 font-400 pb-1 mb-0 mt-0"
                style={{ paddingTop: "8px", opacity: "0.6" }}
              >
                Mobile No.
              </h5>
              <PhoneInputFieldNew
                fieldName="pickupMobile"
                value={formData.pickupMobile}
                onChange={(val) => {
                  setFormData((prev) => ({ ...prev, pickupMobile: val }))
                  if (val) setErrors({ ...errors, pickupMobile: "" })
                }}
                disabled={isStep1Disabled}
                placeholder="Pickup Mobile No"
                error={errors?.pickupMobile}
              />
            </div>

            {/* Alternate Mobile */}
            <div className="mb-4 col-lg-6">
              <h5
                className="font-14 font-400 pb-1 mb-0 mt-0"
                style={{ paddingTop: "8px", opacity: "0.6" }}
              >
                Alternative Mobile No.
              </h5>
              <PhoneInputFieldNew
                fieldName="pickupAltMobile"
                value={formData.pickupAltMobile}
                onChange={(val) => {
                  setFormData((prev) => ({ ...prev, pickupAltMobile: val }))
                  if (val) setErrors({ ...errors, pickupAltMobile: "" })
                }
                }
                disabled={isStep1Disabled}
                placeholder="Alternate Mobile No"
                error={errors?.pickupAltMobile}
              />
            </div>

          </div>
        )}

        {tab === 2 && (
          <div className="row mx-0 filter-row pt-3">
            <div className="col-lg-12 d-flex flex-wrap gap-2 mt-3">
              {/* Download Sample */}
              <button
                type="button"
                className="btn btn-s bg-green-dark rounded-s"
                onClick={handleDownloadSample}
              >
                <i className="fas fa-download" /> {fileDownloadLoadder ? "Downloading..." : "Download Sample Excel"}
              </button>

              {/* If file already uploaded */}
              {defaultDetails?.isFileUploaded ? (<>
                {/* <div className={`upload-file-label-button ${file ? 'selected-file-upload-box': ''}`}>
                  <label className={`btn btn-s bg-blue-dark rounded-s mb-0 cursor-pointer  ${file ? 'selected-file-upload': ''}`}>
                    <i className="fas fa-sync" /> {fileUploadLoader ? 'Re-uploading...' : "Re-upload"}
            <input
              type="file"
              accept=".xlsx,.xls"
              hidden
              onChange={handleFileChange}
            />
                  </label>

                  {file && (
                    <span className="badge bg-light text-dark px-2 py-1 d-float-center upload-choose-file">
                      📂 {file.name}
                    </span>
                  )}
                </div> */}
              </>
              ) : (
                <div className={`upload-file-label-button ${file ? 'selected-file-upload-box' : ''}`}>
                  <label className={`btn btn-s bg-blue-dark rounded-s mb-0 cursor-pointer  ${file ? 'selected-file-upload' : ''}`}>
                    <i className="fas fa-upload" /> {fileUploadLoader ? "Uploading..." : "Upload Excel File"}
                    <input
                      type="file"
                      accept=".xlsx,.xls"
                      hidden
                      onChange={handleFileChange}
                    />
                  </label>

                  {/* Show filename after selection */}
                  {file && (
                    <span className="badge bg-light text-dark px-2 py-1 d-float-center upload-choose-file">
                      📂 {file.name}
                    </span>
                  )}
                </div>
              )}
              {/* Upload status message */}
              {fileUploadMessage?.message ? (
                <div
                  className={`col-lg-12 alert px-3 py-1 mt-2 ${fileUploadMessage?.status ? "alert-success" : "alert-danger"
                    }`}
                  role="alert"
                >
                  {fileUploadMessage.message}
                </div>
              ) : defaultDetails?.isFileUploaded ? (
                <div
                  className={`col-lg-12 alert px-3 py-1 mt-2 ${"alert-success"
                    }`}
                  role="alert"
                >
                  {"✅ File already uploaded"}
                </div>
              ) : ''}              </div>
          </div>
        )}


        {/* {tab === 2 ? () : ''} */}
        <button
          type="submit"
          className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-4 mb-3 rounded-s"
        >
          {tab === 1 ? "Save & Next" : "Place Order"}
        </button>
      </form>
      {/* )} */}
    </>
  );
};

export default OrderForm;
