import { useEffect, useState } from "react";
import { api } from "./api";

import AuthView from "./components/AuthView";
import Sidebar from "./components/Sidebar";
import DashboardTab from "./components/tabs/DashboardTab";
import ProductsTab from "./components/tabs/ProductsTab";
import OrdersTab from "./components/tabs/OrdersTab";
import CustomersTab from "./components/tabs/CustomersTab";
import ReportsTab from "./components/tabs/ReportsTab";


const tabs = ["Dashboard", "Products", "Orders", "Customers", "Reports"];

const phoneRgex = /^\+?[0-9]{10,15}$/;


const formatDateSafe = (value) => {
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? "-" : date.toISOString().slice(0, 10);
};

export default function App() {
  const [user, setUser] = useState(null);
  const [auth, setAuth] = useState({ username: "", password: "" });
  const [isRegister, setIsRegister] = useState(false);
  const [activeTab, setActiveTab] = useState("Dashboard");
  const [error, setError] = useState("");

  const [products, setProducts] = useState([]);
  const [orders, setOrders] = useState([]);
  const [customers, setCustomers] = useState([]);

  const [reportDate, setReportDate] = useState(formatDateSafe(new Date()));
  const [reportRows, setReportRows] = useState([]);

  const [search, setSearch] = useState({ customers: "", orders: "", products: "" });

  const [productForm, setProductForm] = useState({
    productName: "",
    productQuantity: "",
    unitPrice: ""
  });
  const [orderForm, setOrderForm] = useState({ order_date: "", customer_name: "" });
  const [customerForm, setCustomerForm] = useState({
    cust_fname: "",
    cust_lname: "",
    location: "",
    telephone: "",
    ProductCode: "",
    order_number: "",
    quantity: 1,
    total_price: 0
  });

  const [editIds, setEditIds] = useState({ product: "", order: "", customer: "" });

  useEffect(() => {
    checkSession();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function checkSession() {
    try {
      const me = await api.get("/auth/me");
      if (me?.authenticated) {
        setUser(me);
        await loadData();
      } else {
        setUser(null);
      }
    } catch {
      setUser(null);
    }
  }

  async function loadData() {
    const [p, o, c] = await Promise.all([
      api.get("/products"),
      api.get("/orders"),
      api.get("/customers")
    ]);
    setProducts(p);
    setOrders(o);
    setCustomers(c);
  }

  async function handleAuthSubmit(e) {
    e.preventDefault();
    setError("");
    try {
      const path = isRegister ? "/auth/register" : "/auth/login";
      const data = await api.post(path, auth);
      setUser({ username: data.username });
      await loadData();
      setAuth({ username: "", password: "" });
    } catch (err) {
      setError(err.message);
    }
  }

  async function logout() {
    await api.post("/auth/logout", {});
    setUser(null);
    setProducts([]);
    setOrders([]);
    setCustomers([]);
    setReportRows([]);
  }

  async function saveProduct(e) {
    e.preventDefault();
    const payload = {
      productName: productForm.productName,
      productQuantity: Number(productForm.productQuantity),
      unitPrice: Number(productForm.unitPrice)
    };
    if (editIds.product) await api.put(`/products/${editIds.product}`, payload);
    else await api.post("/products", payload);

    setProductForm({ productName: "", productQuantity: "", unitPrice: "" });
    setEditIds((s) => ({ ...s, product: "" }));
    await loadData();
  }

  async function saveOrder(e) {
    e.preventDefault();
    setError("");

    const day = orderForm.order_date; // YYYY-MM-DD from <input type="date">
    if (!day) {
      setError("Please choose an order date.");
      return;
    }

    // Enforce unique order_date_key (frontend guard; backend also enforces it)
    const existingSameDay = orders.filter((o) => formatDateSafe(o.order_date) === day);
    const isEditing = Boolean(editIds.order);
    if (!isEditing && existingSameDay.length > 0) {
      setError("This date already has an order. Please choose another date.");
      return;
    }

    try {
      if (editIds.order) {
        // update order
        await api.put(`/orders/${editIds.order}`, {
          order_date: day,
          customer_name: ""
        });
      } else {
        // create order (customer_name is optional)
        await api.post("/orders", {
          order_date: day,
          customer_name: ""
        });
      }

      setOrderForm({ order_date: "", customer_name: "" });
      setEditIds((s) => ({ ...s, order: "" }));
      setError("");

      await loadData();
    } catch (err) {
      setError(err.message || "Failed to save order");
    }
  }
  async function saveCustomer(e) {
    e.preventDefault();
    setError("");

    if (!/^\+?[0-9]{10,15}$/.test(customerForm.telephone)) {
       window.alert("Telephone must be 10-15 digits (optionally starts with +).")
      // setError("Telephone must be 10-15 digits (optionally starts with +).");
      return;
    }

    const productId = customerForm.ProductCode?._id || customerForm.ProductCode;
    const orderId = customerForm.order_number?._id || customerForm.order_number;

    if (!productId) {
      setError("Please select a product.");
      return;
    }

    if (!orderId) {
      setError("Please select an order.");
      return;
    }

    const qty = Number(customerForm.quantity);

    const payload = {
      ...customerForm,
      ProductCode: productId,
      order_number: orderId,
      quantity: qty,
      total_price: Number(customerForm.total_price)
    };

    try {
      const fullName = `${customerForm.cust_fname} ${customerForm.cust_lname}`.trim();

      if (editIds.customer) {
        await api.put(`/customers/${editIds.customer}`, payload);
      } else {
        await api.post("/customers", payload);
      }

      // Auto update order customer name
      const selectedOrder = orders.find((o) => o._id === orderId);
      if (selectedOrder) {
        await api.put(`/orders/${selectedOrder._id}`, {
          ...selectedOrder,
          customer_name: fullName
        });
      }

      setCustomerForm({
        cust_fname: "",
        cust_lname: "",
        location: "",
        telephone: "",
        ProductCode: "",
        order_number: "",
        quantity: 1,
        total_price: 0
      });
      setEditIds((s) => ({ ...s, customer: "" }));

      await loadData();
      setError("");
    } catch (err) {
      setError(err.message || "Failed to save customer");
    }
  }

  async function loadDailyReport() {
    if (!reportDate) return;
    const rows = await api.get(`/reports/daily?date=${reportDate}`);
    setReportRows(rows);
  }

  function onProductChange(productId) {
    const selectedProduct = products.find((p) => p._id === productId);
    const qty = Number(customerForm.quantity || 0);
    const total = selectedProduct ? qty * Number(selectedProduct.unitPrice) : 0;
    setCustomerForm((prev) => ({ ...prev, ProductCode: productId, total_price: total }));
  }

  function onQuantityChange(qtyValue) {
    const qty = Number(qtyValue || 0);
    const selectedProduct = products.find((p) => p._id === customerForm.ProductCode);
    const total = selectedProduct ? qty * Number(selectedProduct.unitPrice) : 0;
    setCustomerForm((prev) => ({ ...prev, quantity: qtyValue, total_price: total }));
  }

  function onOrderChange(orderId) {
    const selectedOrder = orders.find((o) => o._id === orderId);
    if (selectedOrder?.customer_name) {
      const parts = selectedOrder.customer_name.trim().split(" ");
      const first = parts.shift() || "";
      const last = parts.join(" ");
      setCustomerForm((prev) => ({
        ...prev,
        order_number: orderId,
        cust_fname: first || prev.cust_fname,
        cust_lname: last || prev.cust_lname
      }));
      return;
    }
    setCustomerForm((prev) => ({ ...prev, order_number: orderId }));
  }

  const filteredCustomers = customers.filter((c) =>
    `${c.cust_fname} ${c.cust_lname} ${c.telephone} ${c.location}`.toLowerCase().includes(search.customers.toLowerCase())
  );
  const filteredOrders = orders.filter((o) =>
    `${formatDateSafe(o.order_date)}`
      .toLowerCase()
      .includes(search.orders.toLowerCase())
  );
  const filteredProducts = products.filter((p) =>
    `${p.productName}`.toLowerCase().includes(search.products.toLowerCase())
  );

  const selectedProduct = products.find((p) => p._id === customerForm.ProductCode);

  if (!user) {
    return (
      <div className="auth-wrap auth-gradient-bg">
        <form className="card auth-card modern-auth" onSubmit={handleAuthSubmit}>
          <h1>{isRegister ? "Register" : "Login"}</h1>
          <p>Beauty Warehouse CIMS</p>
          <input
            placeholder="Username"
            value={auth.username}
            onChange={(e) => setAuth({ ...auth, username: e.target.value })}
            required
          />
          <input
            type="password"
            placeholder="Password"
            value={auth.password}
            onChange={(e) => setAuth({ ...auth, password: e.target.value })}
            required
          />
          {error && <div className="error">{error}</div>}
          <button className="auth-primary-btn" type="submit">
            {isRegister ? "Create Account" : "Login"}
          </button>
          <button type="button" className="auth-secondary-btn" onClick={() => setIsRegister(!isRegister)}>
            {isRegister ? "Already have an account? Login" : "No account? Register"}
          </button>
        </form>
      </div>
    );
  }

  return (
    <div className="layout">
      <aside className="sidebar">
        <div className="brand">CIMS</div>
        <div className="menu">
          {tabs.map((t) => (
            <button key={t} className={activeTab === t ? "active menu-btn" : "menu-btn"} onClick={() => setActiveTab(t)}>
              <span className="icon">{t === "Dashboard" ? "" : t === "Products" ? "" : t === "Orders" ? "" : t === "Customers" ? "" : ""}</span>
              {t}
            </button>
          ))}
        </div>
        <button className="ghost logout-btn" onClick={logout}>Logout</button>
      </aside>

      <main className="content">
        <header>
          <h2>Welcome, {user.username}</h2>
        </header>

      {activeTab === "Dashboard" && (
        <section className="card">
          <h3>Dashboard</h3>
          <div className="grid">
            <div className="metric"><strong>{customers.length}</strong><span>Customers</span></div>
            <div className="metric"><strong>{orders.length}</strong><span>Orders</span></div>
            <div className="metric"><strong>{products.length}</strong><span>Products</span></div>
          </div>
        </section>
      )}

      {activeTab === "Products" && (
        <section className="card">
          <h3>Products</h3>
          <form onSubmit={saveProduct} className="grid">
            <input
              placeholder="Product Name"
              value={productForm.productName}
              onChange={(e) => setProductForm({ ...productForm, productName: e.target.value })}
              required
            />
            <input
              type="number"
              placeholder="Quantity"
              value={productForm.productQuantity}
              onChange={(e) => setProductForm({ ...productForm, productQuantity: e.target.value })}
              required
            />
            <input
              type="number"
              step="0.01"
              placeholder="Unit Price"
              value={productForm.unitPrice}
              onChange={(e) => setProductForm({ ...productForm, unitPrice: e.target.value })}
              required
            />
            <button type="submit">{editIds.product ? "Update Product" : "Add Product"}</button>
          </form>
          <input
            placeholder="Search products..."
            value={search.products}
            onChange={(e) => setSearch((s) => ({ ...s, products: e.target.value }))}
          />
          <table>
            <thead>
              <tr>
                <th>Name</th><th>Qty</th><th>Unit</th><th>Total</th><th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredProducts.map((p) => (
                <tr key={p._id}>
                  <td>{p.productName}</td>
                  <td>{p.productQuantity}</td>
                  <td>{p.unitPrice}</td>
                  <td>{p.totalPrice}</td>
                  <td>
                    <button onClick={() => { setProductForm({ productName: p.productName, productQuantity: p.productQuantity, unitPrice: p.unitPrice }); setEditIds((s) => ({ ...s, product: p._id })); }}>Edit</button>
                    <button onClick={async () => { await api.del(`/products/${p._id}`); await loadData(); }}>Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      )}

      {activeTab === "Orders" && (
        <section className="card">
          <h3>Orders</h3>
          <form onSubmit={saveOrder} className="grid">
            <input
              type="date"
              value={orderForm.order_date}
              onChange={(e) => setOrderForm({ order_date: e.target.value })}
              required
            />
            <button type="submit">{editIds.order ? "Update Order" : "Add Order"}</button>
          </form>
          <input
            placeholder="Search orders..."
            value={search.orders}
            onChange={(e) => setSearch((s) => ({ ...s, orders: e.target.value }))}
          />
          <table>
            <thead>
              <tr><th>Order Number</th><th>Order Date</th><th>Actions</th></tr>
            </thead>
            <tbody>
              {filteredOrders.map((o) => (
                <tr key={o._id}>
                  <td>{o.order_number || o._id.slice(-6).toUpperCase()}</td>
                  <td>{formatDateSafe(o.order_date)}</td>
                  <td>
                    <button onClick={() => { setOrderForm({ customer_name: o.customer_name || "", order_date: formatDateSafe(o.order_date) === "-" ? "" : formatDateSafe(o.order_date) }); setEditIds((s) => ({ ...s, order: o._id })); }}>Edit</button>
                    <button onClick={async () => { await api.del(`/orders/${o._id}`); await loadData(); }}>Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      )}

      {activeTab === "Customers" && (
        <section className="card">
          <h3>Customers</h3>
          <form onSubmit={saveCustomer} className="grid">
            <input placeholder="First Name" value={customerForm.cust_fname} onChange={(e) => setCustomerForm({ ...customerForm, cust_fname: e.target.value })} required aria-label="First Name" />
            <input placeholder="Last Name" value={customerForm.cust_lname} onChange={(e) => setCustomerForm({ ...customerForm, cust_lname: e.target.value })} required aria-label="Last Name" />
            <input placeholder="Location" value={customerForm.location} onChange={(e) => setCustomerForm({ ...customerForm, location: e.target.value })} required aria-label="Location" />
            <input placeholder="Telephone (+2507...)" value={customerForm.telephone} onChange={(e) => setCustomerForm({ ...customerForm, telephone: e.target.value })} required aria-label="Telephone" />
            <select value={customerForm.ProductCode} onChange={(e) => onProductChange(e.target.value)} required>
              <option value="">Select Product</option>
              {products.map((p) => <option key={p._id} value={p._id}>{p.productName}</option>)}
            </select>
            <select value={customerForm.order_number} onChange={(e) => onOrderChange(e.target.value)} required>
              <option value="">Select Order</option>
              {orders.map((o) => <option key={o._id} value={o._id}>{formatDateSafe(o.order_date)}</option>)}
            </select>
            <input
              type="number"
              min="1"
              placeholder="Quantity"
              value={customerForm.quantity}
              onChange={(e) => onQuantityChange(e.target.value)}
              required
            />
            <input value={selectedProduct ? `Unit Price: ${selectedProduct.unitPrice}` : "Unit Price: -"} readOnly />
            <input value={`Total Price: ${Number(customerForm.total_price || 0).toFixed(2)}`} readOnly />
            <button type="submit">{editIds.customer ? "Update Customer" : "Add Customer"}</button>
          </form>
          <input
            placeholder="Search customers..."
            value={search.customers}
            onChange={(e) => setSearch((s) => ({ ...s, customers: e.target.value }))}
          />
          <table>
            <thead>
              <tr><th>Name</th><th>Location</th><th>Telephone</th><th>Product</th><th>Qty</th><th>Total</th><th>Order Date</th><th>Actions</th></tr>
            </thead>
            <tbody>
              {filteredCustomers.map((c) => (
                <tr key={c._id}>
                  <td>{c.cust_fname} {c.cust_lname}</td>
                  <td>{c.location}</td>
                  <td>{c.telephone}</td>
                  <td>{c.ProductCode?.productName || "-"}</td>
                  <td>{c.quantity}</td>
                  <td>{c.total_price}</td>
                  <td>{c.order_number?.order_date ? formatDateSafe(c.order_number.order_date) : "-"}</td>
                  <td>
                    <button
                      onClick={() => {
                        setCustomerForm({
                          cust_fname: c.cust_fname,
                          cust_lname: c.cust_lname,
                          location: c.location,
                          telephone: c.telephone,
                          ProductCode: c.ProductCode?._id || "",
                          order_number: c.order_number?._id || "",
                          quantity: c.quantity || 1,
                          total_price: c.total_price || 0
                        });
                        setEditIds((s) => ({ ...s, customer: c._id }));
                      }}
                    >Edit</button>
                    <button onClick={async () => { await api.del(`/customers/${c._id}`); await loadData(); }}>Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      )}

      {activeTab === "Reports" && (
        <section className="card">
          <h3>Daily Report</h3>
          <div className="grid">
            <input type="date" value={reportDate} onChange={(e) => setReportDate(e.target.value)} />
            <button onClick={loadDailyReport}>Generate Report</button>
          </div>
          <table>
            <thead>
              <tr><th>Customer Name</th><th>Product Name</th><th>Quantity</th><th>Total Price</th><th>Order Date</th></tr>
            </thead>
            <tbody>
              {reportRows.map((r) => (
                <tr key={r._id}>
                  <td>{r.cust_fname} {r.cust_lname}</td>
                  <td>{r.ProductCode?.productName || "-"}</td>
                  <td>{r.quantity}</td>
                  <td>{r.total_price}</td>
                  <td>{r.order_number?.order_date ? formatDateSafe(r.order_number.order_date) : "-"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      )}
      </main>
    </div>
  );
}
