import { mdiChartBar, mdiCashCheck, mdiHistory } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import FormField from '../components/FormField';
import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import axios from 'axios';

const ReportsPage = () => {
  const [activeTab, setActiveTab] = useState('current'); // 'current' or 'historical'
  
  // Historical state
  const [reportData, setReportData] = useState(null);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [filtersHistory, setFiltersHistory] = useState({
    startDate: '',
    endDate: '',
    employeeId: ''
  });

  // Current (Generator) state
  const [previewData, setPreviewData] = useState(null);
  const [loadingPreview, setLoadingPreview] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [filtersCurrent, setFiltersCurrent] = useState({
    startDate: '',
    endDate: ''
  });
  const [runSuccess, setRunSuccess] = useState('');
  const [runError, setRunError] = useState('');

  const fetchHistoricalReport = async () => {
    setLoadingHistory(true);
    try {
      const response = await axios.post('/reports', filtersHistory);
      setReportData(response.data);
    } catch (error) {
      console.error('Failed to fetch historical report:', error);
    } finally {
      setLoadingHistory(false);
    }
  };

  const fetchCurrentPreview = async () => {
    setLoadingPreview(true);
    setRunSuccess('');
    setRunError('');
    try {
      const response = await axios.post('/payroll_generator/preview', filtersCurrent);
      setPreviewData(response.data);
    } catch (error) {
      console.error('Failed to fetch current preview:', error);
      setRunError(error.response?.data || 'Failed to fetch unpaid logs.');
    } finally {
      setLoadingPreview(false);
    }
  };

  const generatePayroll = async () => {
    if (!confirm('Are you sure you want to run payroll? This will finalize these amounts and mark the associated logs as paid.')) return;
    
    setGenerating(true);
    setRunError('');
    setRunSuccess('');
    try {
      await axios.post('/payroll_generator/generate', {
        startDate: filtersCurrent.startDate,
        endDate: filtersCurrent.endDate,
        name: `Payroll ${filtersCurrent.startDate} to ${filtersCurrent.endDate}`
      });
      setRunSuccess('Payroll Run successfully generated!');
      setPreviewData(null); // Clear preview since they are now paid
    } catch (error) {
      console.error('Failed to generate payroll:', error);
      setRunError(error.response?.data || 'An error occurred while generating payroll.');
    } finally {
      setGenerating(false);
    }
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Payroll Reports')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartBar} title='Payroll Dashboard' main>
          {''}
        </SectionTitleLineWithButton>

        <div className="flex mb-6 space-x-4 border-b pb-2">
          <button
            onClick={() => setActiveTab('current')}
            className={`px-4 py-2 font-semibold rounded-t-lg transition-colors flex items-center ${
              activeTab === 'current' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
            Current Unpaid Logs
          </button>
          <button
            onClick={() => setActiveTab('historical')}
            className={`px-4 py-2 font-semibold rounded-t-lg transition-colors flex items-center ${
              activeTab === 'historical' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
             Historical Reports
          </button>
        </div>

        {activeTab === 'current' && (
          <div>
            <CardBox className="mb-6">
              <div className="mb-4 text-gray-600">
                Select a date range to view all <strong>unpaid</strong> Job Logs. From here, you can preview what your employees have currently earned and generate a finalized Payroll Run.
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField label="Start Date">
                  <input type="date" value={filtersCurrent.startDate} onChange={e => setFiltersCurrent({...filtersCurrent, startDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
                </FormField>
                <FormField label="End Date">
                  <input type="date" value={filtersCurrent.endDate} onChange={e => setFiltersCurrent({...filtersCurrent, endDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
                </FormField>
                <div className="flex items-end">
                  <BaseButton label="Preview Current Payroll" color="info" onClick={fetchCurrentPreview} disabled={loadingPreview} className="w-full" />
                </div>
              </div>
              {runError && <div className="mt-4 p-3 bg-red-100 text-red-700 rounded">{runError}</div>}
              {runSuccess && <div className="mt-4 p-3 bg-green-100 text-green-700 rounded">{runSuccess}</div>}
            </CardBox>

            {previewData && (
              <>
                <CardBox className="mb-6">
                  <h2 className="text-xl font-bold mb-4">Live Preview Summary</h2>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="p-4 bg-gray-100 rounded">
                      <p className="text-sm text-gray-500">Total Unpaid Gross Pay</p>
                      <p className="text-2xl font-semibold">${previewData.summary.totalGrossPay.toFixed(2)}</p>
                    </div>
                    <div className="p-4 bg-gray-100 rounded">
                      <p className="text-sm text-gray-500">Total Unpaid Hours</p>
                      <p className="text-2xl font-semibold">{previewData.summary.totalHours.toFixed(2)}</p>
                    </div>
                  </div>
                  <div className="mt-6">
                    <BaseButton label="Run & Finalize Payroll" color="success" onClick={generatePayroll} disabled={generating} />
                  </div>
                </CardBox>

                <CardBox>
                  <h2 className="text-xl font-bold mb-4">Employee Breakdown</h2>
                  <div className="overflow-x-auto">
                    <table className="w-full text-left">
                      <thead>
                        <tr>
                          <th className="p-2 border-b">Employee</th>
                          <th className="p-2 border-b">Total Hours</th>
                          <th className="p-2 border-b">Commission Base</th>
                          <th className="p-2 border-b">Calculated Gross Pay</th>
                        </tr>
                      </thead>
                      <tbody>
                        {previewData.lineItems.map((item: any, idx: number) => (
                          <tr key={idx}>
                            <td className="p-2 border-b">{item.employee?.firstName} {item.employee?.lastName || ''}</td>
                            <td className="p-2 border-b">{item.total_hours.toFixed(2)}</td>
                            <td className="p-2 border-b">${item.total_commission_base.toFixed(2)}</td>
                            <td className="p-2 border-b font-semibold text-green-600">${item.gross_pay.toFixed(2)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </CardBox>
              </>
            )}
          </div>
        )}

        {activeTab === 'historical' && (
          <div>
            <CardBox className="mb-6">
              <div className="mb-4 text-gray-600">
                View previously generated payroll line items by date range or employee ID.
              </div>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                <FormField label="Start Date">
                  <input type="date" value={filtersHistory.startDate} onChange={e => setFiltersHistory({...filtersHistory, startDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
                </FormField>
                <FormField label="End Date">
                  <input type="date" value={filtersHistory.endDate} onChange={e => setFiltersHistory({...filtersHistory, endDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
                </FormField>
                <FormField label="Employee ID">
                  <input type="text" value={filtersHistory.employeeId} onChange={e => setFiltersHistory({...filtersHistory, employeeId: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
                </FormField>
                <div className="flex items-end">
                  <BaseButton label="View Historical Report" color="info" onClick={fetchHistoricalReport} disabled={loadingHistory} className="w-full" />
                </div>
              </div>
            </CardBox>

            {reportData && (
              <>
                <CardBox className="mb-6">
                  <h2 className="text-xl font-bold mb-4">Historical Summary</h2>
                  <div className="grid grid-cols-3 gap-4">
                    <div className="p-4 bg-gray-100 rounded">
                      <p className="text-sm text-gray-500">Total Gross Pay</p>
                      <p className="text-2xl font-semibold">${reportData.summary.totalGrossPay.toFixed(2)}</p>
                    </div>
                    <div className="p-4 bg-gray-100 rounded">
                      <p className="text-sm text-gray-500">Total Hours</p>
                      <p className="text-2xl font-semibold">{reportData.summary.totalHours.toFixed(2)}</p>
                    </div>
                    <div className="p-4 bg-gray-100 rounded">
                      <p className="text-sm text-gray-500">Total Work Comp</p>
                      <p className="text-2xl font-semibold">${reportData.summary.totalWorkersComp.toFixed(2)}</p>
                    </div>
                  </div>
                </CardBox>
                <CardBox>
                  <h2 className="text-xl font-bold mb-4">Line Items</h2>
                  <div className="overflow-x-auto">
                    <table className="w-full text-left">
                      <thead>
                        <tr>
                          <th className="p-2 border-b">Employee</th>
                          <th className="p-2 border-b">Hours</th>
                          <th className="p-2 border-b">Gross Pay</th>
                          <th className="p-2 border-b">Work Comp Amount</th>
                          <th className="p-2 border-b">Created At</th>
                        </tr>
                      </thead>
                      <tbody>
                        {reportData.lineItems.map((item: any) => (
                          <tr key={item.id}>
                            <td className="p-2 border-b">{item.employee?.firstName} {item.employee?.lastName || ''}</td>
                            <td className="p-2 border-b">{item.total_hours}</td>
                            <td className="p-2 border-b">${item.gross_pay}</td>
                            <td className="p-2 border-b">${item.workers_comp_amount}</td>
                            <td className="p-2 border-b">{new Date(item.createdAt).toLocaleDateString()}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </CardBox>
              </>
            )}
          </div>
        )}

      </SectionMain>
    </>
  );
};

ReportsPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default ReportsPage;