'use client';

import React, { forwardRef, useCallback, useMemo, useState, ReactNode } from 'react';
import {
  SortableTree,
  SimpleTreeItemWrapper,
  TreeItemComponentProps,
  TreeItems,
} from 'dnd-kit-sortable-tree';
import { Card, CardBody } from '@/components/ui/Card';
import Button from '@/components/ui/Button';

// ==================== TOOLTIP COMPONENT ====================

interface TooltipProps {
  text: string;
  children: ReactNode;
  position?: 'right' | 'top';
}

function Tooltip({ text, children, position = 'right' }: TooltipProps) {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div
      className="relative inline-flex"
      onMouseEnter={() => setIsVisible(true)}
      onMouseLeave={() => setIsVisible(false)}
    >
      {children}
      {isVisible && text && (
        <div
          className={`
            absolute z-50 text-xs font-medium text-white rounded-md shadow-xl whitespace-nowrap
            ${position === 'right' ? 'left-full ml-3 top-1/2 -translate-y-1/2' : 'bottom-full left-1/2 -translate-x-1/2 mb-3'}
          `}
          style={{
            backgroundColor: '#0f172a',
            padding: '8px 12px',
            border: '1px solid rgba(56, 189, 248, 0.3)',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.5)',
          }}
        >
          {text}
          {/* Arrow */}
          <div
            className={`
              absolute w-0 h-0
              ${position === 'right' ? 'right-full top-1/2 -translate-y-1/2 border-y-[6px] border-y-transparent border-r-[6px]' : 'top-full left-1/2 -translate-x-1/2 border-x-[6px] border-x-transparent border-t-[6px]'}
            `}
            style={{
              borderRightColor: position === 'right' ? '#0f172a' : 'transparent',
              borderTopColor: position === 'top' ? '#0f172a' : 'transparent',
            }}
          />
        </div>
      )}
    </div>
  );
}

// ==================== TYPES ====================

export interface NavItemData {
  id: string;
  label: string;
  linkType: 'none' | 'page' | 'external' | 'pdf';
  pageId: string | null;
  pageSlug: string | null;
  externalUrl: string | null;
  openInNewTab: boolean;
  isDefault: boolean;
  defaultKey: string | null;
  defaultSortOrder: number | null;
}

// TreeItem type for dnd-kit-sortable-tree
export type NavTreeItem = NavItemData & {
  children: NavTreeItem[];
  canHaveChildren?: boolean;
};

// ==================== ICONS ====================
// Icons use design system colors: white/50 default, white/70 hover, cyan/red for actions

