import React, { useEffect, useState, useContext } from 'react';
import Table from '../../components/Table/HotelTable';
import ConfirmationModal from '../../components/Modals/ConfirmationModal';
import '../../components/Filters/Filters.css';
import './InventoryReport.css';
import { langContext } from '../../context/LenguageContext';
import ExcelExportButton from '../../components/ExcelExportButton';


export default function InventoryReport() {
  const { lang } = useContext(langContext);
  const [data, setData] = useState([]);
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [productFilter, setProductFilter] = useState('');
  const [productSelectFilter, setProductSelectFilter] = useState('');
  const [movementFilter, setMovementFilter] = useState('');

  useEffect(() => {
    fetch(import.meta.env.VITE_API_BASE_URL + '/products/reportinventory')
      .then(res => res.json())
      .then(report => {
        if (report && report.new_product) {
          const products = report.new_product.map(item => ({
            dateOriginal: item.date_movement ? new Date(item.date_movement) : null,
            productId: item.id_product,
            product: item.name_product,
            movement: item.movement,
            quantity: item.quantity,
            beforeStock: Number(item.before_stock),
            stock: Number(item.stock),
            commentsDiscard: item.comments_discard,
            housekeeperName: item.housekeeper_name
          }));
          setData(products);
        } else {
          setData([]);
        }
      })
      .catch(() => setData([]));
  }, []);

  const uniqueProducts = [...new Set(data.map(item => item.product).filter(Boolean))].sort();
  const uniqueMovements = [...new Set(data.map(item => item.movement).filter(Boolean))].sort();

  const filteredData = data.filter((item) => {
    if (dateRange.from && dateRange.to) {
      if (!item.dateOriginal) return false;
      const movementDate = new Date(item.dateOriginal);
      const from = new Date(dateRange.from);
      const to = new Date(dateRange.to);
      to.setHours(23, 59, 59, 999);
      if (movementDate < from || movementDate > to) return false;
    }

    if (productFilter && !item.product?.toLowerCase().includes(productFilter.toLowerCase())) {
      return false;
    }

    if (productSelectFilter && item.product !== productSelectFilter) {
      return false;
    }

    if (movementFilter && item.movement !== movementFilter) {
      return false;
    }

    return true;
  });

  const totalMovements = filteredData.length;
  const stockSum = filteredData.reduce((acc, curr) => acc + (curr.stock || 0), 0);

  const clearFilters = () => {
    setDateRange({ from: '', to: '' });
    setProductFilter('');
    setProductSelectFilter('');
    setMovementFilter('');
  };

  const columns = [
    { header: lang === "es" ? 'ID Producto' : 'Product ID', key: 'productId' },
    { header: lang === "es" ? 'Producto' : 'Product', key: 'product' },
    { header: lang === "es" ? 'Movimiento' : 'Movement', key: 'movement' },
    {
      header: lang === "es" ? 'Comentarios' : 'Comments',
      key: 'commentsDiscard',
      render: (text, row) => {
        const movement = row.movement?.toLowerCase();
        if (movement === 'discard' && row.commentsDiscard) {
          return row.commentsDiscard;
        }
        return '—';
      }
    },
    {
      header: lang === "es" ? 'Ama de Llaves' : 'Housekeeper',
      key: 'housekeeperName',
      render: (text, row) => {
        const movement = row.movement?.toLowerCase();
        if (movement === 'consumption' && row.housekeeperName) {
          return row.housekeeperName;
        }
        return '—';
      }
    },
    { header: lang === "es" ? 'Cantidad' : 'Quantity', key: 'quantity' },
    {
      header: lang === "es" ? 'Stock Anterior' : 'Before Stock',
      key: 'beforeStock',
      render: (value) => value !== undefined && value !== null ? value : '—'
    },
    { header: lang === "es" ? 'Stock' : 'Stock', key: 'stock' },
    {
      header: lang === "es" ? 'Fecha' : 'Date',
      key: 'dateOriginal',
      render: (text, row) => {
        const date = row.dateOriginal;
        return date && !isNaN(date.getTime())
          ? date.toLocaleDateString(lang === "es" ? "es-MX" : "en-US")
          : '—';
      }
    },
  ];

  const exportColumns = [
    { header: lang === "es" ? 'ID Producto' : 'Product ID', key: 'productId' },
    { header: lang === "es" ? 'Producto' : 'Product', key: 'product' },
    { header: lang === "es" ? 'Movimiento' : 'Movement', key: 'movement' },
    { header: lang === "es" ? 'Comentarios' : 'Comments', key: 'commentsDiscard' },
    { header: lang === "es" ? 'Ama de Llaves' : 'Housekeeper', key: 'housekeeperName' },
    { header: lang === "es" ? 'Cantidad' : 'Quantity', key: 'quantity' },
    { header: lang === "es" ? 'Stock Anterior' : 'Before Stock', key: 'beforeStock' },
    { header: lang === "es" ? 'Stock' : 'Stock', key: 'stock' },
    { header: lang === "es" ? 'Fecha' : 'Date', key: 'dateOriginal' },
  ];

  const transformDataForExport = (data) => {
    return data.map(item => {
      const movement = item.movement?.toLowerCase();
      return {
        ...item,
        dateOriginal: item.dateOriginal && !isNaN(item.dateOriginal.getTime())
          ? item.dateOriginal.toLocaleDateString(lang === "es" ? "es-MX" : "en-US")
          : '—',
        comments_discard: movement === 'discard' && item.comments_discard ? item.comments_discard : '—',
        housekeeper_name: movement === 'consumption' && item.housekeeper_name ? item.housekeeper_name : '—'
      };
    });
  };

  return (
    <div className="report-page">
      <div className="page-header">
        <h2 className="page-title">{lang === "es" ? "Reporte de Inventario" : "Inventory Report"}</h2>
      </div>

      <div className="inventory-filters">
        <div className="date-input-group">
          <label className="date-label">
            {lang === "es" ? "Desde:" : "From:"}
          </label>
        <input
          type="date"
          value={dateRange.from}
          onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
            className="date-input"
        />
        </div>

        <div className="date-input-group">
          <label className="date-label">
            {lang === "es" ? "Hasta:" : "To:"}
          </label>
        <input
          type="date"
          value={dateRange.to}
          onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
            className="date-input"
        />
        </div>

        <input
          type="text"
          placeholder={lang === "es" ? "Search product..." : "Search product..."}
          value={productFilter}
          onChange={(e) => setProductFilter(e.target.value)}
          className="filter-search"
        />

        <select
          value={productSelectFilter}
          onChange={(e) => setProductSelectFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">{lang === "es" ? "Todos los productos" : "All Products"}</option>
          {uniqueProducts.map((product, index) => (
            <option key={index} value={product}>
              {product}
            </option>
          ))}
        </select>

        <select
          value={movementFilter}
          onChange={(e) => setMovementFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">{lang === "es" ? "Todos los movimientos" : "All Movements"}</option>
          {uniqueMovements.map((movement, index) => (
            <option key={index} value={movement}>
              {movement}
            </option>
          ))}
        </select>

        <button
          onClick={clearFilters}
          className="clear-filters-btn"
        >
          {lang === 'es' ? 'Limpiar filtros' : 'Clear filters'}
        </button>
      </div>

      <div className="summary-container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', gap: '80px' }}>
          <div className="summary-card">
            <strong>{lang === "es" ? "Total Movimientos" : "Total Movements"}</strong>
            <div>{totalMovements}</div>
          </div>
          <div className="summary-card">
            <strong>{lang === "es" ? "Stock Total" : "Total Stock"}</strong>
            <div>{stockSum}</div>
          </div>
        </div>
        <ExcelExportButton
          data={filteredData}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "reporte-inventario" : "inventory-report"}
          sheetName={lang === "es" ? "Reporte" : "Report"}
          dataTransform={transformDataForExport}
          className="export-button"
        />
      </div>

      <div className="table-section">
        <Table columns={columns} data={filteredData} />
      </div>
    </div>
  );
}


// import React, { useEffect, useState } from 'react';
// import Table from '../../components/Table/HotelTable';
// import ConfirmationModal from '../../components/Modals/ConfirmationModal';
// import '../../components/Filters/Filters.css';

// const fakeInventoryReport = [
//   {
//     id: 1,
//     date: '2025-09-10',
//     productId: 'P-001',
//     product: 'Coffee Beans',
//     movement: 'Stock In',
//     quantity: 100,
//     stock: 350
//   },
//   {
//     id: 2,
//     date: '2025-09-12',
//     productId: 'P-002',
//     product: 'Sugar',
//     movement: 'Stock Out',
//     quantity: 20,
//     stock: 80
//   },
//   {
//     id: 3,
//     date: '2025-09-13',
//     productId: 'P-003',
//     product: 'Milk',
//     movement: 'Stock In',
//     quantity: 50,
//     stock: 150
//   },
// ];

// export default function InventoryReport() {
//   const [data, setData] = useState([]);
//   const [dateRange, setDateRange] = useState({ from: '', to: '' });

//   useEffect(() => {
//     setData(fakeInventoryReport);
//     // En el futuro: aquí llamas a tu API real con fetch/axios
//   }, []);

//   const filteredData = data.filter((item) => {
//     if (!dateRange.from || !dateRange.to) return true;
//     const movementDate = new Date(item.date);
//     const from = new Date(dateRange.from);
//     const to = new Date(dateRange.to);
//     return movementDate >= from && movementDate <= to;
//   });

//   const totalMovements = filteredData.length;

//   const stockSum = filteredData.reduce((acc, curr) => acc + curr.stock, 0);

//   const columns = [
//     { header: 'DATE', key: 'date' },
//     { header: 'PRODUCT ID', key: 'productId' },
//     { header: 'PRODUCT', key: 'product' },
//     { header: 'MOVEMENT', key: 'movement' },
//     { header: 'QUANTITY', key: 'quantity' },
//     { header: 'STOCK', key: 'stock' },
//   ];

//   return (
//     <div className="report-page">
//       <h2>REPORT</h2>

//       {/* Filtros por fecha */}
//       <div className="page-filters">
//         <input
//           type="date"
//           value={dateRange.from}
//           onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
//         />
//         <input
//           type="date"
//           value={dateRange.to}
//           onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
//         />
//       </div>

//       {/* Summary */}
//       <div className="summary-container">
//         <div className="summary-card">
//           <strong>Total Movements</strong>
//           <div>{totalMovements}</div>
//         </div>
//         <div className="summary-card">
//           <strong>Total Stock</strong>
//           <div>{stockSum}</div>
//         </div>
//       </div>

//       <Table columns={columns} data={filteredData} />
//     </div>
//   );
// }
