import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Calendar, DollarSign, Receipt, TrendingUp, RefreshCw } from 'lucide-react';

export default function MonthlyFinancials() {
  // Updated: Removed manual overrides, added recalculate button - v20260429_2038
  const BUILD_VERSION = '2.0.1'; // Force cache bust
  const [months, setMonths] = useState([]);
  const [recalculating, setRecalculating] = useState({});
  const [msg, setMsg] = useState('');

  const load = async () => {
    const r = await axios.get('/api/monthly-financials');
    setMonths(r.data.months || []);
  };
  useEffect(() => { load(); }, [BUILD_VERSION]);

  const recalculate = async (yearMonth) => {
    setRecalculating(prev => ({ ...prev, [yearMonth]: true }));
    try {
      await axios.post('/api/monthly-financials/recalculate', { year_month: yearMonth });
      setMsg(`Recalculated ${yearMonth} from invoices and expenses`);
      load();
      setTimeout(() => setMsg(''), 3000);
    } catch (err) {
      setMsg('Failed to recalculate');
      setTimeout(() => setMsg(''), 3000);
    } finally {
      setRecalculating(prev => ({ ...prev, [yearMonth]: false }));
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-6">
      <h1 className="text-xl font-bold mb-1">Monthly Financial Overview</h1>
      <p className="text-sm text-gray-500 mb-4">Financials are calculated from invoices and expenses. Revenue includes receivable invoices. Expenses include regular expenses, payable invoices, and staff loan deductions.</p>
      {console.log('MonthlyFinancials loaded - v2.0.1')}
      {msg && <div className="bg-green-50 text-green-700 text-sm p-2 rounded mb-4">{msg}</div>}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {months.map(m => (
          <div key={m.year_month} className="bg-white rounded-xl border border-gray-200 p-4 shadow-sm">
            <div className="flex justify-between items-center mb-3">
              <span className="font-semibold text-sm">{m.month_name}</span>
              <button
                onClick={() => recalculate(m.year_month)}
                disabled={recalculating[m.year_month]}
                className="text-xs text-primary-600 flex items-center gap-1 hover:text-primary-800 disabled:opacity-50"
              >
                <RefreshCw className={`w-3 h-3 ${recalculating[m.year_month] ? 'animate-spin' : ''}`}/>
                {recalculating[m.year_month] ? 'Recalculating...' : 'Recalculate'}
              </button>
            </div>
            <div className="space-y-2 text-sm">
              <div className="flex items-center gap-2"><DollarSign className="w-4 h-4 text-green-600"/><div><p className="text-xs text-gray-500">Revenue</p><p className="font-semibold">₦{m.revenue.toLocaleString()}</p></div></div>
              <div className="flex items-center gap-2"><Receipt className="w-4 h-4 text-red-500"/><div><p className="text-xs text-gray-500">Expenses</p><p className="font-semibold">₦{m.expenses.toLocaleString()}</p></div></div>
              <div className="flex items-center gap-2"><TrendingUp className={`w-4 h-4 ${m.net_profit >= 0 ? 'text-green-600' : 'text-red-600'}`}/><div><p className="text-xs text-gray-500">Net Profit</p><p className={`font-semibold ${m.net_profit >= 0 ? 'text-green-700' : 'text-red-700'}`}>₦{m.net_profit.toLocaleString()}</p></div></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
