import React, { useEffect, useState } from 'react';
import Table from '../../components/Table/HotelTable';
import DateRangeFilter from '../../components/Filters/DateRangeFilter';
import SummaryCard from '../../components/SummaryCard';
import ExcelExportButton from '../../components/ExcelExportButton';
import '../../components/Filters/Filters.css';
import './Income.css';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';


// Ya no se usan datos estáticos para canales


export default function Income() {
  const {lang} = useContext(langContext);
  // Card: Total income (dinámico)
  const [totalIncome, setTotalIncome] = useState(0);
  // Cards: canales (Booking, Expedia, Mr and Mrs Smith)
  const [channels, setChannels] = useState({ booking: 0, expedia: 0, mrsmith: 0 });
  // Tabla usa datos del endpoint
  const [filteredRooms, setFilteredRooms] = useState([]);
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [loadingChannels, setLoadingChannels] = useState(false);
  const [loadingTotalIncome, setLoadingTotalIncome] = useState(false);
  const [loadingTable, setLoadingTable] = useState(false);
  // Consumir el endpoint para las tarjetas de canales
  useEffect(() => {
    async function fetchChannels() {
      if (dateRange.from && dateRange.to) {
        setLoadingChannels(true);
        // Formatear fechas a dd-mm-yyyy
        const formatDate = (dateStr) => {
          const [year, month, day] = dateStr.split('-');
          return `${year}-${month}-${day}`;
        };
        const checkin_initial = formatDate(dateRange.from);
        const checkin_final = formatDate(dateRange.to);
        try {
          const response = await fetch(import.meta.env.VITE_API_BASE_URL + '/incomes/channelscards', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ checkin_initial, checkin_final })
          });
          const data = await response.json();
          console.log(data.data);
          setChannels({
            booking: data.data[3].total_channel || 0,
            expedia: data.data[1].total_channel || 0,
            mrsmith: data.data[4].total_channel || 0,
          });
        } catch {
          setChannels({ booking: 0, expedia: 0, mrsmith: 0 });
        } finally {
          setLoadingChannels(false);
        }
      } else {
        setChannels({ booking: 0, expedia: 0, mrsmith: 0 });
        setLoadingChannels(false);
      }
    }
    fetchChannels();
  }, [dateRange]);
  // Consumir el endpoint para la tarjeta Total income
  useEffect(() => {
    async function fetchTotalIncome() {
      if (dateRange.from && dateRange.to) {
        setLoadingTotalIncome(true);
        // Formatear fechas a dd-mm-yyyy
        const formatDate = (dateStr) => {
          const [year, month, day] = dateStr.split('-');
          return `${year}-${month}-${day}`;
        };
        const checkin_initial = formatDate(dateRange.from);
        const checkin_final = formatDate(dateRange.to);
        try {
          const response = await fetch(import.meta.env.VITE_API_BASE_URL + '/incomes/totalincomes', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ checkin_initial, checkin_final })
          });
          const data = await response.json();
          setTotalIncome(data.data || 0);
        } catch {
          setTotalIncome(0);
        } finally {
          setLoadingTotalIncome(false);
        }
      } else {
        setTotalIncome(0);
        setLoadingTotalIncome(false);
      }
    }
    fetchTotalIncome();
  }, [dateRange]);

  // Al cargar la página, seleccionar el rango de fechas de un mes
  useEffect(() => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    // Primer día del mes
    const firstDay = new Date(year, month, 1);
    // Último día del mes
    const lastDay = new Date(year, month + 1, 0);
    // Formato yyyy-mm-dd
    const pad = (n) => n.toString().padStart(2, '0');
    const from = `${year}-${pad(month + 1)}-${pad(firstDay.getDate())}`;
    const to = `${year}-${pad(month + 1)}-${pad(lastDay.getDate())}`;
    setDateRange({ from, to });
  }, []);

  // Consumir el endpoint solo para la tabla
  useEffect(() => {
    async function fetchIncome() {
      if (dateRange.from && dateRange.to) {
        setLoadingTable(true);
        // Formatear fechas a dd-mm-yyyy
        const formatDate = (dateStr) => {
          const [year, month, day] = dateStr.split('-');
          return `${year}-${month}-${day}`;
        };
        try {
          const checkin_initial = formatDate(dateRange.from);
          const checkin_final = formatDate(dateRange.to);
          // GET pero solo para la tabla
          const url = import.meta.env.VITE_API_BASE_URL + `/incomes/getincomes`;
          const response = await fetch(url,  {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ checkin_initial, checkin_final })
          });
          const data = await response.json();
          setFilteredRooms( data.data || []);
        } catch {
          setFilteredRooms([]);
        } finally {
          setLoadingTable(false);
        }
      } else {
        setFilteredRooms([]);
        setLoadingTable(false);
      }
    }
    fetchIncome();
  }, [dateRange]);

  const columns = [
    { header: 'ROOM', key: 'room' },
    { header: 'OCCUPATION', key: 'occupation' },
    {
      header: 'AVG. INCOME PER NIGHT',
      key: 'income_per_night',
      render: (value) => value ? `$${parseFloat(value).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : ''
    },
    {
      header: 'TOTAL INCOME',
      key: 'total_income',
      render: (value) => value ? `$${parseFloat(value).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : ''
    },
  ];

  const exportColumns = [
    { header: lang === "es" ? "HABITACIÓN" : "ROOM", key: "room" },
    { header: lang === "es" ? "OCUPACIÓN" : "OCCUPATION", key: "occupation" },
    { header: lang === "es" ? "INGRESO PROMEDIO POR NOCHE" : "AVG. INCOME PER NIGHT", key: "income_per_night" },
    { header: lang === "es" ? "INGRESO TOTAL" : "TOTAL INCOME", key: "total_income" },
  ];

  const dataTransform = (data) => {
    return data.map((row) => ({
      ...row,
      income_per_night: row.income_per_night ? `$${parseFloat(row.income_per_night).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '',
      total_income: row.total_income ? `$${parseFloat(row.total_income).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '',
    }));
  };

  // Cards usan datos dinámicos de canales y totalIncome
  const bookingPercentage = totalIncome
    ? Math.round((channels.booking / totalIncome) * 100)
    : 0;
  const expediaPercentage = totalIncome
    ? Math.round((channels.expedia / totalIncome) * 100)
    : 0;
  const mrsmithPercentage = totalIncome
    ? Math.round((channels.mrsmith / totalIncome) * 100)
    : 0;

  return (
    <div className="income-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Little Hotelier" : "Little Hotelier"}
        </h2>
      </div>

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

      <div className="summary-section">
        <div className="summary-cards-wrapper">
          <SummaryCard
            title={lang === "en" ? "Total Income" : "Total de Ingresos"}
            amount={parseFloat(totalIncome || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            isPrimary={true}
            isLoading={loadingTotalIncome}
          />
          <SummaryCard
            title="Booking"
            amount={parseFloat(channels.booking || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            percentage={bookingPercentage}
            isLoading={loadingChannels}
          />
          <SummaryCard
            title="Expedia"
            amount={parseFloat(channels.expedia || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            percentage={expediaPercentage}
            isLoading={loadingChannels}
          />
          <SummaryCard
            title="Mr and Mrs Smith"
            amount={parseFloat(channels.mrsmith || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            percentage={mrsmithPercentage}
            isLoading={loadingChannels}
          />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '15px' }}>
        <ExcelExportButton
          data={filteredRooms}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "informe-ingresos" : "income-report"}
          sheetName={lang === "es" ? "Datos de Ingresos" : "Income Data"}
          dataTransform={dataTransform}
        />
      </div>

      <div className="table-section">
        {loadingTable ? (
          <div className="table-loading">
            <div className="loading-spinner-large"></div>
            <p>{lang === "en" ? "Loading data..." : "Cargando datos..."}</p>
          </div>
        ) : (
          <Table columns={columns} data={filteredRooms} />
        )}
      </div>
    </div>
  );
}

// const fakeIncome = {
//   totalIncome: 15950,
//   booking: 7975,
//   expedia: 4785,
//   rooms: [
//     {
//       name: 'San Miguel Presidential',
//       occupation: '10 nights',
//       avgIncomePerNight: '$300',
//       totalIncome: '$3,000',
//     },
//     {
//       name: 'Angels View',
//       occupation: '15 nights',
//       avgIncomePerNight: '$300',
//       totalIncome: '$4,500',
//     },
//     {
//       name: 'Angels Dome',
//       occupation: '17 nights',
//       avgIncomePerNight: '$250',
//       totalIncome: '$4,250',
//     },
//     {
//       name: 'Celestial',
//       occupation: '21 nights',
//       avgIncomePerNight: '$200',
//       totalIncome: '$4,200',
//     },
//   ],
// };

// export default function Income() {
//   const [income, setIncome] = useState({});
//   const [filteredRooms, setFilteredRooms] = useState([]);
//   const [dateRange, setDateRange] = useState({ from: '', to: '' });

//   useEffect(() => {
//     // Simular carga de datos
//     setIncome(fakeIncome);
//     setFilteredRooms(fakeIncome.rooms);
//   }, []);

//   // Si en el futuro deseas aplicar filtros por fecha real:
//   useEffect(() => {
//     if (dateRange.from && dateRange.to) {
//       // Lógica de filtrado por fecha (si tuvieras fechas en los datos de cada habitación)
//       // Aquí se deja como estático porque los datos no tienen campo de fecha
//       setFilteredRooms(fakeIncome.rooms); // Simulando que no cambia
//     }
//   }, [dateRange]);

//   const columns = [
//     { header: 'ROOM', key: 'name' },
//     { header: 'OCCUPATION', key: 'occupation' },
//     { header: 'AVG. INCOME PER NIGHT', key: 'avgIncomePerNight' },
//     { header: 'TOTAL INCOME', key: 'totalIncome' },
//   ];

//   const bookingPercentage = income.totalIncome
//     ? Math.round((income.booking / income.totalIncome) * 100)
//     : 0;
//   const expediaPercentage = income.totalIncome
//     ? Math.round((income.expedia / income.totalIncome) * 100)
//     : 0;

//   return (
//     <div>
//       <h2>INCOME</h2>

//       {/* Date Filters */}
//       <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 Cards */}
//       <div style={{ display: 'flex', gap: '240px', marginBottom: '20px' }}>
//         <div className="summary-card">
//           <strong>Total income</strong>
//           <div>${income.totalIncome?.toLocaleString() || 0}</div>
//         </div>
//         <div className="summary-card">
//           <strong>Booking</strong>
//           <div>${income.booking?.toLocaleString() || 0}</div>
//           <div>{bookingPercentage}%</div>
//         </div>
//         <div className="summary-card">
//           <strong>Expedia</strong>
//           <div>${income.expedia?.toLocaleString() || 0}</div>
//           <div>{expediaPercentage}%</div>
//         </div>
//       </div>

//       {/* Income Table */}
//       <Table columns={columns} data={filteredRooms} />
//     </div>
//   );
// }


//style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px', marginBottom: '15px' }}