import React, { useEffect, useState } from 'react';
import DateRangeFilter from '../../components/Filters/DateRangeFilter';
import SummaryCard from '../../components/SummaryCard';
import '../../components/Filters/Filters.css';
import './Approved.css';
import Table from '../../components/Table/HotelTable';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';
//**////** */ */
export default function Approved() {
  const { lang } = useContext(langContext);
  const [approvedExpenses, setApprovedExpenses] = useState([]);
  const [filteredExpenses, setFilteredExpenses] = useState([]);
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [totalApprovedFromAPI, setTotalApprovedFromAPI] = useState(0);
  const [mainSupplier, setMainSupplier] = useState('N/A');
  const [descriptionFilter, setDescriptionFilter] = useState('');
  const [areaFilter, setAreaFilter] = useState('');



  //Obtener lista de gastos aprobados
  useEffect(() => {
    axios.get(import.meta.env.VITE_API_BASE_URL + '/expenses/approvedexpenses')
      .then((res) => {
        const formatted = res.data.data.map((item, index) => ({
          id: index + 1,
          description: item.expense_description,
          requestDate: new Date(item.request_date).toISOString().split('T')[0],
          approvedDate: new Date(item.approval_date).toISOString().split('T')[0],
          area: item.area,
          requestedBy: item.requested_by,
          amount: parseFloat(item.amount),
        }));

        setApprovedExpenses(formatted);
        setFilteredExpenses(formatted);
      })
      .catch((err) => {
        if (err.response) {
          console.error(`❌ Error ${err.response.status}: ${err.response.data.message}`);
        } else {
          console.error('❌ Error fetching approved expenses:', err.message);
        }
      });
  }, []);

  //Obtener total aprobado (GET con opción 1)
  useEffect(() => {
    axios.post(import.meta.env.VITE_API_BASE_URL + '/expenses/totalapproved', { option: 1 })
      .then((response) => {
        // Aquí asumo que response.data tiene la forma { message, data }
        // El valor está en response.data.data y es string, convertir a número:
        const total = parseFloat(response.data.data);
        setTotalApprovedFromAPI(isNaN(total) ? 0 : total);
      })
      .catch((error) => {
        console.error('Error fetching total approved:', error);
      });
  }, []);




  // Obtener proveedor principal
  useEffect(() => {
    axios.get(import.meta.env.VITE_API_BASE_URL + '/expenses/mainsupplier')
      .then((res) => {
        const supplier = res.data?.data?.[0]?.supplier || 'N/A';
        setMainSupplier(supplier);
      })
      .catch((err) => {
        if (err.response) {
          console.error(`❌ Error ${err.response.status}: ${err.response.data.message}`);
        } else {
          console.error('❌ Error fetching main supplier:', err.message);
        }
      });
  }, []);

  useEffect(() => {
    let filtered = [...approvedExpenses];

    if (dateRange.from && dateRange.to) {
      const from = new Date(dateRange.from);
      const to = new Date(dateRange.to);
      filtered = filtered.filter((item) => {
        const itemDate = new Date(item.approvedDate);
        return itemDate >= from && itemDate <= to;
      });
    }

    if (descriptionFilter) {
      filtered = filtered.filter((item) =>
        item.description?.toLowerCase().includes(descriptionFilter.toLowerCase())
      );
    }

    if (areaFilter) {
      filtered = filtered.filter((item) => item.area === areaFilter);
    }

    setFilteredExpenses(filtered);
  }, [dateRange, approvedExpenses, descriptionFilter, areaFilter]);

  // Columnas para la tabla
  const columns = [
    {
      header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO",
      key: 'description',
      render: (text, row) => (
        <Link
          to={`/app/expenses/${row.id}`}
          style={{ color: 'blue', textDecoration: 'underline' }}
        >
          {text}
        </Link>
      ),
    }
    ,
    { header: lang === "en" ? "REQUEST DATE" : "FECHA DE SOLICITUD", key: 'requestDate' },
    { header: lang === "en" ? "APPROVED DATE" : "FECHA DE APROBACIÓN", key: 'approvedDate' },
    { header: lang === "en" ? "AREA" : "ÁREA", key: 'area' },
    { header: lang === "en" ? "REQUESTED BY" : "SOLICITADO POR", key: 'requestedBy' },
    {
      header: lang === "en" ? "AMOUNT" : "IMPORTE",
      key: 'amount',
      render: (amount) => `$${amount.toLocaleString()}`
    },
    {
      header: lang === "en" ? "STATUS" : "ESTADO",
      key: 'id',
      headerStyle: { textAlign: 'center' },
      render: () => (
        <div style={{ textAlign: 'center' }}>
          <button className="status-button approve" style={{ pointerEvents: 'none' }}>
            {lang === "en" ? "APPROVED" : "APROBADO"}
          </button>
        </div>
      )
    }
  ];

  const uniqueAreas = [...new Set(approvedExpenses.map(item => item.area).filter(Boolean))].sort();

  const clearFilters = () => {
    setDateRange({ from: '', to: '' });
    setDescriptionFilter('');
    setAreaFilter('');
  };

  return (
    <div className="approved-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Approved Expenses" : "Gastos Aprobados"}
        </h2>
      </div>

      <div className="filters-section">
        <input
          type="text"
          placeholder={lang === "en" ? "Search by description..." : "Buscar por descripción..."}
          value={descriptionFilter}
          onChange={(e) => setDescriptionFilter(e.target.value)}
          className="filter-search"
        />

        <select 
          value={areaFilter} 
          onChange={(e) => setAreaFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">{lang === "en" ? "All Areas" : "Todas las Áreas"}</option>
          {uniqueAreas.map((area, index) => (
            <option key={index} value={area}>
              {area}
            </option>
          ))}
        </select>

        <DateRangeFilter 
          dateRange={dateRange}
          onDateChange={setDateRange}
          lang={lang}
        />

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

      <div className="summary-cards-wrapper">
        <SummaryCard
          title={lang === "en" ? "Total Approved" : "Total Aprobado"}
          amount={totalApprovedFromAPI}
        />
        <div className="info-card">
          <h3 className="card-title">{lang === "en" ? "Main Supplier" : "Proveedor Principal"}</h3>
          <div className="card-value">{mainSupplier}</div>
        </div>
      </div>

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



