"use client";

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

type LevelRow = { id: string; name: string; groupId: string };
type GroupRow = {
  id: string;
  name: string;
  targetPercentage: number;
  sortOrder: number;
  levels: LevelRow[];
};

type EditingGroup = {
  id?: string;
  name: string;
  targetPercentage: number;
  sortOrder: number;
};

type EditingLevel = {
  id?: string;
  name: string;
  groupId: string;
};

export function ManagementLevelsClient() {
  const [editingGroup, setEditingGroup] = useState<EditingGroup | null>(null);
  const [editingLevel, setEditingLevel] = useState<EditingLevel | null>(null);
  const [confirmDeleteLevel, setConfirmDeleteLevel] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const utils = trpc.useUtils();
  const { data: groups, isLoading } = trpc.managementLevel.listGroups.useQuery();

  const createGroupMut = trpc.managementLevel.createGroup.useMutation({
    onSuccess: () => { void utils.managementLevel.listGroups.invalidate(); setEditingGroup(null); },
    onError: (e) => setError(e.message),
  });
  const updateGroupMut = trpc.managementLevel.updateGroup.useMutation({
    onSuccess: () => { void utils.managementLevel.listGroups.invalidate(); setEditingGroup(null); },
    onError: (e) => setError(e.message),
  });
  const createLevelMut = trpc.managementLevel.createLevel.useMutation({
    onSuccess: () => { void utils.managementLevel.listGroups.invalidate(); setEditingLevel(null); },
    onError: (e) => setError(e.message),
  });
  const updateLevelMut = trpc.managementLevel.updateLevel.useMutation({
    onSuccess: () => { void utils.managementLevel.listGroups.invalidate(); setEditingLevel(null); },
    onError: (e) => setError(e.message),
  });
  const deleteLevelMut = trpc.managementLevel.deleteLevel.useMutation({
    onSuccess: () => void utils.managementLevel.listGroups.invalidate(),
    onError: (e) => setError(e.message),
  });

  function openCreateGroup() {
    const maxOrder = Math.max(0, ...(groups ?? []).map((g) => (g as unknown as GroupRow).sortOrder));
    setEditingGroup({ name: "", targetPercentage: 0, sortOrder: maxOrder + 1 });
    setError(null);
  }

  function openEditGroup(g: GroupRow) {
    setEditingGroup({ id: g.id, name: g.name, targetPercentage: g.targetPercentage, sortOrder: g.sortOrder });
    setError(null);
  }

  function handleSaveGroup() {
    if (!editingGroup) return;
    setError(null);
    if (editingGroup.id) {
      updateGroupMut.mutate({
        id: editingGroup.id,
        data: { name: editingGroup.name, targetPercentage: editingGroup.targetPercentage, sortOrder: editingGroup.sortOrder },
      });
    } else {
      createGroupMut.mutate({
        name: editingGroup.name,
        targetPercentage: editingGroup.targetPercentage,
        sortOrder: editingGroup.sortOrder,
      });
    }
  }

  function openCreateLevel(groupId: string) {
    setEditingLevel({ name: "", groupId });
    setError(null);
  }

  function openEditLevel(l: LevelRow) {
    setEditingLevel({ id: l.id, name: l.name, groupId: l.groupId });
    setError(null);
  }

  function handleSaveLevel() {
    if (!editingLevel) return;
    setError(null);
    if (editingLevel.id) {
      updateLevelMut.mutate({
        id: editingLevel.id,
        data: { name: editingLevel.name, groupId: editingLevel.groupId },
      });
    } else {
      createLevelMut.mutate({ name: editingLevel.name, groupId: editingLevel.groupId });
    }
  }

  const isGroupPending = createGroupMut.isPending || updateGroupMut.isPending;
  const isLevelPending = createLevelMut.isPending || updateLevelMut.isPending;
  const rows = (groups ?? []) as unknown as GroupRow[];

  return (
    <div className="p-6 max-w-5xl 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">Management Levels</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Level groups with chargeability targets and individual levels <InfoTooltip content="Management levels define seniority groups (e.g. Senior Management, Team Lead). Each group has a chargeability target that appears in chargeability reports. Individual levels within a group are assigned to resources." />
          </p>
        </div>
        <button
          type="button"
          onClick={openCreateGroup}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium"
        >
          + Add Group
        </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>
      )}

      {isLoading && <div className="text-center py-8 text-gray-400">Loading...</div>}

      <div className="space-y-4">
        {rows.map((group) => (
          <div key={group.id} className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
            {/* Group header */}
            <div className="flex items-center justify-between px-4 py-3 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center gap-3">
                <h3 className="font-semibold text-gray-900 dark:text-gray-100">{group.name}</h3>
                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400">
                  Target: {Math.round(group.targetPercentage * 100)}%
                </span>
                <InfoTooltip content="The chargeability target for this group. Resources in this group are expected to achieve this percentage of chargeable hours. Used in chargeability reports and dashboards." />
              </div>
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => openCreateLevel(group.id)}
                  className="text-xs text-green-600 hover:text-green-800 font-medium"
                >
                  + Level
                </button>
                <button
                  type="button"
                  onClick={() => openEditGroup(group)}
                  className="text-xs text-brand-600 hover:text-brand-800 font-medium"
                >
                  Edit Group
                </button>
              </div>
            </div>

            {/* Levels */}
            <div className="divide-y divide-gray-100 dark:divide-gray-800">
              {group.levels.length === 0 && (
                <div className="px-4 py-3 text-sm text-gray-400">No levels in this group yet.</div>
              )}
              {group.levels.map((level) => (
                <div key={level.id} className="flex items-center justify-between px-4 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-800/30 group">
                  <span className="text-sm text-gray-900 dark:text-gray-100">{level.name}</span>
                  <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      type="button"
                      onClick={() => openEditLevel(level)}
                      className="text-xs text-brand-600 hover:text-brand-800 font-medium"
                    >
                      Edit
                    </button>
                    <button
                      type="button"
                      onClick={() => setConfirmDeleteLevel(level.id)}
                      className="text-xs text-red-500 hover:text-red-700 font-medium"
                    >
                      Delete
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}

        {!isLoading && rows.length === 0 && (
          <div className="text-center py-8 text-gray-400">No management level groups yet.</div>
        )}
      </div>

      {/* Group Modal */}
      <AnimatedModal open={editingGroup !== null} onClose={() => setEditingGroup(null)} maxWidth="max-w-md">
        {editingGroup && (<>
            <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">
                {editingGroup.id ? "Edit Group" : "Add Group"}
              </h2>
              <button type="button" onClick={() => setEditingGroup(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>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Name <InfoTooltip content="The name of this management level group (e.g. Senior Management, Team Leads)." /></label>
                <input
                  type="text"
                  value={editingGroup.name}
                  onChange={(e) => setEditingGroup({ ...editingGroup, name: e.target.value })}
                  placeholder="e.g. Senior Management"
                  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 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">Target % (0-100) <InfoTooltip content="The chargeability target for resources in this group. Enter as a percentage (e.g. 70 for 70%). Used in chargeability reports." /></label>
                  <input
                    type="number"
                    value={Math.round(editingGroup.targetPercentage * 100)}
                    onChange={(e) => setEditingGroup({ ...editingGroup, targetPercentage: (parseInt(e.target.value) || 0) / 100 })}
                    min={0}
                    max={100}
                    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">Sort Order <InfoTooltip content="Controls the display order of groups. Lower numbers appear first." /></label>
                  <input
                    type="number"
                    value={editingGroup.sortOrder}
                    onChange={(e) => setEditingGroup({ ...editingGroup, 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>

            <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={() => setEditingGroup(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={handleSaveGroup}
                disabled={isGroupPending || !editingGroup.name}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                {isGroupPending ? "Saving..." : editingGroup.id ? "Update" : "Create"}
              </button>
            </div>
        </>)}
      </AnimatedModal>

      {/* Level Modal */}
      <AnimatedModal open={editingLevel !== null} onClose={() => setEditingLevel(null)} maxWidth="max-w-sm">
        {editingLevel && (<>
            <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">
                {editingLevel.id ? "Edit Level" : "Add Level"}
              </h2>
              <button type="button" onClick={() => setEditingLevel(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>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Level Name <InfoTooltip content="The specific title within the group (e.g. Managing Director, VP). This is assigned to individual resources." /></label>
                <input
                  type="text"
                  value={editingLevel.name}
                  onChange={(e) => setEditingLevel({ ...editingLevel, name: e.target.value })}
                  placeholder="e.g. Managing Director"
                  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">Group <InfoTooltip content="The management level group this level belongs to. Determines chargeability target and reporting." /></label>
                <select
                  value={editingLevel.groupId}
                  onChange={(e) => setEditingLevel({ ...editingLevel, groupId: e.target.value })}
                  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"
                >
                  {rows.map((g) => (
                    <option key={g.id} value={g.id}>{g.name}</option>
                  ))}
                </select>
              </div>
            </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={() => setEditingLevel(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={handleSaveLevel}
                disabled={isLevelPending || !editingLevel.name}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                {isLevelPending ? "Saving..." : editingLevel.id ? "Update" : "Create"}
              </button>
            </div>
        </>)}
      </AnimatedModal>

      {confirmDeleteLevel && (
        <ConfirmDialog
          title="Delete level"
          message="Are you sure you want to delete this level?"
          confirmLabel="Delete"
          variant="danger"
          onConfirm={() => {
            deleteLevelMut.mutate({ id: confirmDeleteLevel });
            setConfirmDeleteLevel(null);
          }}
          onCancel={() => setConfirmDeleteLevel(null)}
        />
      )}
    </div>
  );
}
