import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Laptop } from "lucide-react";
import Dashboard from "./CRMpages/Dashboard";
import Customers from "./CRMpages/Customers";
import Inventory from "./CRMpages/Inventory";
import Rentals from "./CRMpages/Rentals";
import Sales from "./CRMpages/Sales";
import Expenses from "./CRMpages/Expenses";
import axios from "axios";

const CRMDashboard = () => {
  const [activeTab, setActiveTab] = useState("dashboard");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [customers, setCustomers] = useState([]);
  const [inventory, setInventory] = useState([]);
  const [rentals, setRentals] = useState([]);
  const [sales] = useState([]);
  const [expenses] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState("");
  const [editingItem, setEditingItem] = useState(null);

  const api = useMemo(() => {
    const instance = axios.create({
      baseURL: process.env.REACT_APP_BASE_URL,
    });

    instance.interceptors.request.use((config) => {
      const token = localStorage.getItem("adminToken");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    return instance;
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);

        const [customersRes, inventoryRes, rentalsRes] = await Promise.all([
          api.get("/api/users/customers"),
          api.get("/api/laptops"),
          api.get("/api/equipment/activity"),
        ]);

        setCustomers(customersRes.data.customers);
        setInventory(inventoryRes.data);
        setRentals(rentalsRes.data);
      } catch (err) {
        setError(err.response?.data?.message || err.message);
        console.error("Error fetching data:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [api]);

  const formatCurrency = useCallback((amount) => {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount || 0);
  }, []);

  const handleSave = useCallback(
    async (type, data) => {
      try {
        const lowerType = type.toLowerCase();
        const isEdit = !!editingItem;
        let endpoint = "";
        let method = "POST";

        if (isEdit) {
          method = "PUT";
          switch (lowerType) {
            case "customer":
              endpoint = `/api/users/customers/${editingItem._id}`;
              break;
            case "laptop":
              endpoint = `/api/laptops/${editingItem._id}`;
              // Convert frontend field names to backend field names
              data = {
                ...data,
                Brand: data.brand,
                RAM: data.ram,
                Storage: data.storage,
                Graphic: data.graphic,
                Display: data.display,
              };
              break;
            case "rental":
              endpoint = `/api/equipment/activity/${editingItem._id}`;
              break;
            default:
              throw new Error("Invalid type for update");
          }
        } else {
          switch (lowerType) {
            case "customer":
              endpoint = `/api/users/customers`;
              break;
            case "laptop":
              endpoint = `/api/laptops`;
              // Convert frontend field names to backend field names
              data = {
                ...data,
                Brand: data.brand,
                RAM: data.ram,
                Storage: data.storage,
                Graphic: data.graphic,
                Display: data.display,
              };
              break;
            case "rental":
              endpoint = `/api/equipment/activity`;
              break;
            default:
              throw new Error("Invalid type for creation");
          }
        }

        const response = await api[method.toLowerCase()](endpoint, data);

        switch (lowerType) {
          case "customer":
            setCustomers((prev) =>
              isEdit
                ? prev.map((c) =>
                    c._id === editingItem._id ? response.data : c
                  )
                : [...prev, response.data]
            );
            break;
          case "laptop":
            setInventory((prev) =>
              isEdit
                ? prev.map((i) =>
                    i._id === editingItem._id ? response.data : i
                  )
                : [...prev, response.data]
            );
            break;
          case "rental":
            setRentals((prev) =>
              isEdit
                ? prev.map((r) =>
                    r._id === editingItem._id ? response.data : r
                  )
                : [...prev, response.data]
            );
            break;
          default:
            break;
        }

        setShowModal(false);
        setEditingItem(null);
      } catch (err) {
        setError(err.response?.data?.message || err.message);
        console.error("Error saving data:", err);
      }
    },
    [api, editingItem]
  );

  const handleDelete = useCallback(
    async (type, id) => {
      if (
        window.confirm(
          `Are you sure you want to delete this ${type.toLowerCase()}?`
        )
      ) {
        try {
          await api.delete(`/api/${type.toLowerCase()}s/${id}`);

          switch (type.toLowerCase()) {
            case "customer":
              setCustomers((prev) => prev.filter((c) => c._id !== id));
              break;
            case "laptop":
              setInventory((prev) => prev.filter((i) => i._id !== id));
              break;
            case "rental":
              setRentals((prev) => prev.filter((r) => r._id !== id));
              break;
            default:
              break;
          }
        } catch (err) {
          setError(err.response?.data?.message || err.message);
          console.error("Error deleting item:", err);
        }
      }
    },
    [api]
  );

  const openModal = useCallback((type, item = null) => {
    setModalType(type);
    setEditingItem(item);
    setShowModal(true);
  }, []);

  const Modal = React.memo(
    ({ type, item, onSave, onClose, customers, inventory }) => {
      const getDefaultFormData = useCallback((type) => {
        switch (type.toLowerCase()) {
          case "customer":
            return {
              name: "",
              email: "",
              mobile: "",
              address: "",
              company: "",
              status: "Active",
            };
          case "laptop":
            return {
              name: "",
              processor: "",
              price: "",
              ram: "",
              storage: "",
              graphic: "",
              display: "",
              category: "",
              brand: "",
              serialNumber: "",
              mode: "buy",
              status: "available",
            };
          case "rental":
            return {
              customerId: "",
              laptopId: "",
              startDate: "",
              endDate: "",
              totalAmount: 0,
              advancePaid: 0,
            };
          default:
            return {};
        }
      }, []);

      const [formData, setFormData] = useState(() => {
        if (item) {
          const defaultData = getDefaultFormData(type);
          return {
            ...defaultData,
            ...item,
            brand: item.Brand || item.brand || "",
            ram: item.RAM || item.ram || "",
            storage: item.Storage || item.storage || "",
            graphic: item.Graphic || item.graphic || "",
            display: item.Display || item.display || "",
            price: item.price || "",
            totalAmount: item.totalAmount || 0,
            advancePaid: item.advancePaid || 0,
            startDate: item.startDate ? item.startDate.split("T")[0] : "",
            endDate: item.endDate ? item.endDate.split("T")[0] : "",
          };
        }
        return getDefaultFormData(type);
      });

      const [errors, setErrors] = useState({});

      useEffect(() => {
        if (item) {
          const defaultData = getDefaultFormData(type);
          setFormData({
            ...defaultData,
            ...item,
            brand: item.Brand || item.brand || "",
            ram: item.RAM || item.ram || "",
            storage: item.Storage || item.storage || "",
            graphic: item.Graphic || item.graphic || "",
            display: item.Display || item.display || "",
            price: item.price || "",
            totalAmount: item.totalAmount || 0,
            advancePaid: item.advancePaid || 0,
            startDate: item.startDate ? item.startDate.split("T")[0] : "",
            endDate: item.endDate ? item.endDate.split("T")[0] : "",
          });
        } else {
          setFormData(getDefaultFormData(type));
        }
        setErrors({});
      }, [item, type, getDefaultFormData]);

      const handleChange = useCallback((e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
          ...prev,
          [name]: value,
        }));
      }, []);

      const validateForm = useCallback(() => {
        const newErrors = {};

        switch (type.toLowerCase()) {
          case "customer":
            if (!formData.name) newErrors.name = "Name is required";
            if (!formData.email) newErrors.email = "Email is required";
            if (!formData.mobile) newErrors.mobile = "Mobile is required";
            break;
          case "laptop":
            if (!formData.name) newErrors.name = "Laptop name is required";
            if (!formData.price || formData.price <= 0)
              newErrors.price = "Valid price required";
            if (!formData.processor)
              newErrors.processor = "Processor is required";
            if (!formData.ram) newErrors.ram = "RAM is required";
            if (!formData.brand) newErrors.brand = "Brand is required";
            if (!formData.mode || !["buy", "rent"].includes(formData.mode))
              newErrors.mode = "Select mode: buy or rent";
            break;
          case "rental":
            if (!formData.customerId)
              newErrors.customerId = "Customer is required";
            if (!formData.laptopId) newErrors.laptopId = "Laptop is required";
            if (!formData.startDate)
              newErrors.startDate = "Start date is required";
            if (!formData.endDate) newErrors.endDate = "End date is required";
            break;
          default:
            break;
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
      }, [formData, type]);

      const handleSubmit = useCallback(
        async (e) => {
          e.preventDefault();
          if (validateForm()) {
            await onSave(type, formData);
          }
        },
        [formData, onSave, validateForm, type]
      );

      const renderFormFields = useCallback(() => {
        switch (type.toLowerCase()) {
          case "customer":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Name
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Email
                  </label>
                  <input
                    type="email"
                    name="email"
                    value={formData.email || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.email && (
                    <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Mobile
                  </label>
                  <input
                    type="text"
                    name="mobile"
                    value={formData.mobile || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.mobile && (
                    <p className="mt-1 text-sm text-red-600">{errors.mobile}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Address
                  </label>
                  <textarea
                    name="address"
                    value={formData.address || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Company
                  </label>
                  <input
                    type="text"
                    name="company"
                    value={formData.company || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Status
                  </label>
                  <select
                    name="status"
                    value={formData.status || "Active"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="Active">Active</option>
                    <option value="Inactive">Inactive</option>
                  </select>
                </div>
              </div>
            );
          case "laptop":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Laptop Name
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Brand
                  </label>
                  <input
                    type="text"
                    name="brand"
                    value={formData.brand || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.brand && (
                    <p className="mt-1 text-sm text-red-600">{errors.brand}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Processor
                  </label>
                  <input
                    type="text"
                    name="processor"
                    value={formData.processor || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.processor && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.processor}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    RAM
                  </label>
                  <input
                    type="text"
                    name="ram"
                    value={formData.ram || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.ram && (
                    <p className="mt-1 text-sm text-red-600">{errors.ram}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Storage
                  </label>
                  <input
                    type="text"
                    name="storage"
                    value={formData.storage || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Graphics
                  </label>
                  <input
                    type="text"
                    name="graphic"
                    value={formData.graphic || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Display
                  </label>
                  <input
                    type="text"
                    name="display"
                    value={formData.display || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Category
                  </label>
                  <input
                    type="text"
                    name="category"
                    value={formData.category || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Serial Number
                  </label>
                  <input
                    type="text"
                    name="serialNumber"
                    value={formData.serialNumber || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Price (₹)
                  </label>
                  <input
                    type="number"
                    name="price"
                    value={formData.price || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.price && (
                    <p className="mt-1 text-sm text-red-600">{errors.price}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Mode
                  </label>
                  <select
                    name="mode"
                    value={formData.mode || "buy"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="buy">Buy</option>
                    <option value="rent">Rent</option>
                  </select>
                  {errors.mode && (
                    <p className="mt-1 text-sm text-red-600">{errors.mode}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Status
                  </label>
                  <select
                    name="status"
                    value={formData.status || "available"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="available">Available</option>
                    <option value="rented">Rented</option>
                    <option value="sold">Sold</option>
                    <option value="maintenance">Maintenance</option>
                  </select>
                </div>
              </div>
            );
          case "rental":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Customer
                  </label>
                  <select
                    name="customerId"
                    value={formData.customerId || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="">Select Customer</option>
                    {customers.map((customer) => (
                      <option key={customer._id} value={customer._id}>
                        {customer.name}
                      </option>
                    ))}
                  </select>
                  {errors.customerId && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.customerId}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Laptop
                  </label>
                  <select
                    name="laptopId"
                    value={formData.laptopId || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="">Select Laptop</option>
                    {inventory
                      .filter((item) => item.status === "available")
                      .map((laptop) => (
                        <option key={laptop._id} value={laptop._id}>
                          {laptop.Brand || laptop.brand} {laptop.name}
                        </option>
                      ))}
                  </select>
                  {errors.laptopId && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.laptopId}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Start Date
                  </label>
                  <input
                    type="date"
                    name="startDate"
                    value={formData.startDate || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.startDate && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.startDate}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    End Date
                  </label>
                  <input
                    type="date"
                    name="endDate"
                    value={formData.endDate || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.endDate && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.endDate}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Total Amount (₹)
                  </label>
                  <input
                    type="number"
                    name="totalAmount"
                    value={formData.totalAmount || 0}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Advance Paid (₹)
                  </label>
                  <input
                    type="number"
                    name="advancePaid"
                    value={formData.advancePaid || 0}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
              </div>
            );
          default:
            return null;
        }
      }, [type, formData, errors, handleChange, customers, inventory]);

      return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold mb-4 text-blue-800">
              {item ? "Edit" : "Add"} {type}
            </h3>
            <form onSubmit={handleSubmit}>
              {renderFormFields()}
              <div className="flex gap-2 pt-4">
                <button
                  type="submit"
                  className="flex-1 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 font-medium"
                >
                  Save {type}
                </button>
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 bg-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-400 font-medium"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      );
    }
  );

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex justify-center items-center h-screen text-red-500">
        <div className="bg-red-100 p-4 rounded-lg max-w-md">
          <div className="flex items-center">
            <h3 className="font-medium">Error loading data</h3>
          </div>
          <p className="mt-2 text-sm">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <nav className="bg-white shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center">
              <Laptop className="h-8 w-8 text-blue-600" />
              <span className="ml-2 text-xl font-semibold text-gray-900">
                Aura Tech CRM
              </span>
            </div>
            <div className="hidden md:flex items-center space-x-4">
              {[
                "dashboard",
                "customers",
                "inventory",
                "rentals",
                "sales",
                "expenses",
              ].map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    activeTab === tab
                      ? "bg-blue-100 text-blue-700"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  {tab.charAt(0).toUpperCase() + tab.slice(1)}
                </button>
              ))}
            </div>
          </div>
        </div>
      </nav>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {activeTab === "dashboard" && (
          <Dashboard
            customers={customers}
            inventory={inventory}
            rentals={rentals}
            sales={sales}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "customers" && (
          <Customers
            customers={customers}
            onEdit={(item) => openModal("Customer", item)}
            onDelete={(id) => handleDelete("Customer", id)}
            onAdd={() => openModal("Customer")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "inventory" && (
          <Inventory
            inventory={inventory}
            onEdit={(item) => openModal("Laptop", item)}
            onDelete={(id) => handleDelete("Laptop", id)}
            onAdd={() => openModal("Laptop")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "rentals" && (
          <Rentals
            rentals={rentals}
            customers={customers}
            inventory={inventory}
            onEdit={(item) => openModal("Rental", item)}
            onDelete={(id) => handleDelete("Rental", id)}
            onAdd={() => openModal("Rental")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "sales" && (
          <Sales
            sales={sales}
            customers={customers}
            inventory={inventory}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "expenses" && (
          <Expenses expenses={expenses} formatCurrency={formatCurrency} />
        )}
      </main>

      {showModal && (
        <Modal
          type={modalType}
          item={editingItem}
          onSave={(data) => handleSave(modalType, data)}
          onClose={() => {
            setShowModal(false);
            setEditingItem(null);
          }}
          customers={customers}
          inventory={inventory}
        />
      )}
    </div>
  );
};

export default React.memo(CRMDashboard);






Solution:
Update the handleSave function in your CRMDashboard.js:

jsx
const handleSave = useCallback(
  async (type, data) => {
    try {
      const lowerType = type.toLowerCase();
      const isEdit = !!editingItem;
      let endpoint = "";
      let method = "POST";
      let payload = data;

      // Transform data for laptops to match backend expectations
      if (lowerType === "laptop") {
        payload = {
          ...data,
          // Map frontend field names to backend field names
          Brand: data.brand,
          RAM: data.ram,
          Storage: data.storage,
          Graphic: data.graphic,
          Display: data.display,
          // Ensure price is a number
          price: parseFloat(data.price) || 0
        };
      }

      if (isEdit) {
        method = "PUT";
        switch (lowerType) {
          case "customer":
            endpoint = `/api/users/customers/${editingItem._id}`;
            break;
          case "laptop":
            endpoint = `/api/laptops/${editingItem._id}`;
            break;
          case "rental":
            endpoint = `/api/equipment/activity/${editingItem._id}`;
            break;
          default:
            throw new Error("Invalid type for update");
        }
      } else {
        switch (lowerType) {
          case "customer":
            endpoint = `/api/users/customers`;
            break;
          case "laptop":
            endpoint = `/api/laptops`;
            break;
          case "rental":
            endpoint = `/api/equipment/activity`;
            break;
          default:
            throw new Error("Invalid type for creation");
        }
      }

      const response = await api[method.toLowerCase()](endpoint, payload);

      // Rest of your success handling...
    } catch (err) {
      console.error("Error saving data:", err);
      setError(err.response?.data?.message || err.message);
      
      // Log the exact error details from the server if available
      if (err.response?.data?.errors) {
        console.error("Validation errors:", err.response.data.errors);
      }
    }
  },
  [api, editingItem]
);
Update the Modal component's validation:

jsx
const validateForm = useCallback(() => {
  const newErrors = {};

  switch (type.toLowerCase()) {
    case "laptop":
      if (!formData.name || validator.isEmpty(formData.name.trim())) {
        newErrors.name = "Laptop name is required";
      }
      if (!formData.price || isNaN(parseFloat(formData.price)) {
        newErrors.price = "Valid price is required";
      }
      if (!formData.processor || validator.isEmpty(formData.processor.trim())) {
        newErrors.processor = "Processor is required";
      }
      if (!formData.ram || validator.isEmpty(formData.ram.trim())) {
        newErrors.ram = "RAM is required";
      }
      if (!formData.brand || validator.isEmpty(formData.brand.trim())) {
        newErrors.brand = "Brand is required";
      }
      if (!formData.mode || !["buy", "rent"].includes(formData.mode)) {
        newErrors.mode = "Select mode: buy or rent";
      }
      break;
    // ... other cases
  }

  setErrors(newErrors);
  return Object.keys(newErrors).length === 0;
}, [formData, type]);
Ensure proper data transformation in the Modal component:

jsx
const handleSubmit = useCallback(
  async (e) => {
    e.preventDefault();
    if (validateForm()) {
      // Transform data before saving
      const dataToSave = {
        ...formData,
        price: parseFloat(formData.price) || 0
      };
      await onSave(type, dataToSave);
    }
  },
  [formData, onSave, validateForm, type]
);
Key Fixes:
Field Name Consistency: Ensures frontend field names (brand, ram) are properly mapped to backend expectations (Brand, RAM)

Data Type Validation: Explicitly converts price to a number before sending

Better Error Handling: Provides more detailed error logging to help diagnose issues

Form Validation: Strengthens validation to prevent invalid data submission

Additional Debugging Steps:
Check the Network Request:

Open Chrome DevTools (F12)

Go to the Network tab

Look for the failed PUT request

Check the "Payload" and "Response" tabs to see what was sent and what error was returned

Verify Backend Validation:

Ensure your backend is properly validating the incoming data

Check if there are any required fields you might be missing

Test with Postman:

Try making the same request with Postman to isolate whether the issue is frontend or backend

This solution should resolve the 400 Bad Request error by ensuring proper data formatting and field name consistency between your frontend and backend.






implement this solution and give me final fully updated code.