import { useEffect, useMemo, useState } from "react";
import {
  createDepartment,
  deleteDepartment,
  getDepartments,
  seedDepartments,
  updateDepartment,
} from "../api/departmentApi";

function DepartmentPage() {
  const [departments, setDepartments] = useState([]);
  const [form, setForm] = useState({
    departmentCode: "",
    departmentName: "",
    grossSalary: "",
    totalDeduction: "",
  });
  const [message, setMessage] = useState("");
  const [editingId, setEditingId] = useState("");

  const isEditMode = Boolean(editingId);

  const loadDepartments = async () => {
    const response = await getDepartments();
    setDepartments(response.data);
  };

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

    const run = async () => {
      try {
        await loadDepartments();
      } catch {
        if (isMounted) setMessage("Failed to load departments");
      }
    };

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

  const departmentStats = useMemo(() => {
    const totalGross = departments.reduce((acc, item) => acc + Number(item.grossSalary || 0), 0);
    const totalDeductions = departments.reduce((acc, item) => acc + Number(item.totalDeduction || 0), 0);
    const totalNet = totalGross - totalDeductions;

    return {
      totalGross,
      totalDeductions,
      totalNet,
      avg: departments.length > 0 ? Math.round(totalNet / departments.length) : 0,
    };
  }, [departments]);

  const netPreview = useMemo(() => {
    const gross = Number(form.grossSalary || 0);
    const deduction = Number(form.totalDeduction || 0);
    if (Number.isNaN(gross) || Number.isNaN(deduction)) return 0;
    return gross - deduction;
  }, [form.grossSalary, form.totalDeduction]);

  const formatNumber = (value) => {
    const number = Number(value);
    if (Number.isNaN(number)) return "-";
    return number.toLocaleString();
  };

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

  const resetForm = () => {
    setForm({
      departmentCode: "",
      departmentName: "",
      grossSalary: "",
      totalDeduction: "",
    });
    setEditingId("");
  };

  const onSubmit = async (event) => {
    event.preventDefault();
    setMessage("");

    const code = form.departmentCode.trim().toUpperCase();
    const name = form.departmentName.trim();
    const gross = Number(form.grossSalary);
    const deduction = Number(form.totalDeduction);

    if (!/^[A-Z0-9]{2,10}$/.test(code)) {
      setMessage("Department code must be 2-10 uppercase letters or numbers");
      return;
    }
    if (name.length < 2) {
      setMessage("Department name must be at least 2 characters");
      return;
    }
    if (Number.isNaN(gross) || gross < 0 || Number.isNaN(deduction) || deduction < 0) {
      setMessage("Gross salary and deduction must be positive numbers");
      return;
    }
    if (deduction > gross) {
      setMessage("Total deduction cannot exceed gross salary");
      return;
    }

    try {
      const payload = {
        departmentCode: code,
        departmentName: name,
        grossSalary: gross,
        totalDeduction: deduction,
      };

      if (isEditMode) {
        await updateDepartment(editingId, payload);
        setMessage("Department updated");
      } else {
        await createDepartment(payload);
        setMessage("Department saved");
      }

      resetForm();
      await loadDepartments();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to save department");
    }
  };

  const onSeed = async () => {
    setMessage("");
    try {
      await seedDepartments();
      setMessage("Starter departments loaded");
      await loadDepartments();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to seed departments");
    }
  };

  const onEdit = (item) => {
    setEditingId(item._id);
    setForm({
      departmentCode: item.departmentCode || "",
      departmentName: item.departmentName || "",
      grossSalary: item.grossSalary ?? "",
      totalDeduction: item.totalDeduction ?? "",
    });
  };

  const onDelete = async (id) => {
    setMessage("");
    const ok = window.confirm("Delete this department? This action cannot be undone.");
    if (!ok) return;

    try {
      await deleteDepartment(id);
      setMessage("Department deleted");
      if (editingId === id) resetForm();
      await loadDepartments();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to delete department");
    }
  };

  return (
    <div className="space-y-4">
      <div className="ui-card p-5">
        <div className="rounded-xl bg-gradient-to-r from-purple-600 via-purple-600 to-pink-700 p-4">
          <div className="flex items-start justify-between">
            <div>
              <h1 className="text-2xl font-bold text-white">Department Management</h1>
              <p className="mt-1 text-sm text-purple-50">Organize and manage departments</p>
            </div>
            <div className="rounded-lg bg-white/20 px-4 py-2 backdrop-blur-sm">
              <div className="text-2xl font-bold text-white">{departments.length}</div>
              <div className="text-xs text-purple-100">Total Departments</div>
            </div>
          </div>
        </div>
      </div>

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

      <div className="grid gap-4 md:grid-cols-2">
        <section className="ui-card p-5">
          <div className="mb-4 flex items-center justify-between gap-3">
            <h2 className="text-lg font-semibold text-blue-900">
              {isEditMode ? "Edit Department" : "Add New Department"}
            </h2>
            <button type="button" onClick={onSeed} className="ui-btn ui-btn-muted text-xs">
              Seed Defaults
            </button>
          </div>

          <form onSubmit={onSubmit} className="space-y-3">
            <input
              name="departmentCode"
              className="ui-input"
              placeholder="Department Code"
              value={form.departmentCode}
              onChange={onChange}
              pattern="[A-Za-z0-9]{2,10}"
              title="Use 2-10 letters or numbers"
              required
              disabled={isEditMode}
            />

            <input
              name="departmentName"
              className="ui-input"
              placeholder="Department Name"
              value={form.departmentName}
              onChange={onChange}
              minLength={2}
              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 Preview: ${formatNumber(netPreview)}`}
              readOnly
            />

            <div className="flex gap-2">
              <button className="ui-btn ui-btn-primary flex-1" type="submit">
                {isEditMode ? "Update Department" : "Save Department"}
              </button>
              {isEditMode && (
                <button type="button" onClick={resetForm} className="ui-btn ui-btn-muted">
                  Cancel
                </button>
              )}
            </div>
          </form>

          {message && (
            <div
              className={`mt-3 rounded-lg p-3 text-sm ${
                message.includes("deleted") ||
                message.includes("saved") ||
                message.includes("updated") ||
                message.includes("loaded")
                  ? "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 Departments</h2>

          <div className="ui-table-wrap">
            <table className="ui-table">
              <thead>
                <tr>
                  <th>Code</th>
                  <th>Name</th>
                  <th style={{ textAlign: "right" }}>Gross</th>
                  <th style={{ textAlign: "right" }}>Deduction</th>
                  <th style={{ textAlign: "left" }}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {departments.map((item) => (
                  <tr key={item._id}>
                    <td>
                      <span className="font-semibold text-blue-700">{item.departmentCode}</span>
                    </td>
                    <td>{item.departmentName}</td>
                    <td style={{ textAlign: "right" }} className="font-medium text-blue-700">
                      {formatNumber(item.grossSalary)}
                    </td>
                    <td style={{ textAlign: "right" }} className="font-medium text-red-700">
                      {formatNumber(item.totalDeduction)}
                    </td>
                    <td>
                      <div className="flex gap-2">
                        <button type="button" className="ui-btn ui-btn-amber" onClick={() => onEdit(item)}>
                          Edit
                        </button>
                        <button type="button" className="ui-btn ui-btn-danger" onClick={() => onDelete(item._id)}>
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </div>
  );
}

export default DepartmentPage;
