import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';

const Dashboard = () => {
  const [data, setData] = useState({ employees: [], departments: [], salaries: [] });
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Gukurura data zose icyarimwe (Performance optimization)
        const [empRes, deptRes, salRes] = await Promise.all([
          axios.get('http://localhost:5000/api/employee'),
          axios.get('http://localhost:5000/api/department'),
          axios.get('http://localhost:5000/api/salary')
        ]);
        setData({ employees: empRes.data, departments: deptRes.data, salaries: salRes.data });
      } catch (err) { console.error("Error fetching data:", err); }
    };
    fetchData();
  }, []);

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-3xl font-bold text-gray-800 mb-6">Employee management</h1>

      {/* 1. Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-blue-600 p-6 rounded-xl text-white shadow-lg">
          <h3 className="text-sm uppercase opacity-80">Total Employees</h3>
          <p className="text-4xl font-bold">{data.employees.length}</p>
        </div>
        <div className="bg-green-600 p-6 rounded-xl text-white shadow-lg">
          <h3 className="text-sm uppercase opacity-80">Departments</h3>
          <p className="text-4xl font-bold">{data.departments.length}</p>
        </div>
        <div className="bg-purple-600 p-6 rounded-xl text-white shadow-lg">
          <h3 className="text-sm uppercase opacity-80">Salary Records</h3>
          <p className="text-4xl font-bold">{data.salaries.length}</p>
        </div>
      </div>

      {/* 2. Salary Analysis Chart */}
      <div className="bg-white p-6 rounded-xl shadow-md h-72">
        <h2 className="text-xl font-bold mb-4">Salary Monthly Trend</h2>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart data={data.salaries}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="month" />
            <YAxis />
            <Tooltip />
            <Bar dataKey="NetSalary" fill="#4f46e5" radius={[5, 5, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* 3. Searchable Recent Salary Records */}
      <div className="bg-white p-6 rounded-xl shadow-md">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold">Latest Salary Records</h2>
          <input 
            type="text" 
            placeholder="Filter by Emp ID..." 
            className="border border-gray-300 p-2 rounded-lg w-64"
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <table className="w-full text-left">
          <thead className="bg-gray-50 border-b">
            <tr>
              <th className="p-4">Employee ID</th>
              <th className="p-4">Month</th>
              <th className="p-4">Net Salary (RWF)</th>
            </tr>
          </thead>
          <tbody>
            {data.salaries
              .filter(s => s.employeeNumber.toString().includes(searchTerm))
              .slice(0, 5).map((s, i) => (
              <tr key={i} className="border-b hover:bg-gray-50 transition">
                <td className="p-4 font-medium">{s.employeeNumber}</td>
                <td className="p-4">{s.month}</td>
                <td className="p-4 font-bold text-blue-700">{s.NetSalary}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Dashboard;