import { useEffect, useState } from 'react'
import Loading from '../components/Loading'
import { useReportStore } from '../store/reportStore'

const TabButton = ({ active, onClick, children }) => (
  <button
    type="button"
    onClick={onClick}
    className={
      active
        ? 'rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white'
        : 'rounded-xl bg-slate-100 px-4 py-2 text-sm font-semibold text-slate-800 hover:bg-slate-200'
    }
  >
    {children}
  </button>
)

export default function Reports() {
  const { daily, weekly, monthly, loading, fetchDailyReport, fetchWeeklyReport, fetchMonthlyReport } = useReportStore()
  const [tab, setTab] = useState('daily')
  const [error, setError] = useState(null)

  useEffect(() => {
    const load = async () => {
      setError(null)
      try {
        if (tab === 'daily') await fetchDailyReport()
        if (tab === 'weekly') await fetchWeeklyReport()
        if (tab === 'monthly') await fetchMonthlyReport()
      } catch (e) {
        setError(e.message)
      }
    }
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tab])

  const data = tab === 'daily' ? daily : tab === 'weekly' ? weekly : monthly

  const employees = data?.employees || []
  const departments = data?.departments || []
  const salaries = data?.salaries || []

  return (
    <div>
      <div className="mb-5">
        <h1 className="text-2xl font-bold text-slate-900">Reports</h1>
        <p className="mt-1 text-sm text-slate-500">Daily, weekly and monthly reports generated from salary records.</p>
      </div>

      <div className="mb-4 flex flex-wrap gap-3">
        <TabButton active={tab === 'daily'} onClick={() => setTab('daily')}>Daily</TabButton>
        <TabButton active={tab === 'weekly'} onClick={() => setTab('weekly')}>Weekly</TabButton>
        <TabButton active={tab === 'monthly'} onClick={() => setTab('monthly')}>Monthly</TabButton>
      </div>

      {loading ? (
        <Loading label="Generating report" />
      ) : error ? (
        <div className="rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
      ) : (
        <div className="grid gap-4 lg:grid-cols-3">
          <div className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200 lg:col-span-1">
            <h2 className="text-lg font-semibold text-slate-900">Employees</h2>
            <div className="mt-3 overflow-x-auto">
              <table className="min-w-full text-left text-sm">
                <thead className="text-xs uppercase text-slate-500">
                  <tr>
                    <th className="py-2 pr-3">#</th>
                    <th className="py-2">Name</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {employees.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="py-3 text-sm text-slate-600">No data</td>
                    </tr>
                  ) : (
                    employees.map((e) => (
                      <tr key={e._id}>
                        <td className="py-2 pr-3 font-medium">{e.employeeNumber}</td>
                        <td className="py-2">{e.firstName} {e.lastName}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>

          <div className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200 lg:col-span-1">
            <h2 className="text-lg font-semibold text-slate-900">Departments</h2>
            <div className="mt-3 overflow-x-auto">
              <table className="min-w-full text-left text-sm">
                <thead className="text-xs uppercase text-slate-500">
                  <tr>
                    <th className="py-2 pr-3">Code</th>
                    <th className="py-2">Name</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {departments.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="py-3 text-sm text-slate-600">No data</td>
                    </tr>
                  ) : (
                    departments.map((d) => (
                      <tr key={d._id}>
                        <td className="py-2 pr-3 font-medium">{d.departmentCode}</td>
                        <td className="py-2">{d.departmentName}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>

          <div className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200 lg:col-span-1">
            <h2 className="text-lg font-semibold text-slate-900">Salaries</h2>
            <div className="mt-3 overflow-x-auto">
              <table className="min-w-full text-left text-sm">
                <thead className="text-xs uppercase text-slate-500">
                  <tr>
                    <th className="py-2 pr-3">Employee</th>
                    <th className="py-2 pr-3">Net</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {salaries.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="py-3 text-sm text-slate-600">No data</td>
                    </tr>
                  ) : (
                    salaries.map((s) => (
                      <tr key={s._id}>
                        <td className="py-2 pr-3 font-medium">{s.employee?.firstName} {s.employee?.lastName}</td>
                        <td className="py-2 pr-3 font-bold">{Number(s.netSalary).toFixed(2)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

