"use client";

import { useState, useEffect, useCallback } from "react";

interface Category {
  id: string;
  name: string;
  nameAr: string | null;
  color: string;
  icon: string | null;
  sortOrder: number;
  expenseCount: number;
}

const t = {
  en: {
    title: "Manage Categories",
    addCategory: "Add Category",
    name: "Name",
    nameAr: "Name (Arabic)",
    color: "Color",
    save: "Save",
    cancel: "Cancel",
    edit: "Edit",
    delete: "Delete",
    confirmDelete: "Delete this category?",
    cannotDelete: "Cannot delete: category has linked expenses.",
    expenses: "expenses",
    noCategories: "No categories yet.",
  },
  ar: {
    title: "إدارة الفئات",
    addCategory: "إضافة فئة",
    name: "الاسم",
    nameAr: "الاسم (عربي)",
    color: "اللون",
    save: "حفظ",
    cancel: "إلغاء",
    edit: "تعديل",
    delete: "حذف",
    confirmDelete: "حذف هذه الفئة؟",
    cannotDelete: "لا يمكن الحذف: الفئة مرتبطة بمصروفات.",
    expenses: "مصروفات",
    noCategories: "لا توجد فئات بعد.",
  },
};

interface CategoryManagerProps {
  lang: string;
}

export default function CategoryManager({ lang }: CategoryManagerProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formName, setFormName] = useState("");
  const [formNameAr, setFormNameAr] = useState("");
  const [formColor, setFormColor] = useState("#6366f1");
  const [error, setError] = useState("");

  const fetchCategories = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/dashboard/expenses/categories");
      const data = await res.json();
      if (data.success) setCategories(data.categories);
    } catch {
      /* ignore */
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    fetchCategories();
  }, [fetchCategories]);

  const resetForm = () => {
    setShowForm(false);
    setEditingId(null);
    setFormName("");
    setFormNameAr("");
    setFormColor("#6366f1");
    setError("");
  };

  const startEdit = (cat: Category) => {
    setEditingId(cat.id);
    setFormName(cat.name);
    setFormNameAr(cat.nameAr ?? "");
    setFormColor(cat.color);
    setShowForm(true);
  };

  const handleSave = async () => {
    setError("");
    const body = {
      name: formName,
      nameAr: formNameAr || undefined,
      color: formColor,
    };

    if (editingId) {
      await fetch(`/api/dashboard/expenses/categories/${editingId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } else {
      await fetch("/api/dashboard/expenses/categories", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    }

    resetForm();
    fetchCategories();
  };

  const handleDelete = async (cat: Category) => {
    if (cat.expenseCount > 0) {
      setError(labels.cannotDelete);
      return;
    }
    if (!confirm(labels.confirmDelete)) return;

    const res = await fetch(`/api/dashboard/expenses/categories/${cat.id}`, {
      method: "DELETE",
    });
    const data = await res.json();
    if (!data.success) {
      setError(data.error);
    } else {
      fetchCategories();
    }
  };

  return (
    <div dir={isAr ? "rtl" : "ltr"}>
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
          {labels.title}
        </h3>
        <button
          onClick={() => {
            resetForm();
            setShowForm(true);
          }}
          className="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-700"
        >
          <span className="text-lg leading-none">+</span> {labels.addCategory}
        </button>
      </div>

      {error && (
        <div className="mb-3 rounded-lg bg-red-50 p-3 text-sm text-red-700 dark:bg-red-900/20 dark:text-red-300">
          {error}
        </div>
      )}

      {/* Inline form */}
      {showForm && (
        <div className="mb-4 flex flex-wrap items-end gap-3 rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800">
          <div>
            <label className="mb-1 block text-xs text-gray-500">
              {labels.name}
            </label>
            <input
              type="text"
              value={formName}
              onChange={(e) => setFormName(e.target.value)}
              className="rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-500">
              {labels.nameAr}
            </label>
            <input
              type="text"
              dir="rtl"
              value={formNameAr}
              onChange={(e) => setFormNameAr(e.target.value)}
              className="rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-500">
              {labels.color}
            </label>
            <input
              type="color"
              value={formColor}
              onChange={(e) => setFormColor(e.target.value)}
              className="h-10 w-14 cursor-pointer rounded border border-gray-300"
            />
          </div>
          <button
            onClick={handleSave}
            disabled={!formName.trim()}
            className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
          >
            {labels.save}
          </button>
          <button
            onClick={resetForm}
            className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-300"
          >
            {labels.cancel}
          </button>
        </div>
      )}

      {/* Category list */}
      {loading ? (
        <div className="flex h-32 items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-indigo-300 border-t-indigo-600" />
        </div>
      ) : categories.length === 0 ? (
        <p className="text-sm text-gray-500">{labels.noCategories}</p>
      ) : (
        <div className="space-y-2">
          {categories.map((cat) => (
            <div
              key={cat.id}
              className="flex items-center justify-between rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-700"
            >
              <div className="flex items-center gap-3">
                <span
                  className="h-4 w-4 rounded-full"
                  style={{ backgroundColor: cat.color }}
                />
                <span className="font-medium text-gray-900 dark:text-white">
                  {isAr && cat.nameAr ? cat.nameAr : cat.name}
                </span>
                <span className="text-xs text-gray-500">
                  ({cat.expenseCount} {labels.expenses})
                </span>
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => startEdit(cat)}
                  className="text-sm text-indigo-600 hover:underline dark:text-indigo-400"
                >
                  {labels.edit}
                </button>
                <button
                  onClick={() => handleDelete(cat)}
                  className="text-sm text-red-600 hover:underline dark:text-red-400"
                >
                  {labels.delete}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
