import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Navbar from './Navbar';

const Reports = () => {
  const [month, setMonth] = useState('');
  const [availableMonths, setAvailableMonths] = useState([]);
  const [report, setReport] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchAvailableMonths();
  }, []);

  const fetchAvailableMonths = async () => {
    try {
      console.log('Fetching available months...');
      const response = await axios.get('http://localhost:5000/api/reports/available-months', {
        withCredentials: true
      });
      console.log('Available months response:', response.data);
      
      if (response.data && response.data.length > 0) {
        setAvailableMonths(response.data);
        // Auto-select first month
        setMonth(response.data[0].month.toString());
      } else {
        // Add default months if none found
        const defaultMonths = [
            { month: '1', monthName: 'January' },
            { month: '2', monthName: 'February' },
            { month: '3', monthName: 'March' },
            { month: '4', monthName: 'April' },
            { month: '5', monthName: 'May' },
            { month: '6', monthName: 'June' },
            { month: '7', monthName: 'July' },
            { month: '8', monthName: 'August' },
            { month: '9', monthName: 'September' },
            { month: '10', monthName: 'October' },
            { month: '11', monthName: 'November' },
            { month: '12', monthName: 'December' }
        ];
        setAvailableMonths(defaultMonths);
      }
    } catch (error) {
      console.error('Error fetching months:', error);
      // Set default months on error
      const defaultMonths = [
          { month: '1', monthName: 'January' }, { month: '2', monthName: 'February' },
          { month: '3', monthName: 'March' }, { month: '4', monthName: 'April' },
          { month: '5', monthName: 'May' }, { month: '6', monthName: 'June' },
          { month: '7', monthName: 'July' }, { month: '8', monthName: 'August' },
          { month: '9', monthName: 'September' }, { month: '10', monthName: 'October' },
          { month: '11', monthName: 'November' }, { month: '12', monthName: 'December' }
      ];
      setAvailableMonths(defaultMonths);
      setError('Could not fetch months, using defaults');
    }
  };

  const generateReport = async () => {
    if (!month) {
      setError('Please select a month');
      return;
    }
    
    setLoading(true);
    setError('');
    setReport(null);
    
    try {
      console.log(`Generating report for month: ${month}`);
      const response = await axios.get(`http://localhost:5000/api/reports/monthly-payroll?month=${month}`, {
        withCredentials: true
      });
      
      console.log('Report response:', response.data);
      setReport(response.data);
      
      if (response.data.employeeCount === 0) {
        setError(`No employees found with salary records for ${getMonthName(month)}. Please add salary records to employees first.`);
      }
    } catch (error) {
      console.error('Error generating report:', error);
      console.error('Error details:', error.response);
      setError(error.response?.data?.message || 'Failed to generate report. Please check console for details.');
    } finally {
      setLoading(false);
    }
  };

  const getMonthName = (monthNum) => {
    const months = {
      '1': 'January', '2': 'February', '3': 'March', '4': 'April',
      '5': 'May', '6': 'June', '7': 'July', '8': 'August',
      '9': 'September', '10': 'October', '11': 'November', '12': 'December'
    };
    return months[monthNum] || monthNum;
  };

  const printReport = () => {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>Payroll Report - ${getMonthName(month)}</title>
          <style>
            body { font-family: Arial, sans-serif; padding: 20px; }
            table { width: 100%; border-collapse: collapse; margin-top: 20px; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            .header { text-align: center; margin-bottom: 30px; }
            .summary { margin: 20px 0; padding: 10px; background-color: #f9f9f9; }
            .total { font-weight: bold; background-color: #f0f0f0; }
          </style>
        </head>
        <body>
          ${document.getElementById('report-content').innerHTML}
        </body>
      </html>
    `);
    printWindow.print();
    printWindow.close();
  };

  return (
    <div>
      <Navbar />
      <div className="p-6 bg-gray-100 min-h-screen">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold text-gray-800 mb-6">Monthly Payroll Reports</h1>

          {/* Report Controls */}
          <div className="bg-white rounded-lg shadow-md p-6 mb-8">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium mb-2">Select Month</label>
                <select
                  value={month}
                  onChange={(e) => setMonth(e.target.value)}
                  className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">Select a month</option>
                  {availableMonths.map(m => (
                    <option key={m.month} value={m.month}>
                      {m.monthName}
                    </option>
                  ))}
                </select>
              </div>
              
              <div>
                <button
                  onClick={generateReport}
                  disabled={loading || !month}
                  className="w-full bg-blue-600 text-white px-6 py-2 rounded-md hover:bg-blue-700 disabled:bg-gray-400"
                >
                  {loading ? 'Generating...' : 'Generate Report'}
                </button>
              </div>
              
              {report && report.employeeCount > 0 && (
                <div>
                  <button
                    onClick={printReport}
                    className="w-full bg-green-600 text-white px-6 py-2 rounded-md hover:bg-green-700"
                  >
                     Print Report
                  </button>
                </div>
              )}
            </div>
            
            {error && (
              <div className="mt-4 p-3 bg-red-100 text-red-700 rounded-md">
                 {error}
              </div>
            )}
          </div>

          {/* Report Display */}
          {report && (
            <div className="bg-white rounded-lg shadow-md p-6" id="report-content">
              {/* Report Header */}
              <div className="text-center mb-6 pb-4 border-b">
                <h2 className="text-2xl font-bold">SmartPark EPMS</h2>
                <h3 className="text-xl mt-1">Monthly Payroll Report</h3>
                <p className="text-gray-600 mt-2">
                  {getMonthName(report.reportMonth)}
                </p>
                <p className="text-sm text-gray-500">
                  Generated: {new Date(report.generatedAt).toLocaleString()}
                </p>
              </div>

              {/* Summary Cards */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div className="bg-blue-50 p-4 rounded-lg text-center">
                  <p className="text-sm text-blue-600">Total Employees</p>
                  <p className="text-2xl font-bold text-blue-700">{report.employeeCount}</p>
                </div>
                <div className="bg-green-50 p-4 rounded-lg text-center">
                  <p className="text-sm text-green-600">Total Gross Salary</p>
                  <p className="text-2xl font-bold text-green-700">{report.summary.totalGrossSalary.toLocaleString()} RWF</p>
                </div>
                <div className="bg-red-50 p-4 rounded-lg text-center">
                  <p className="text-sm text-red-600">Total Deductions</p>
                  <p className="text-2xl font-bold text-red-700">{report.summary.totalDeduction.toLocaleString()} RWF</p>
                </div>
                <div className="bg-purple-50 p-4 rounded-lg text-center">
                  <p className="text-sm text-purple-600">Total Net Payroll</p>
                  <p className="text-2xl font-bold text-purple-700">{report.summary.totalNetSalary.toLocaleString()} RWF</p>
                </div>
              </div>

              {/* Employee Table */}
              {report.employeeCount > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="p-3 text-left">First Name</th>
                        <th className="p-3 text-left">Last Name</th>
                        <th className="p-3 text-left">Position</th>
                        <th className="p-3 text-left">Department</th>
                        <th className="p-3 text-right">Gross Salary</th>
                        <th className="p-3 text-right">Deduction</th>
                        <th className="p-3 text-right">Net Salary</th>
                      </tr>
                    </thead>
                    <tbody>
                      {report.employees.map((emp, idx) => (
                        <tr key={idx} className="border-t">
                          <td className="p-3">{emp.FirstName}</td>
                          <td className="p-3">{emp.LastName}</td>
                          <td className="p-3">{emp.Position}</td>
                          <td className="p-3">{emp.Department}</td>
                          <td className="p-3 text-right">{emp.GrossSalary.toLocaleString()} RWF</td>
                          <td className="p-3 text-right text-red-600">{emp.TotalDeduction.toLocaleString()} RWF</td>
                          <td className="p-3 text-right font-bold text-green-600">{emp.NetSalary.toLocaleString()} RWF</td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot className="bg-gray-100 font-bold">
                      <tr>
                        <td colSpan="4" className="p-3 text-right">TOTAL:</td>
                        <td className="p-3 text-right">{report.summary.totalGrossSalary.toLocaleString()} RWF</td>
                        <td className="p-3 text-right">{report.summary.totalDeduction.toLocaleString()} RWF</td>
                        <td className="p-3 text-right">{report.summary.totalNetSalary.toLocaleString()} RWF</td>
                       </tr>
                    </tfoot>
                  </table>
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <p className="text-lg">No salary records found for {getMonthName(report.reportMonth)}</p>
                  <p className="text-sm mt-2">Please add salary records to employees first</p>
                </div>
              )}

            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Reports;