"use client";

import { useState } from "react";
import { AnimatedModal } from "~/components/ui/AnimatedModal.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { trpc } from "~/lib/trpc/client.js";

type CategoryRow = {
  id: string;
  code: string;
  name: string;
  description: string | null;
  sortOrder: number;
  isDefault: boolean;
  isActive: boolean;
};

type EditingCategory = {
  id?: string;
  code: string;
  name: string;
  description: string;
  sortOrder: number;
  isDefault: boolean;
};

const emptyCategory: EditingCategory = {
  code: "",
  name: "",
  description: "",
  sortOrder: 0,
  isDefault: false,
};

export function UtilizationCategoriesClient() {
  const [editing, setEditing] = useState<EditingCategory | null>(null);
  const [error, setError] = useState<string | null>(null);

  const utils = trpc.useUtils();
  const { data: categories, isLoading } = trpc.utilizationCategory.list.useQuery();

  const createMut = trpc.utilizationCategory.create.useMutation({
    onSuccess: () => { void utils.utilizationCategory.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });
  const updateMut = trpc.utilizationCategory.update.useMutation({
    onSuccess: () => { void utils.utilizationCategory.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });

  function openCreate() {
    const maxOrder = Math.max(0, ...(categories ?? []).map((c) => (c as unknown as CategoryRow).sortOrder));
    setEditing({ ...emptyCategory, sortOrder: maxOrder + 1 });
    setError(null);
  }

  function openEdit(c: CategoryRow) {
    setEditing({
      id: c.id,
      code: c.code,
      name: c.name,
      description: c.description ?? "",
      sortOrder: c.sortOrder,
      isDefault: c.isDefault,
    });
    setError(null);
  }

  function handleSave() {
    if (!editing) return;
    setError(null);

    if (editing.id) {
      updateMut.mutate({
        id: editing.id,
        data: {
          code: editing.code,
          name: editing.name,
          description: editing.description || undefined,
          sortOrder: editing.sortOrder,
          isDefault: editing.isDefault,
        },
      });
    } else {
      createMut.mutate({
        code: editing.code,
        name: editing.name,
        description: editing.description || undefined,
        sortOrder: editing.sortOrder,
        isDefault: editing.isDefault,
      });
    }
  }

  const isPending = createMut.isPending || updateMut.isPending;
  const rows = (categories ?? []) as unknown as CategoryRow[];

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-50">Utilization Categories</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Categories assigned to projects for chargeability reporting
          </p>
        </div>
        <button
          type="button"
          onClick={openCreate}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium"
        >
          + Add Category
        </button>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-4 py-3 text-sm text-red-700 dark:text-red-400 flex items-center justify-between">
          {error}
          <button type="button" onClick={() => setError(null)} className="text-red-400 hover:text-red-600 text-lg leading-none">&times;</button>
        </div>
      )}

      <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
              <th className="text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center">Code <InfoTooltip content="A short unique identifier (e.g. 'Chg', 'Int', 'OH'). Used in reports and exports." /></span></th>
              <th className="text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center">Name <InfoTooltip content="The display name for this category (e.g. 'Chargeable', 'Internal', 'Overhead'). Shown in dropdowns and reports." /></span></th>
              <th className="text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center">Description <InfoTooltip content="Explains what type of work falls into this category. Helps users choose the right category for projects." /></span></th>
              <th className="text-center px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center justify-center">Default <InfoTooltip content="The default category pre-selected when creating new projects. Only one category can be default." /></span></th>
              <th className="text-center px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center justify-center">Order <InfoTooltip content="Controls the display order in dropdowns and reports. Lower numbers appear first." /></span></th>
              <th className="text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr><td colSpan={6} className="text-center py-8 text-gray-400">Loading...</td></tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr><td colSpan={6} className="text-center py-8 text-gray-400">No categories yet.</td></tr>
            )}
            {rows.map((c) => (
              <tr key={c.id} className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/30">
                <td className="px-4 py-3 font-mono font-medium text-gray-900 dark:text-gray-100">{c.code}</td>
                <td className="px-4 py-3 text-gray-900 dark:text-gray-100">{c.name}</td>
                <td className="px-4 py-3 text-gray-500 dark:text-gray-400 text-xs max-w-xs truncate">{c.description ?? "—"}</td>
                <td className="px-4 py-3 text-center">
                  {c.isDefault && (
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400">Default</span>
                  )}
                </td>
                <td className="px-4 py-3 text-center text-gray-400">{c.sortOrder}</td>
                <td className="px-4 py-3 text-right">
                  <button type="button" onClick={() => openEdit(c)} className="text-xs text-brand-600 hover:text-brand-800 font-medium">Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Create/Edit Modal */}
      <AnimatedModal open={editing !== null} onClose={() => setEditing(null)} maxWidth="max-w-md">
        {editing && (<>
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                {editing.id ? "Edit Category" : "Add Category"}
              </h2>
              <button type="button" onClick={() => setEditing(null)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-2xl leading-none">&times;</button>
            </div>

            <div className="px-6 py-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Code <InfoTooltip content="A short unique identifier for this category. Used in reports and data exports." /></label>
                  <input
                    type="text"
                    value={editing.code}
                    onChange={(e) => setEditing({ ...editing, code: e.target.value })}
                    placeholder="Chg"
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400 font-mono"
                  />
                </div>
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Sort Order <InfoTooltip content="Controls display position. Lower numbers appear first." /></label>
                  <input
                    type="number"
                    value={editing.sortOrder}
                    onChange={(e) => setEditing({ ...editing, sortOrder: parseInt(e.target.value) || 0 })}
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                  />
                </div>
              </div>

              <div>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Name <InfoTooltip content="The display name shown in project dropdowns and chargeability reports." /></label>
                <input
                  type="text"
                  value={editing.name}
                  onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                  placeholder="Chargeable"
                  className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                />
              </div>

              <div>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Description <InfoTooltip content="Explains what type of work this category covers. Helps project managers choose the correct category." /></label>
                <textarea
                  value={editing.description}
                  onChange={(e) => setEditing({ ...editing, description: e.target.value })}
                  rows={2}
                  placeholder="Revenue-generating client project work"
                  className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400 resize-none"
                />
              </div>

              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
                <input
                  type="checkbox"
                  checked={editing.isDefault}
                  onChange={(e) => setEditing({ ...editing, isDefault: e.target.checked })}
                  className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
                />
                Default category for new projects <InfoTooltip content="When checked, new projects are automatically assigned this category." />
              </label>
            </div>

            <div className="flex items-center justify-end px-6 py-4 border-t border-gray-200 dark:border-gray-700 gap-3">
              <button type="button" onClick={() => setEditing(null)} className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">Cancel</button>
              <button
                type="button"
                onClick={handleSave}
                disabled={isPending || !editing.code || !editing.name}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                {isPending ? "Saving..." : editing.id ? "Update" : "Create"}
              </button>
            </div>
        </>)}
      </AnimatedModal>
    </div>
  );
}
