import React, { useState, useEffect, useRef, useContext } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Column } from "primereact/column";
import ServerSideDataTable from "@/Components/ServerSideDataTable";
import { Toast } from "primereact/toast";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { Dialog } from "primereact/dialog";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { classNames } from "primereact/utils";
import axios from "axios";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import CustomerDropdown from "@/Components/CustomerDropdown";
import DynamicFieldGroup from "@/Components/DynamicFieldGroup";
import ProductDropdown from "@/Components/ProductDropdown";
import DocumentUpload from "@/Components/DocumentUpload";
import SendForApprovalModal from "@/Components/SendForApprovalModal";
import { authUser } from "@/Components/AuthProvider";

export default function WorkOrder({ auth }) {
  const { permission } = useContext(authUser);
  const toast = useRef(null);
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const [modelShow, setModelShow] = useState(false);
  const [status, setStatus] = useState("create");
  const [quotations, setQuotations] = useState([]);
  const [selectCustomer, setSelectCustomer] = useState("");
  const [selectedClient, setSelectedClient] = useState(null);
  const [search, setSearch] = useState({
    product: "",
  });
  const [documentModalVisible, setDocumentModalVisible] = useState(false);
  const [selectedWorkOrderForDocs, setSelectedWorkOrderForDocs] = useState(null);
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [selectedWorkOrderForApproval, setSelectedWorkOrderForApproval] = useState(null);
  const FormSubmit = useRef(null);
  const scroll = useRef(null);

  const {
    control,
    register,
    formState: { errors },
    handleSubmit,
    reset,
    watch,
    setValue,
  } = useForm({
    defaultValues: {
      date: new Date(),
      quotation_id: "",
      client_id: "",
      note: "",
      payment_term: "",
      list: [],
    },
  });

  const { fields, append, remove, replace } = useFieldArray({
    control,
    name: "list",
  });

  // Fetch quotations on component mount
  useEffect(() => {
    fetchQuotations();
  }, []);

  // Open edit modal when arriving with ?edit=ID (e.g. from Merge list Edit)
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const editId = params.get("edit");
    if (!editId) return;
    axios
      .get(route("work-order.show", editId), {
        headers: { Accept: "application/json" },
      })
      .then(({ data: rowData }) => {
        const customerName = rowData.client
          ? `${rowData.client.name}${rowData.client.code
            ? ` (${rowData.client.code})`
            : ""
          }`
          : "";
        setSelectCustomer(customerName);
        setModelShow(true);
        setStatus("update");
        reset({
          id: rowData.id,
          date: new Date(rowData.date),
          quotation_id: rowData.quotation_id
            ? Number(rowData.quotation_id)
            : "",
          client_id: rowData.client_id
            ? Number(rowData.client_id)
            : "",
          note: rowData.note || "",
          payment_term: rowData.payment_term || "",
          list: (rowData.work_order_details || []).map((item) => ({
            product_name: item.product_name,
            product_id: Number(item.product_id),
            attribute_id: Number(item.attribute_id),
            quantity: Number(item.quantity),
            unit_price: Number(item.price),
            price: Number(item.price),
            discount: Number(item.discount) || 0,
            total: Number(item.total),
          })),
        });
        setSelectedClient(rowData.client || null);
        window.history.replaceState(
          {},
          "",
          window.location.pathname
        );
      })
      .catch(() => { });
  }, []);

  const fetchQuotations = async () => {
    try {
      const response = await axios.get(route("work-order.quotations"));
      setQuotations(response.data);
    } catch (error) {
      console.error("Error fetching quotations:", error);
    }
  };

  // Refresh data table
  const refreshData = () => {
    setRefreshTrigger(prev => prev + 1);
  };

  // Calculate totals
  let list = watch("list");
  const total = list
    ? list.reduce((acc, item) => acc + Number(item.total || 0), 0)
    : 0;

  useEffect(() => {
    setValue("total", total);
    setValue("grand_total", total.toFixed(2));
  }, [total, setValue]);

  // Handle quotation selection - Auto-load products and auto-select client
  const handleQuotationChange = async (quotationId) => {
    if (!quotationId) {
      replace([]);
      setValue("client_id", "");
      setSelectCustomer("");
      setValue("payment_term", "");
      return;
    }

    try {
      const response = await axios.get(
        route("work-order.quotation.details", quotationId)
      );
      const { details, client, payment_term } = response.data;

      // Auto-select client from quotation
      if (client) {
        const customerName = client.name
          ? `${client.name}${client.code ? ` (${client.code})` : ""}`
          : "";
        setSelectCustomer(customerName);
        setSelectedClient(client);
        setValue("client_id", Number(client.id));
      }

      // Auto-fill payment_term from quotation
      if (payment_term) {
        setValue("payment_term", payment_term);
      }

      // Clear existing products and add quotation products
      replace(
        details.map((detail) => ({
          product_name: detail.product_name,
          product_id: Number(detail.product_id),
          attribute_id: Number(detail.attribute_id),
          quantity: Number(detail.quantity),
          unit_price: Number(detail.price),
          price: Number(detail.price),
          discount: 0,
          total: Number(detail.quantity * detail.price),
        }))
      );
    } catch (error) {
      console.error("Error loading quotation details:", error);
      toast.current?.show({
        severity: "error",
        summary: "Error",
        detail: "Failed to load quotation details",
        life: 3000,
      });
    }
  };

  // Set Selected Product - For manual product addition
  const selectedItem = (item) => {
    setSearch((old) => {
      return {
        product: "",
      };
    });

    let inputValue = "";
    if (item.product) {
      inputValue += item.product.name + " ";
      if (item.sku) inputValue += "(SKU: " + item.sku + ")";
    }

    let list = watch("list");
    let find = list && list.find((e) => e.attribute_id == item.id);

    if (find) {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Your Product is already add ",
        life: 3000,
      });
    } else {
      append({
        product_name: inputValue,
        product_id: Number(item.product.id),
        other: item,
        attribute_id: Number(item.id),
        quantity: "",
        price: Number(item.unit_price || item.price || 0),
        discount: 0,
        total: "",
      });
    }
  };

  // Model Hide
  const hideModel = () => {
    setModelShow(false);
    setSelectCustomer("");
    reset({
      date: new Date(),
      quotation_id: "",
      client_id: "",
      note: "",
      payment_term: "",
      list: [],
    });
  };

  // Handle create new work order
  const handleCreateWorkOrder = () => {
    setStatus("create");
    setSelectCustomer("");
    reset({
      date: new Date(),
      quotation_id: "",
      client_id: "",
      note: "",
      payment_term: "",
      list: [],
    });
    setModelShow(true);
  };

  {
    /*Table Header*/
  }
  const TableHeader = ({ search, setSearch }) => {
    return (

      <>
        <div className="flex items-center gap-2">
          {permission.includes('work_order_create') && (
            <Button
              type="button"
              icon={<span className="pi pi-plus text-sm pr-1" />}
              label="Add"
              onClick={handleCreateWorkOrder}
              className="p-button-success h-[41px] text-[14px]"
            />
          )}

        </div>
        <div className="p-input-icon-left h-10">
          <i className="pi pi-search" />
          <InputText
            className="h-[41px] w-48"
            placeholder="Search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </>

    );
  };

  // Model Footer Content
  const footerContent = (
    <div className="grid grid-cols-12">
      <div className="col-span-12 flex justify-end">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={hideModel}
          className="p-button-text w-13 text-sm"
        />
        <Button
          label="Save"
          type="submit"
          onClick={() => {
            FormSubmit.current.dispatchEvent(
              new Event("submit", { bubbles: true })
            );
          }}
          icon="pi pi-check"
          className="p-button-text w-13 text-sm"
        />
      </div>
    </div>
  );

  // set Error Message Multiple field
  const getFormErrorMessageMultiple = (name, index = null) => {
    return errors["list"] &&
      errors["list"][index] &&
      errors["list"][index][name] ? (
      <small className="p-error">
        {errors["list"][index][name]["message"]}
      </small>
    ) : (
      ""
    );
  };

  // set Error Message Multiple single Field
  const getFormErrorMessageSingle = (name) => {
    return errors[name] ? (
      <small className="p-error">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };

  // Format date to YYYY-MM-DD for MySQL
  const formatDateForDB = (date) => {
    if (!date) return null;
    if (date instanceof Date) {
      return date.toISOString().split("T")[0];
    }
    if (typeof date === "string") {
      return date.split("T")[0];
    }
    return null;
  };

  const storeWorkOrder = (data) => {
    if (data.list.length != 0) {
      const formattedData = {
        ...data,
        date: formatDateForDB(data.date),
      };
      axios
        .post(route("work-order.store"), formattedData)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
          refreshData();
          setSelectCustomer("");
          reset({
            date: new Date(),
            quotation_id: "",
            client_id: "",
            note: "",
            list: [],
          });
          setModelShow(false);
        })
        .catch((error) => {
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail:
              error.response?.data?.message ||
              "Failed to create work order",
            life: 3000,
          });
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must need a product",
        life: 3000,
      });
    }
  };

  const updateWorkOrder = (data) => {
    if (data.list.length != 0) {
      const formattedData = {
        ...data,
        date: formatDateForDB(data.date),
      };
      axios
        .put(route("work-order.update", data.id), formattedData)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
          // refreshData();
          // console.log(response.data);
          setSelectCustomer("");
          reset({
            date: new Date(),
            quotation_id: "",
            client_id: "",
            note: "",
            list: [],
          });
          setModelShow(false);
        })
        .catch((error) => {
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail:
              error.response?.data?.message ||
              "Failed to update work order",
            life: 3000,
          });
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must need a product",
        life: 3000,
      });
    }
  };

  // Data Delete
  const handelDelete = (e) => {
    const id = e.currentTarget.getAttribute("data-id");

    confirmPopup({
      target: e.currentTarget,
      message: "Do you want to delete this record?",
      icon: "pi pi-info-circle",
      acceptClassName: "p-button-danger",
      accept() {
        axios
          .delete(route("work-order.destroy", id))
          .then((response) => {
            refreshData();
            toast.current.show({
              severity: "info",
              summary: "Confirmed",
              detail: response.data.success,
              life: 3000,
            });
          })
          .catch((error) => {
            toast.current.show({
              severity: "warn",
              summary: "Rejected",
              detail: error.response?.data?.error || "Failed to delete",
              life: 3000,
            });
          });
      },
      reject() {
        toast.current.show({
          severity: "warn",
          summary: "Rejected",
          detail: "You have rejected",
          life: 3000,
        });
      },
    });
  };

  const statusBodyTemplate = (rowData) => {
    const statusMap = {
      pending: { label: "Pending", badgeClass: "pending" },
      in_progress: { label: "In Progress", badgeClass: "pending" },
      completed: { label: "Completed", badgeClass: "complite" },
      cancelled: { label: "Cancelled", badgeClass: "new" },
    };
    const status = statusMap[rowData.status] || statusMap.pending;
    return (
      <div className="flex flex-col gap-1 items-center">
        {rowData.approval_status == 'draft' || !rowData.approval_status ? (
          <b className={`product-badge ${status.badgeClass}`}>
            {status.label}
          </b>
        ) : null}
        {rowData.approval_status && rowData.approval_status !== 'draft' && (
          <span
            className={`px-2 py-1 rounded text-xs font-semibold ${rowData.approval_status === 'approved'
              ? 'bg-green-100 text-green-800'
              : rowData.approval_status === 'rejected'
                ? 'bg-red-100 text-red-800'
                : 'bg-yellow-100 text-yellow-800'
              }`}
            title={`Approval Status: ${rowData.approval_status}`}
          >
            {rowData.approval_status?.toUpperCase()}
          </span>
        )}
      </div>
    );
  };

  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium">Work Order</h2>
          <p className="text-skin-sub-header font-semibold text-xs">
            Home - Work Order
          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />
      {/* View Table*/}
      <div className="card">
        <ServerSideDataTable
          key={refreshTrigger}
          fetchUrl={route("work-order.view")}
          emptyMessage="No work order found."
          headerActions={TableHeader}
        >
          <Column
            field="work_order_no"
            header="Work Order No"
            className="text-left"
            style={{ minWidth: "120px" }}
          />
          <Column
            body={(e) =>
              new Date(e.date).toLocaleDateString("en-us")
            }
            header="Date"
            className="text-left"
            style={{ minWidth: "100px" }}
          />
          <Column
            header="Quotation"
            body={(rowData) =>
              rowData.quotation
                ? `QTN-${rowData.quotation.quotation_number}`
                : "N/A"
            }
            className="text-left"
            style={{ minWidth: "120px" }}
          />
          <Column
            field="client.name"
            header="Client"
            className="text-left"
            style={{ minWidth: "150px" }}
          />
          <Column
            field="grand_total"
            header="Total Amount"
            body={(rowData) =>
              `৳${Number(rowData.grand_total).toFixed(2)}`
            }
            className="text-left"
            style={{ minWidth: "120px" }}
          />
          <Column
            body={statusBodyTemplate}
            header="Status"
            bodyClassName="text-center"
            style={{ minWidth: "120px" }}
          />
          <Column
            header="Action"
            body={(rowData) => (
              <div className="flex flex-wrap gap-1 justify-center">
                <ConfirmPopup />
                {permission.includes('work_order_view') && (
                  <Button
                    icon="pi pi-eye"
                    title="View Details"
                    onClick={() => {
                      window.location.href = route("work-order.show", rowData.id);
                    }}
                    className="p-button-rounded p-button-help px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                    tooltip="View"
                    tooltipOptions={{ position: "top" }}
                  />
                )}
                {permission.includes('work_order_edit') && (
                  <Button
                    icon="pi pi-pencil"
                    onClick={() => {
                      setModelShow(true);
                      setStatus("update");
                      const customerName = rowData.client
                        ? `${rowData.client.name}${rowData.client.code
                          ? ` (${rowData.client.code})`
                          : ""
                        }`
                        : "";
                      setSelectCustomer(customerName);
                      setSelectedClient(rowData.client || null);
                      reset({
                        id: rowData.id,
                        date: new Date(rowData.date),
                        quotation_id: rowData.quotation_id
                          ? Number(rowData.quotation_id)
                          : "",
                        client_id: rowData.client_id
                          ? Number(rowData.client_id)
                          : "",
                        note: rowData.note || "",
                        payment_term: rowData.payment_term || "",
                        list: rowData.work_order_details.map(
                          (item) => {
                            return {
                              product_name:
                                item.product_name,
                              product_id: Number(
                                item.product_id
                              ),
                              attribute_id: Number(
                                item.attribute_id
                              ),
                              quantity: Number(
                                item.quantity
                              ),
                              unit_price: Number(
                                item.price
                              ),
                              price: Number(
                                item.price
                              ),
                              discount:
                                Number(
                                  item.discount
                                ) || 0,
                              total: Number(item.total),
                            };
                          }
                        ),
                      });
                    }}
                    className="p-button-rounded p-button-success px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                    tooltip="Edit"
                    tooltipOptions={{ position: "top" }}
                  />
                )}
                <Button
                  icon="pi pi-file"
                  title="Manage Documents"
                  onClick={() => {
                    setSelectedWorkOrderForDocs(rowData);
                    setDocumentModalVisible(true);
                  }}
                  className="p-button-rounded p-button-secondary px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                  tooltip="Manage Documents"
                  tooltipOptions={{ position: "top" }}
                />
                {rowData.approval_status === 'draft' || !rowData.approval_status ? (
                  <Button
                    icon="pi pi-send"
                    title="Send for Approval"
                    onClick={() => {
                      setSelectedWorkOrderForApproval(rowData);
                      setApprovalModalVisible(true);
                    }}
                    className="p-button-rounded p-button-primary px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                    tooltip="Send for Approval"
                    tooltipOptions={{ position: "top" }}
                  />
                ) : rowData.approval_status === 'rejected' ? (
                  <Button
                    icon="pi pi-refresh"
                    title="Reapply for Approval"
                    onClick={() => {
                      setSelectedWorkOrderForApproval(rowData);
                      setApprovalModalVisible(true);
                    }}
                    className="p-button-rounded p-button-primary px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                    tooltip="Reapply for Approval"
                    tooltipOptions={{ position: "top" }}
                  />
                ) : null}
                {permission.includes('work_order_delete') && (
                  <Button
                    icon="pi pi-trash"
                    data-id={rowData.id}
                    onClick={handelDelete}
                    className="p-button-rounded p-button-warning px-2 py-2 w-9 h-9 sm:w-10 sm:h-10 font-medium"
                    tooltip="Delete"
                    tooltipOptions={{ position: "top" }}
                  />
                )}
              </div>
            )}
            dataType="boolean"
            bodyClassName="text-center"
            style={{ minWidth: "100px" }}
          />
        </ServerSideDataTable>
      </div>
      {/* View Table End*/}

      {/* Create Model*/}
      <Dialog
        header={() => (
          <div className="flex items-center gap-2">
            <i
              className={`pi ${status === "create"
                ? "pi-plus-circle"
                : "pi-pencil"
                } text-xl`}
            ></i>
            <span className="text-xl font-semibold">
              {status === "create"
                ? "Create Work Order"
                : "Update Work Order"}
            </span>
          </div>
        )}
        visible={modelShow}
        className="w-full h-full sm:w-[90vw] md:w-[85vw]"
        footer={footerContent}
        onHide={hideModel}
      >
        <form
          onSubmit={
            status == "create"
              ? handleSubmit(storeWorkOrder)
              : handleSubmit(updateWorkOrder)
          }
          ref={FormSubmit}
          onKeyPress={(event) => {
            if (event.key === "Enter") {
              event.preventDefault();
            }
          }}
        >
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-12 gap-6 p-4 pt-10 bg-gray-50 rounded-lg">
            {/* Date */}
            <div className="field col-span-12 md:col-span-3 min-w-0">
              <Controller
                name="date"
                control={control}
                rules={{ required: "Date is required." }}
                render={({ field, fieldState }) => (
                  <span className="p-float-label block">
                    <Calendar
                      id="date"
                      inputId={field.name}
                      value={field.value}
                      onChange={(e) =>
                        field.onChange(e.value)
                      }
                      className="w-full h-11"
                      inputClassName="w-full h-11"
                    />
                    <label htmlFor="date">Date</label>
                  </span>
                )}
              />
              {getFormErrorMessageSingle("date")}
            </div>

            {/* Quotation */}
            <div className="field col-span-12 md:col-span-3 min-w-0">
              <Controller
                name="quotation_id"
                control={control}
                render={({ field, fieldState }) => (
                  <span className="p-float-label block">
                    <Dropdown
                      showClear={true}
                      options={quotations}
                      optionLabel="label"
                      optionValue="id"
                      value={field.value}
                      onChange={(event) => {
                        field.onChange(event.value ?? "");
                        handleQuotationChange(event.value);
                      }}
                      placeholder="Select a quotation"
                      className={`${classNames({
                        "p-invalid":
                          fieldState.invalid,
                      })} w-full h-11`}
                    />
                    <label htmlFor="quotation_id">Quotation</label>
                  </span>
                )}
              />
            </div>

            {/* Client */}
            <div className="field col-span-12 md:col-span-3 min-w-0">
              <Controller
                name="client_id"
                control={control}
                render={({ field }) => (
                  <CustomerDropdown
                    selectedValue={selectCustomer}
                    onSelect={(customer) => {
                      setSelectCustomer(
                        customer
                          ? `${customer.name}${customer.code
                            ? ` (${customer.code})`
                            : ""
                          }`
                          : ""
                      );
                      setSelectedClient(customer);
                      field.onChange(customer?.id || "");
                    }}
                    showLabel={false}
                    className="w-full"
                    inputClassName="w-full h-11 rounded-lg"
                  />
                )}
              />

            </div>

            {/* Note */}
            <div className="field col-span-12 md:col-span-3 min-w-0">
              <Controller
                name="note"
                control={control}
                render={({ field, fieldState }) => (
                  <span className="p-float-label block">
                    <InputText
                      id={field.name}
                      {...field}
                      className={`${classNames({
                        "p-invalid":
                          fieldState.invalid,
                      })} w-full h-11`}
                    />
                    <label htmlFor={field.name}>
                      Note (optional)
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingle("note")}
            </div>

            {/* Payment Term */}
            <div className="field col-span-12 md:col-span-3 min-w-0">
              <Controller
                name="payment_term"
                control={control}
                render={({ field, fieldState }) => (
                  <span className="p-float-label block">
                    <InputText
                      id={field.name}
                      {...field}
                      className={`${classNames({
                        "p-invalid":
                          fieldState.invalid,
                      })} w-full h-11`}
                    />
                    <label htmlFor={field.name}>
                      Payment Term
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingle("payment_term")}
            </div>

            {/* Product (centered on md+, full-width on mobile) */}
            <div className="field col-span-12 md:col-span-10 md:col-start-2 min-w-0">
              <Controller
                name="remark"
                control={control}
                render={({ field, fieldState }) => (
                  <ProductDropdown
                    field={field}
                    selectedItem={selectedItem}
                  />
                )}
              />
            </div>
          </div>

          <div
            className="grid grid-cols-12 gap-6 mt-10 h-[80%] md:h-[300px] xl:h-[500px] overflow-y-auto pt-6"
            ref={scroll}
          >
            {fields.map((item, index) => (
              <DynamicFieldGroup
                key={item.id}
                control={control}
                watch={watch}
                setValue={setValue}
                remove={remove}
                index={index}
                getFormErrorMessageMultiple={
                  getFormErrorMessageMultiple
                }
                mode="work_order"
                readOnlyFields={["product_name", "total"]}
              />
            ))}
          </div>
          <div className="bg-white p-6 rounded-2xl shadow-sm border-t">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
              {list && (
                <div className="text-lg font-semibold">
                  <span>Total QTY: </span>
                  <span className="text-blue-600">
                    {list.reduce(
                      (acc, item) =>
                        acc + Number(item.quantity || 0),
                      0
                    )}
                  </span>
                </div>
              )}
              {list && (
                <div className="flex justify-end items-center text-lg font-semibold">
                  <span>Total Amount:</span>
                  <span className="text-blue-600 pl-8">
                    ৳{list.reduce(
                      (acc, item) => acc + Number(item.total || 0),
                      0
                    ).toFixed(2)}
                  </span>
                </div>
              )}
            </div>
          </div>
        </form>
      </Dialog>
      {/* Create Model End*/}

      {/* Document Management Modal */}
      <Dialog
        header="Manage Documents"
        visible={documentModalVisible}
        style={{ width: "90vw", maxWidth: "800px" }}
        onHide={() => {
          setDocumentModalVisible(false);
          setSelectedWorkOrderForDocs(null);
        }}
        footer={
          <div className="flex justify-end">
            <Button
              label="Close"
              icon="pi pi-times"
              className="p-button-text"
              onClick={() => {
                setDocumentModalVisible(false);
                setSelectedWorkOrderForDocs(null);
              }}
            />
          </div>
        }
      >
        {selectedWorkOrderForDocs && (
          <div className="p-4">
            <div className="mb-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
              <div className="text-sm font-semibold text-blue-900">
                Work Order: {selectedWorkOrderForDocs.work_order_no}
              </div>
              <div className="text-xs text-blue-700 mt-1">
                Date: {new Date(selectedWorkOrderForDocs.date).toLocaleDateString()}
              </div>
            </div>
            <DocumentUpload
              documentableType="App\\Models\\WorkOrderMaster"
              documentableId={selectedWorkOrderForDocs.id}
              showLabel={true}
              label="Documents"
            />
          </div>
        )}
      </Dialog>

      {/* Send for Approval Modal */}
      <SendForApprovalModal
        visible={approvalModalVisible}
        onHide={() => {
          setApprovalModalVisible(false);
          setSelectedWorkOrderForApproval(null);
        }}
        approvableType="WorkOrderMaster"
        approvableId={selectedWorkOrderForApproval?.id}
        onSuccess={() => {
          refreshData();
        }}
      />
    </AuthenticatedLayout>
  );
}
