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

export default function RoomAnalysis() {
  const { lang } = useContext(langContext);
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [reportData, setReportData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const formatCurrency = (value) => {
    const num = parseFloat(value || 0);
    return num.toLocaleString('en-US', { 
      minimumFractionDigits: 2, 
      maximumFractionDigits: 2 
    });
  };

  const fetchReportData = async () => {
    if (!dateRange.from || !dateRange.to) return;

    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/incomes/reportincomes`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            initial_date: dateRange.from,
            final_date: dateRange.to,
          }),
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      
      if (Array.isArray(data)) {
        setReportData(data);
      } else if (data.data && Array.isArray(data.data)) {
        setReportData(data.data);
      } else if (data.result && Array.isArray(data.result)) {
        setReportData(data.result);
      } else {
        setReportData([]);
      }
    } catch (err) {
      console.error('Error fetching report data:', err);
      setError(err.message);
      setReportData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    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 });
  }, []);

  useEffect(() => {
    if (dateRange.from && dateRange.to) {
      fetchReportData();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateRange]);

  const calculateSummary = () => {
    if (!reportData.length) return { revpar: 0, fixedCost: 0 };
    
    const totalIncome = reportData.reduce((sum, item) => {
      return sum + parseFloat(item.total_income || 0);
    }, 0);
    
    const totalUses = reportData.reduce((sum, item) => {
      return sum + parseInt(item.total_uses || 0, 10);
    }, 0);
    
    const revpar = totalUses > 0 ? totalIncome / totalUses : 0;
    const fixedCost = totalIncome;
    
    return { revpar, fixedCost };
  };

  const summary = calculateSummary();

  const columns = [
    { 
      header: 'ROOM', 
      key: 'room_type',
      render: (value) => value || '-'
    },
    { 
      header: 'ADR', 
      key: 'ADR',
      render: (value) => `$${formatCurrency(value || 0)}`
    },
    { 
      header: 'CPOR', 
      key: 'CPOR',
      render: (value) => `$${formatCurrency(value || 0)}`
    },
    { 
      header: 'CPAR', 
      key: 'CPAR',
      render: (value) => `$${formatCurrency(value || 0)}`
    },
    { 
      header: 'PPOR', 
      key: 'PPOR',
      render: (value) => `$${formatCurrency(value || 0)}`
    },
    { 
      header: 'BREAK EVEN POINT', 
      key: 'break_event_point',
      render: (value) => parseFloat(value || 0).toFixed(2)
    },
    { 
      header: 'GIFT ROOM', 
      key: 'gift_room',
      render: (value) => `$${formatCurrency(value || 0)}`
    },
  ];

  const exportColumns = [
    { header: lang === "es" ? "HABITACIÓN" : "ROOM", key: "room_type" },
    { header: lang === "es" ? "ADR" : "ADR", key: "ADR" },
    { header: lang === "es" ? "CPOR" : "CPOR", key: "CPOR" },
    { header: lang === "es" ? "CPAR" : "CPAR", key: "CPAR" },
    { header: lang === "es" ? "PPOR" : "PPOR", key: "PPOR" },
    { header: lang === "es" ? "PUNTO DE EQUILIBRIO" : "BREAK EVEN POINT", key: "break_event_point" },
    { header: lang === "es" ? "HABITACIÓN DE REGALO" : "GIFT ROOM", key: "gift_room" },
  ];

  const dataTransform = (data) => {
    return data.map((row) => ({
      ...row,
      ADR: row.ADR ? `$${formatCurrency(row.ADR)}` : '',
      CPOR: row.CPOR ? `$${formatCurrency(row.CPOR)}` : '',
      CPAR: row.CPAR ? `$${formatCurrency(row.CPAR)}` : '',
      PPOR: row.PPOR ? `$${formatCurrency(row.PPOR)}` : '',
      break_event_point: row.break_event_point ? parseFloat(row.break_event_point || 0).toFixed(2) : '',
      gift_room: row.gift_room ? `$${formatCurrency(row.gift_room)}` : '',
    }));
  };

  return (
    <div className="income-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === 'en' ? 'Room Analysis' : 'Análisis de Habitaciones'}
        </h2>
      </div>

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

      <div className="summary-section">
        <div className="summary-cards-wrapper">
          <SummaryCard
            title="RevPAR"
            amount={formatCurrency(summary.revpar)}
            isPrimary={true}
            isLoading={loading}
          />
          <SummaryCard
            title="Fixed Cost"
            amount={formatCurrency(summary.fixedCost)}
            isPrimary={true}
            isLoading={loading}
          />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '15px' }}>
        <ExcelExportButton
          data={reportData}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "analisis-habitaciones" : "room-analysis"}
          sheetName={lang === "es" ? "Análisis de Habitaciones" : "Room Analysis"}
          dataTransform={dataTransform}
        />
      </div>

      <div className="table-section">
        {loading ? (
          <div className="table-loading">
            <div className="loading-spinner-large"></div>
            <p>{lang === 'en' ? 'Loading room analysis data...' : 'Cargando datos de análisis de habitaciones...'}</p>
          </div>
        ) : error ? (
          <div className="error-container" style={{ 
            textAlign: 'center', 
            padding: '2rem',
            color: '#d32f2f',
            backgroundColor: '#ffebee',
            borderRadius: '8px',
            margin: '1rem 0'
          }}>
            <p>{lang === 'en' ? `Error loading data: ${error}` : `Error al cargar datos: ${error}`}</p>
          </div>
        ) : (
          <Table columns={columns} data={reportData} />
        )}
      </div>
    </div>
  );
}
