"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { Plus, Pencil, Trash2, Wrench } from "lucide-react";
import { useToolsMenuContext } from "@/hooks/useToolsMenuContext";
import type { ToolEntry, ToolType, ToolConfigField, AppIcon } from "@/lib/types";
import { ToolGrid } from "./ToolGrid";
import { ToolModal } from "./ToolModal";
import { ToolTypeModal } from "./ToolTypeModal";
import { DeleteConfirmModal } from "./DeleteConfirmModal";

interface ToolsMenuViewProps {
  activeSubcategory: string;
}

function parseSubcategory(sub: string): string | null {
  if (sub.startsWith("type:")) {
    return sub.slice("type:".length);
  }
  return null;
}

export function ToolsMenuView({ activeSubcategory }: ToolsMenuViewProps) {
  const {
    types,
    tools,
    typeDefinitions,
    loading,
    addType,
    updateType,
    deleteType,
    updateTypeFields,
    addTool,
    updateTool,
    deleteTool,
    updateViewOrder,
  } = useToolsMenuContext();

  const typeId = parseSubcategory(activeSubcategory);
  const isAddMode = typeId === "add";

  // View order state
  const [viewOrder, setViewOrder] = useState<string[]>([]);

  // Modal state
  const [toolModalOpen, setToolModalOpen] = useState(false);
  const [editingTool, setEditingTool] = useState<ToolEntry | null>(null);
  const [typeModalOpen, setTypeModalOpen] = useState(false);
  const [editingType, setEditingType] = useState<ToolType | null>(null);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleteAffectedTools, setDeleteAffectedTools] = useState<ToolEntry[]>([]);

  // Auto-open type modal in add mode
  useEffect(() => {
    if (isAddMode) {
      setEditingType(null);
      setTypeModalOpen(true);
    }
  }, [isAddMode]);

  // Fetch view order when type changes
  const viewKey = useMemo(() => {
    if (!typeId || isAddMode) return null;
    return `type:${typeId}`;
  }, [typeId, isAddMode]);

  // Re-fetch view order when tools change (add/delete) or type changes
  useEffect(() => {
    if (!viewKey) {
      setViewOrder([]);
      return;
    }
    fetch(`/api/tools-menu/view-orders/${encodeURIComponent(viewKey)}`)
      .then((r) => r.json())
      .then((data) => setViewOrder(data.order ?? []))
      .catch(() => setViewOrder([]));
  }, [viewKey, tools]);

  // Find the current type
  const currentType = !isAddMode ? types.find((t) => t.id === typeId) ?? null : null;

  // Filter tools for the current type
  const filteredTools = useMemo(() => {
    if (!typeId || isAddMode) return [];
    return tools.filter((t) => t.typeId === typeId);
  }, [tools, typeId, isAddMode]);

  // Handlers
  const handleReorder = useCallback(
    (newOrder: string[]) => {
      setViewOrder(newOrder);
      if (viewKey) {
        updateViewOrder(viewKey, newOrder);
      }
    },
    [viewKey, updateViewOrder],
  );

  const handleEditTool = useCallback((tool: ToolEntry) => {
    setEditingTool(tool);
    setToolModalOpen(true);
  }, []);

  const handleToolSave = useCallback(
    async (data: {
      name: string;
      typeId: string;
      address?: string;
      description?: string;
      icon: AppIcon;
      color: string;
      config: Record<string, string>;
      status: "online" | "offline";
    }) => {
      if (editingTool) {
        await updateTool(editingTool.id, data);
      } else {
        await addTool(data);
      }
      setToolModalOpen(false);
      setEditingTool(null);
    },
    [editingTool, updateTool, addTool],
  );

  const handleToolDelete = useCallback(async () => {
    if (editingTool) {
      await deleteTool(editingTool.id);
      setToolModalOpen(false);
      setEditingTool(null);
    }
  }, [editingTool, deleteTool]);

  const handleTypeSave = useCallback(
    async (data: {
      name: string;
      description?: string;
      icon: AppIcon;
      configFields: ToolConfigField[];
    }) => {
      const { configFields, ...typeData } = data;
      if (editingType) {
        await updateType(editingType.id, typeData);
        await updateTypeFields(editingType.id, configFields);
      } else {
        await addType({ ...typeData, configFields });
      }
      setTypeModalOpen(false);
      setEditingType(null);
    },
    [editingType, updateType, updateTypeFields, addType],
  );

  const handleDeleteType = useCallback(async () => {
    if (!typeId || isAddMode) return;
    const result = await deleteType(typeId);
    if (!result.deleted && result.affectedTools) {
      setDeleteAffectedTools(result.affectedTools);
      setDeleteModalOpen(true);
    }
  }, [typeId, isAddMode, deleteType]);

  const handleCascadeDelete = useCallback(async () => {
    if (!typeId || isAddMode) return;
    await deleteType(typeId, true);
    setDeleteModalOpen(false);
    setDeleteAffectedTools([]);
  }, [typeId, isAddMode, deleteType]);

  const handleReassign = useCallback(
    async (newTypeId: string) => {
      if (!typeId || isAddMode) return;
      for (const tool of deleteAffectedTools) {
        await updateTool(tool.id, { typeId: newTypeId });
      }
      await deleteType(typeId, true);
      setDeleteModalOpen(false);
      setDeleteAffectedTools([]);
    },
    [typeId, isAddMode, deleteAffectedTools, updateTool, deleteType],
  );

  // Alternatives for delete reassign
  const deleteAlternatives = useMemo(() => {
    return types
      .filter((t) => t.id !== typeId)
      .map((t) => ({ id: t.id, name: t.name }));
  }, [types, typeId]);

  // Edit config fields for current type
  const currentConfigFields = currentType ? typeDefinitions[currentType.id]?.configFields || [] : [];

  // Loading state
  if (loading) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <p className="text-sm text-zinc-400 dark:text-zinc-500">Loading tools...</p>
      </div>
    );
  }

  // Add mode
  if (isAddMode) {
    return (
      <>
        <div className="flex flex-1 items-center justify-center">
          <p className="text-sm text-zinc-400 dark:text-zinc-500">
            Adding a new type...
          </p>
        </div>
        <ToolTypeModal
          open={typeModalOpen}
          onClose={() => setTypeModalOpen(false)}
          onSave={handleTypeSave}
        />
      </>
    );
  }

  // Type not found
  if (!currentType) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <p className="text-sm text-zinc-400 dark:text-zinc-500">Type not found.</p>
      </div>
    );
  }

  return (
    <div className="flex flex-1 flex-col overflow-hidden">
      {/* Top bar */}
      <div className="flex items-center justify-between border-b border-zinc-200 px-3 py-3 md:px-6 md:py-4 dark:border-zinc-800">
        <div className="flex min-w-0 items-center gap-2 md:gap-3">
          <Wrench size={20} className="shrink-0 text-zinc-400" />
          <div className="min-w-0">
            <h2 className="truncate text-base font-semibold text-zinc-900 md:text-lg dark:text-zinc-100">
              {currentType.name}
            </h2>
            {currentType.description && (
              <p className="truncate text-sm text-zinc-500 dark:text-zinc-400">
                {currentType.description}
              </p>
            )}
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-1 md:gap-2">
          <button
            onClick={() => {
              setEditingTool(null);
              setToolModalOpen(true);
            }}
            className="flex items-center gap-1.5 rounded-lg bg-blue-600 px-2.5 py-2 text-sm font-medium text-white hover:bg-blue-700 md:px-3"
          >
            <Plus size={16} />
            <span className="hidden sm:inline">Add Tool</span>
          </button>
          <button
            onClick={() => {
              setEditingType(currentType);
              setTypeModalOpen(true);
            }}
            className="flex items-center gap-1.5 rounded-lg px-2.5 py-2 text-sm text-zinc-600 hover:bg-zinc-100 md:px-3 dark:text-zinc-400 dark:hover:bg-zinc-800"
          >
            <Pencil size={14} />
            <span className="hidden sm:inline">Edit</span>
          </button>
          <button
            onClick={handleDeleteType}
            className="flex items-center gap-1.5 rounded-lg px-2.5 py-2 text-sm text-red-500 hover:bg-red-50 md:px-3 dark:hover:bg-red-950/30"
          >
            <Trash2 size={14} />
            <span className="hidden sm:inline">Delete</span>
          </button>
        </div>
      </div>

      {/* Tool grid or empty state */}
      {filteredTools.length === 0 ? (
        <div className="flex flex-1 items-center justify-center">
          <div className="flex flex-col items-center gap-3 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-zinc-100 dark:bg-zinc-800">
              <Wrench size={24} className="text-zinc-400" />
            </div>
            <div>
              <p className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                No tools yet
              </p>
              <p className="mt-1 text-xs text-zinc-500 dark:text-zinc-400">
                Add your first {currentType.name} tool.
              </p>
            </div>
            <button
              onClick={() => {
                setEditingTool(null);
                setToolModalOpen(true);
              }}
              className="flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-2 text-sm font-medium text-white hover:bg-blue-700"
            >
              <Plus size={16} />
              Add Tool
            </button>
          </div>
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto">
          <ToolGrid
            tools={filteredTools}
            order={viewOrder}
            onEditTool={handleEditTool}
            onReorder={handleReorder}
          />
        </div>
      )}

      {/* Modals */}
      <ToolModal
        open={toolModalOpen}
        onClose={() => {
          setToolModalOpen(false);
          setEditingTool(null);
        }}
        onSave={handleToolSave}
        onDelete={editingTool ? handleToolDelete : undefined}
        editTool={editingTool}
        types={types}
        typeDefinitions={typeDefinitions}
        defaultTypeId={typeId ?? undefined}
      />
      <ToolTypeModal
        open={typeModalOpen}
        onClose={() => {
          setTypeModalOpen(false);
          setEditingType(null);
        }}
        onSave={handleTypeSave}
        editType={editingType}
        editConfigFields={editingType ? currentConfigFields : undefined}
      />
      <DeleteConfirmModal
        open={deleteModalOpen}
        onClose={() => {
          setDeleteModalOpen(false);
          setDeleteAffectedTools([]);
        }}
        entityName={currentType.name}
        affectedTools={deleteAffectedTools}
        alternatives={deleteAlternatives}
        onCascade={handleCascadeDelete}
        onReassign={handleReassign}
      />
    </div>
  );
}