function ChevronIcon({ isOpen }: { isOpen: boolean }) {
  return (
    <svg
      className={`w-4 h-4 transition-transform duration-200 ${isOpen ? 'rotate-90' : ''}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}

function ExternalLinkIcon() {
  return (
    <svg
      className="ml-2 text-white/50"
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-label="External link"
    >
      <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
      <polyline points="15 3 21 3 21 9" />
      <line x1="10" y1="14" x2="21" y2="3" />
    </svg>
  );
}

function PageLinkIcon() {
  return (
    <svg
      className="ml-2 text-white/50"
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-label="Internal page link"
    >
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
    </svg>
  );
}

function PdfLinkIcon() {
  return (
    <svg
      className="ml-2 text-white/50"
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-label="PDF document link"
    >
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <text x="12" y="17" textAnchor="middle" fill="currentColor" stroke="none" fontSize="7" fontWeight="bold">PDF</text>
    </svg>
  );
}

function GripIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <circle cx="9" cy="5" r="1.5" />
      <circle cx="15" cy="5" r="1.5" />
      <circle cx="9" cy="12" r="1.5" />
      <circle cx="15" cy="12" r="1.5" />
      <circle cx="9" cy="19" r="1.5" />
      <circle cx="15" cy="19" r="1.5" />
    </svg>
  );
}

function TrashIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="3 6 5 6 21 6" />
      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
    </svg>
  );
}

function EditIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
    </svg>
  );
}

// ==================== NAV TREE ITEM COMPONENT ====================

interface NavTreeItemProps extends TreeItemComponentProps<NavTreeItem> {
  onEdit?: (item: NavTreeItem) => void;
  onDelete?: (itemId: string) => void;
}

const NavTreeItemComponent = forwardRef<HTMLDivElement, NavTreeItemProps>(
  function NavTreeItemComponent(props, ref) {
    const { onEdit, onDelete, ...wrapperProps } = props;
    const { item } = props;
    const isDragging = props.clone;
    const hasChildren = item.children && item.children.length > 0;
    const isCollapsed = props.collapsed;
    const depth = props.depth || 0;
    const isTopLevel = depth === 0;

    // Wrapper background - applies to full width of the tree item
    const getWrapperBackground = () => {
      if (isDragging) return 'rgba(255, 255, 255, 0.1)';
      // Top-level parents get a subtle blue-tinted background (like spreadsheet alternating rows)
      if (isTopLevel) return 'rgba(56, 189, 248, 0.06)';
      // Children have no background (they're indented so parent color shows hierarchy)
      return 'transparent';
    };

    return (
      <SimpleTreeItemWrapper
        {...wrapperProps}
        ref={ref}
        manualDrag
        showDragHandle={false}
        style={{ backgroundColor: getWrapperBackground() }}
      >
        <div
          className={`
            flex items-center
            border-b border-white/10
            transition-all duration-200
            hover:bg-white/5
            ${isDragging ? 'rounded-lg shadow-lg' : ''}
          `}
          style={{ padding: '16px 20px', gap: '20px' }}
        >
          {/* Drag Handle */}
          <Tooltip text="Drag to reorder">
            <div
              className="cursor-grab text-white/50 hover:text-white/80 transition-colors flex-shrink-0"
              {...props.handleProps}
            >
              <GripIcon />
            </div>
          </Tooltip>

          {/* Label and link type icons */}
          <span className="flex-1 font-medium flex items-center text-white" style={{ gap: '8px' }}>
            <Tooltip text={item.externalUrl || (item.pageSlug ? `/${item.pageSlug}` : '') || ''}>
              <span className="cursor-default">{item.label}</span>
            </Tooltip>
            {item.linkType === 'external' && (
              <Tooltip text="Opens external website">
                <span>
                  <ExternalLinkIcon />
                </span>
              </Tooltip>
            )}
            {item.linkType === 'page' && (
              <Tooltip text="Links to internal page">
                <span>
                  <PageLinkIcon />
                </span>
              </Tooltip>
            )}
            {item.linkType === 'pdf' && (
              <Tooltip text="Opens PDF document">
                <span>
                  <PdfLinkIcon />
                </span>
              </Tooltip>
            )}
          </span>

          {/* Actions row - edit, delete, chevron all aligned at end */}
          <div className="flex items-center flex-shrink-0" style={{ gap: '16px' }}>
            <Tooltip text="Edit item">
              <button
                className="text-white/50 hover:text-[#38bdf8] transition-colors"
                style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
                onClick={() => onEdit?.(item)}
                type="button"
              >
                <EditIcon />
              </button>
            </Tooltip>
            <Tooltip text="Delete item">
              <button
                className="text-white/50 hover:text-[#f87171] transition-colors"
                style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
                onClick={() => onDelete?.(item.id)}
                type="button"
              >
                <TrashIcon />
              </button>
            </Tooltip>

            {/* Chevron for items with children - aligned with other icons */}
            {hasChildren && (
              <Tooltip text={isCollapsed ? 'Expand children' : 'Collapse children'}>
                <button
                  className="text-white/50 hover:text-white/80 transition-colors"
                  style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
                  onClick={() => props.onCollapse?.()}
                  type="button"
                >
                  <ChevronIcon isOpen={!isCollapsed} />
                </button>
              </Tooltip>
            )}
          </div>
        </div>
      </SimpleTreeItemWrapper>
    );
  }
);

// ==================== HEADER PREVIEW COMPONENT ====================

interface HeaderPreviewProps {
  items: NavTreeItem[];
  dealerName?: string;
  dealerCity?: string;
  dealerPhone?: string;
}

function HeaderPreview({
  items,
  dealerName = 'Your Name',
  dealerCity = 'Your City, ST',
  dealerPhone = '(555) 123-4567',
}: HeaderPreviewProps) {
  return (
    <Card variant="surface" style={{ marginBottom: '1.5rem' }}>
      <CardBody style={{ overflow: 'visible' }}>
        <h3 className="text-sm font-medium text-white/70 mb-4">Live Header Preview</h3>
        <div className="rounded-lg" style={{ overflow: 'visible' }}>
          {/* Header Row 1 - Black bar with logo + INDEPENDENT DEALER + contact */}
          <div style={{ backgroundColor: '#000000', padding: '0.5rem 1rem' }}>
            <div className="flex justify-between items-center">
              <div className="flex items-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/images/logo/amsoil-logo.png"
                  alt="AMSOIL"
                  style={{ maxWidth: '80px', marginRight: '15px' }}
                  onError={(e) => {
                    e.currentTarget.style.display = 'none';
                    e.currentTarget.nextElementSibling?.classList.remove('hidden');
                  }}
                />
                <span
                  className="hidden text-white font-bold text-sm tracking-wide"
                  style={{ marginRight: '15px' }}
                >
                  AMSOIL
                </span>
                <span className="text-white/80 text-[10px] font-semibold tracking-wider uppercase">
                  Independent Dealer
                </span>
              </div>
              <div className="flex items-center gap-4 text-white/60 text-[10px]">
                <span>📍 {dealerCity}</span>
                <span>📞 {dealerPhone}</span>
              </div>
            </div>
          </div>

          {/* Header Row 2 - Navy bar with dealer name + navigation on same row */}
          <div style={{ backgroundColor: '#093b66', padding: '0.75rem 1rem' }}>
            <div className="flex items-center flex-wrap" style={{ gap: '2rem' }}>
              {/* Dealer name - to the LEFT of menu */}
              <span className="text-white font-bold text-base">{dealerName}</span>

              {/* Navigation - same row as dealer name */}
              <nav className="flex flex-wrap items-center" style={{ gap: '1.5rem' }}>
                {items.length === 0 ? (
                  <span className="text-white/40 text-sm italic">
                    Your navigation items will appear here
                  </span>
                ) : (
                  items.map((item) => (
                    <div key={item.id} className="relative group">
                      <span className="text-white font-semibold text-sm cursor-pointer hover:text-white/80 transition-colors">
                        {item.label}
                        {item.children.length > 0 && <span className="ml-1 text-white/60">▾</span>}
                      </span>
                      {/* Dropdown on hover */}
                      {item.children.length > 0 && (
                        <div
                          className="absolute left-0 top-full pt-2 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-150 z-10"
                          style={{ minWidth: '200px' }}
                        >
                          <div
                            className="rounded-md shadow-lg py-3"
                            style={{ backgroundColor: '#0a4a7a' }}
                          >
                            {item.children.map((child) => (
                              <div
                                key={child.id}
                                className="text-white/90 text-sm hover:bg-white/10 cursor-pointer"
                                style={{ padding: '12px 20px' }}
                              >
                                {child.label}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </nav>
            </div>
          </div>
        </div>
      </CardBody>
    </Card>
  );
}

// ==================== MAIN EDITOR COMPONENT ====================

interface NavTreeEditorProps {
  items: NavTreeItem[];
  onItemsChange: (items: NavTreeItem[]) => void;
  onAddItem?: () => void;
  onEditItem?: (item: NavTreeItem) => void;
  maxDepth?: number;
  dealerName?: string;
  dealerCity?: string;
  dealerPhone?: string;
}

export function NavTreeEditor({
  items,
  onItemsChange,
  onAddItem,
  onEditItem,
  maxDepth = 1, // Navigation only supports 2 levels (0 = top, 1 = child)
  dealerName,
  dealerCity,
  dealerPhone,
}: NavTreeEditorProps) {
  const handleDelete = useCallback(
    (itemId: string) => {
      const removeItem = (treeItems: NavTreeItem[]): NavTreeItem[] => {
        return treeItems
          .filter((item) => item.id !== itemId)
          .map((item) => ({
            ...item,
            children: removeItem(item.children),
          }));
      };
      onItemsChange(removeItem(items));
    },
    [items, onItemsChange]
  );

  // Create a wrapped component that includes our callbacks
  // Using useMemo instead of useCallback for component factory (proper pattern for HOCs)
  const TreeItemWithCallbacks = useMemo(
    () =>
      forwardRef<HTMLDivElement, TreeItemComponentProps<NavTreeItem>>(
        function TreeItemWithCallbacks(props, ref) {
          return (
            <NavTreeItemComponent
              {...props}
              ref={ref}
              onEdit={onEditItem}
              onDelete={handleDelete}
            />
          );
        }
      ),
    [onEditItem, handleDelete]
  );

  // Prepare items with canHaveChildren flag
  const treeItems = useMemo(() => {
    const prepare = (treeItems: NavTreeItem[], depth = 0): TreeItems<NavTreeItem> => {
      return treeItems.map((item) => ({
        ...item,
        canHaveChildren: depth < maxDepth,
        children: prepare(item.children, depth + 1),
      }));
    };
    return prepare(items);
  }, [items, maxDepth]);

  return (
    <>
      {/* Card 1: Header Preview (shown first for intuitive layout) */}
      <HeaderPreview
        items={items}
        dealerName={dealerName}
        dealerCity={dealerCity}
        dealerPhone={dealerPhone}
      />

      {/* Card 2: Navigation Items */}
      <Card variant="surface">
        <CardBody>
          {/* Header */}
          <div
            className="flex justify-between items-center border-b border-white/10"
            style={{ paddingBottom: '20px', marginBottom: '20px' }}
          >
            <h3 className="text-lg font-semibold text-white">Navigation Items</h3>
            {onAddItem && (
              <Button variant="primary" size="sm" onClick={onAddItem}>
                + Add Item
              </Button>
            )}
          </div>

          {/* Tree or Empty State */}
          {items.length === 0 ? (
            <div className="text-center py-12 text-white/50">
              <p>No navigation items yet. Click &quot;Add Item&quot; to get started.</p>
            </div>
          ) : (
            <SortableTree
              items={treeItems}
              onItemsChanged={(newItems) => {
                onItemsChange(newItems as NavTreeItem[]);
              }}
              TreeItemComponent={TreeItemWithCallbacks}
              indentationWidth={32}
              pointerSensorOptions={{
                activationConstraint: {
                  distance: 5,
                },
              }}
            />
          )}
        </CardBody>
      </Card>
    </>
  );
}

export default NavTreeEditor;
