import { useEffect, useMemo, useState } from "react";
import { getDepartments } from "../api/departmentApi";
import { getEmployees } from "../api/employeeApi";
import { createSalary, deleteSalary, getSalaries, updateSalary } from "../api/salaryApi";

function SalaryPage() {
  const [departments, setDepartments] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [salaries, setSalaries] = useState([]);
  const [message, setMessage] = useState("");
  const [editingId, setEditingId] = useState("");
  const [form, setForm] = useState({
    employeeId: "",
    departmentId: "",
    grossSalary: "",
    totalDeduction: "",
    month: "",
  });

  const netSalaryPreview = useMemo(
    () => Number(form.grossSalary || 0) - Number(form.totalDeduction || 0),
    [form.grossSalary, form.totalDeduction]
  );

  const salaryStats = useMemo(() => {
    const totalGross = salaries.reduce((acc, s) => acc + Number(s.grossSalary || 0), 0);
    const totalDeductions = salaries.reduce((acc, s) => acc + Number(s.totalDeduction || 0), 0);
    const totalNet = salaries.reduce((acc, s) => acc + Number(s.netSalary || 0), 0);
    return {
      totalGross,
      totalDeductions,
      totalNet,
      count: salaries.length,
      avg: salaries.length > 0 ? Math.round(totalNet / salaries.length) : 0
    };
  }, [salaries]);

  const formatNumber = (n) => {
    const num = Number(n);
    if (Number.isNaN(num)) return "—";
    return num.toLocaleString();
  };

  const loadData = async () => {
    const [deptRes, empRes, salRes] = await Promise.all([getDepartments(), getEmployees(), getSalaries()]);
    setDepartments(deptRes.data);
    setEmployees(empRes.data);
    setSalaries(salRes.data);
  };

  useEffect(() => {
    let isMounted = true;

    const run = async () => {
      try {
        const [deptRes, empRes, salRes] = await Promise.all([getDepartments(), getEmployees(), getSalaries()]);
        if (!isMounted) return;
        setDepartments(deptRes.data);
        setEmployees(empRes.data);
        setSalaries(salRes.data);
      } catch {
        if (isMounted) setMessage("Failed to load salary data");
      }
    };

    run();
    return () => {
      isMounted = false;
    };
  }, []);

  const onChange = (event) => {
    setForm((prev) => ({ ...prev, [event.target.name]: event.target.value }));
  };

  const resetForm = () => {
    setForm({ employeeId: "", departmentId: "", grossSalary: "", totalDeduction: "", month: "" });
    setEditingId("");
  };

  const onSubmit = async (event) => {
    event.preventDefault();
    setMessage("");
    const grossSalary = Number(form.grossSalary);
    const totalDeduction = Number(form.totalDeduction);
    const month = String(form.month || "").trim();
    if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) {
      setMessage("Month must use YYYY-MM format");
      return;
    }
    if (Number.isNaN(grossSalary) || grossSalary < 0 || Number.isNaN(totalDeduction) || totalDeduction < 0) {
      setMessage("Gross salary and deduction must be positive numbers");
      return;
    }
    if (totalDeduction > grossSalary) {
      setMessage("Total deduction cannot exceed gross salary");
      return;
    }
    const payload = {
      ...form,
      month,
      grossSalary,
      totalDeduction,
    };

    try {
      if (editingId) {
        await updateSalary(editingId, {
          grossSalary: payload.grossSalary,
          totalDeduction: payload.totalDeduction,
          month: payload.month,
        });
        setMessage("Salary updated");
      } else {
        await createSalary(payload);
        setMessage("Salary saved");
      }
      resetForm();
      await loadData();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to save salary");
    }
  };

  const onEdit = (item) => {
    setEditingId(item._id);
    setForm({
      employeeId: item.employee?._id || "",
      departmentId: item.department?._id || "",
      grossSalary: item.grossSalary,
      totalDeduction: item.totalDeduction,
      month: item.month,
    });
  };

  const onDelete = async (id) => {
    setMessage("");
    try {
      await deleteSalary(id);
      setMessage("Salary deleted");
      await loadData();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to delete salary");
    }
  };

  return (
    <div className="space-y-4">
      <div className="ui-card p-5">
        <div className="rounded-xl bg-gradient-to-r from-green-600 via-green-600 to-emerald-700 p-4">
          <div className="flex items-start justify-between">
            <div>
              <h1 className="text-2xl font-bold text-white">Salary Management</h1>
              <p className="mt-1 text-sm text-green-50">Manage employee salaries and deductions</p>
            </div>
            <div className="rounded-lg bg-white/20 px-4 py-2 backdrop-blur-sm">
              <div className="text-2xl font-bold text-white">{salaryStats.count}</div>
              <div className="text-xs text-green-100">Total Records</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <div className="ui-card p-4 bg-gradient-to-br from-blue-50 to-blue-100 ring-1 ring-blue-200">
          <div className="text-xs font-semibold text-blue-700">Total Gross Salary</div>
          <div className="mt-2 text-2xl font-bold text-blue-900">{formatNumber(salaryStats.totalGross)}</div>
        </div>
        <div className="ui-card p-4 bg-gradient-to-br from-red-50 to-red-100 ring-1 ring-red-200">
          <div className="text-xs font-semibold text-red-700">Total Deductions</div>
          <div className="mt-2 text-2xl font-bold text-red-900">{formatNumber(salaryStats.totalDeductions)}</div>
        </div>
        <div className="ui-card p-4 bg-gradient-to-br from-green-50 to-green-100 ring-1 ring-green-200">
          <div className="text-xs font-semibold text-green-700">Total Net Salary</div>
          <div className="mt-2 text-2xl font-bold text-green-900">{formatNumber(salaryStats.totalNet)}</div>
        </div>
        <div className="ui-card p-4 bg-gradient-to-br from-purple-50 to-purple-100 ring-1 ring-purple-200">
          <div className="text-xs font-semibold text-purple-700">Average Net Salary</div>
          <div className="mt-2 text-2xl font-bold text-purple-900">{formatNumber(salaryStats.avg)}</div>
        </div>
      </div>

      <section className="ui-card p-5">
        <h2 className="mb-4 text-lg font-semibold text-blue-900">{editingId ? '✏️ Edit Salary' : '➕ Add Salary Record'}</h2>
        <form onSubmit={onSubmit} className="grid gap-3 md:grid-cols-3">
          <select
            name="employeeId"
            className="ui-select"
            value={form.employeeId}
            onChange={onChange}
            required
            disabled={Boolean(editingId)}
          >
            <option value="">Select employee</option>
            {employees.map((item) => (
              <option key={item._id} value={item._id}>
                {item.firstName} {item.lastName}
              </option>
            ))}
          </select>

          <select
            name="departmentId"
            className="ui-select"
            value={form.departmentId}
            onChange={onChange}
            required
            disabled={Boolean(editingId)}
          >
            <option value="">Select department</option>
            {departments.map((item) => (
              <option key={item._id} value={item._id}>
                {item.departmentName}
              </option>
            ))}
          </select>

          <input
            type="month"
            name="month"
            className="ui-input"
            value={form.month}
            onChange={onChange}
            required
          />
          <input
            type="number"
            name="grossSalary"
            className="ui-input"
            placeholder="Gross Salary"
            value={form.grossSalary}
            onChange={onChange}
            min={0}
            required
          />
          <input
            type="number"
            name="totalDeduction"
            className="ui-input"
            placeholder="Total Deduction"
            value={form.totalDeduction}
            onChange={onChange}
            min={0}
            required
          />
          <input
            className="ui-input bg-gradient-to-r from-green-50 to-green-100 font-semibold text-green-900"
            value={`Net Salary: ${formatNumber(netSalaryPreview)}`}
            readOnly
          />

          <div className="md:col-span-3 flex gap-2">
            <button className="ui-btn ui-btn-primary flex-1">
              {editingId ? "Update Salary" : "Save Salary"}
            </button>
            {editingId && (
              <button
                type="button"
                onClick={resetForm}
                className="ui-btn ui-btn-secondary"
              >
                Cancel Edit
              </button>
            )}
          </div>
        </form>
        {message && (
          <div className={`mt-3 rounded-lg p-3 text-sm ${
            message.includes('deleted') || message.includes('saved') || message.includes('updated')
              ? 'bg-green-50 text-green-700 ring-1 ring-green-200'
              : 'bg-red-50 text-red-700 ring-1 ring-red-200'
          }`}>
            {message}
          </div>
        )}
      </section>

      <section className="ui-card p-5">
        <h2 className="mb-4 text-lg font-semibold text-blue-900">💰 All Salary Records</h2>
        <div className="ui-table-wrap">
          <table className="ui-table">
            <thead>
              <tr className="bg-slate-100">
                <th className="p-2 text-left">Employee</th>
                <th className="p-2 text-left">Department</th>
                <th className="p-2 text-left">Month</th>
                <th className="p-2 text-right">Gross</th>
                <th className="p-2 text-right">Deduction</th>
                <th className="p-2 text-right">Net</th>
                <th className="p-2 text-left">Actions</th>
              </tr>
            </thead>
            <tbody>
              {salaries.map((item) => (
                <tr key={item._id} className="border-b">
                  <td className="p-2">
                    {item.employee?.firstName} {item.employee?.lastName}
                  </td>
                  <td className="p-2">{item.department?.departmentName}</td>
                  <td className="p-2">{item.month}</td>
                  <td className="p-2 text-right font-medium text-blue-700">{formatNumber(item.grossSalary)}</td>
                  <td className="p-2 text-right font-medium text-red-700">{formatNumber(item.totalDeduction)}</td>
                  <td className="p-2 text-right font-bold text-green-700">{formatNumber(item.netSalary)}</td>
                  <td className="p-2">
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => onEdit(item)}
                        className="ui-btn ui-btn-amber"
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        onClick={() => onDelete(item._id)}
                        className="ui-btn ui-btn-danger"
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}

export default SalaryPage;
