import type { Meta, StoryObj } from '@storybook/react';
import { TreeView } from './tree-view';
import { useTreeView, type TreeNode } from './use-tree-view';
import { Folder, File, Code, Database, Globe, ChevronRight, ChevronDown } from 'lucide-react';
import React, { useState } from 'react';
import { cn } from '../../shared/utils';

const meta: Meta<typeof TreeView> = {
  title: 'UI/TreeView',
  component: TreeView,
  render: args => <TreeView {...args} />,
};

export default meta;
type Story = StoryObj<typeof TreeView>;

const fileTree: TreeNode[] = [
  {
    id: 'root',
    label: 'Project',
    icon: <Folder className="h-4 w-4" />,
    children: [
      {
        id: 'src',
        label: 'src',
        icon: <Folder className="h-4 w-4" />,
        children: [
          {
            id: 'components',
            label: 'components',
            icon: <Folder className="h-4 w-4" />,
            children: [
              { id: 'btn', label: 'Button.tsx', icon: <Code className="h-4 w-4" /> },
              { id: 'inp', label: 'Input.tsx', icon: <Code className="h-4 w-4" /> },
            ],
          },
          { id: 'app', label: 'App.tsx', icon: <Code className="h-4 w-4" /> },
        ],
      },
      {
        id: 'public',
        label: 'public',
        icon: <Globe className="h-4 w-4" />,
        children: [{ id: 'favicon', label: 'favicon.ico', icon: <File className="h-4 w-4" /> }],
      },
      { id: 'json', label: 'package.json', icon: <Database className="h-4 w-4" /> },
    ],
  },
];

export const Default: Story = {
  args: {
    data: fileTree,
  },
  render: args => (
    <div className="w-[300px] rounded-lg border p-4">
      <TreeView {...args} onNodeSelect={node => console.log('Selected:', node)} />
    </div>
  ),
};

/**
 * ## useTreeView — Headless Hook
 *
 * Use `useTreeView` when you need the full tree logic (expand/collapse,
 * keyboard navigation, selection) but want to render a completely custom UI.
 * The example below renders a flat indented list with custom styling instead
 * of the default `<TreeView>` component.
 *
 * ```tsx
 * import { useTreeView } from '@xertica/ui/tree-view';
 *
 * const { expanded, effectiveSelectedId, toggleExpand, handleSelect, handleKeyDown, getNodeRef } =
 *   useTreeView({ data, onNodeSelect });
 * ```
 */
export const HeadlessHook: Story = {
  name: 'useTreeView (headless)',
  render: () => {
    const [selectedId, setSelectedId] = useState<string | undefined>(undefined);

    const { expanded, effectiveSelectedId, getNodeRef, toggleExpand, handleSelect, handleKeyDown } =
      useTreeView({
        data: fileTree,
        defaultExpanded: ['root', 'src'],
        selectedNodeId: selectedId,
        onNodeSelect: node => {
          setSelectedId(node.id);
          console.log('Selected:', node.label);
        },
      });

    const renderNode = (node: TreeNode, level: number): React.ReactNode => {
      const hasChildren = !!node.children?.length;
      const isExpanded = expanded.has(node.id);
      const isSelected = node.id === effectiveSelectedId;

      return (
        <div key={node.id}>
          <button
            ref={getNodeRef(node.id)}
            role="treeitem"
            aria-expanded={hasChildren ? isExpanded : undefined}
            aria-selected={isSelected}
            tabIndex={isSelected ? 0 : -1}
            onClick={() => {
              if (hasChildren) toggleExpand(node.id);
              handleSelect(node);
            }}
            onKeyDown={e => handleKeyDown(e, node)}
            style={{ paddingLeft: `${level * 16 + 8}px` }}
            className={cn(
              'flex w-full items-center gap-1.5 rounded py-1 pr-2 text-left text-sm transition-colors',
              'hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring',
              isSelected ? 'bg-primary text-primary-foreground font-semibold' : 'text-foreground'
            )}
          >
            {hasChildren ? (
              <span className="flex-shrink-0">
                {isExpanded ? (
                  <ChevronDown className="h-3.5 w-3.5" />
                ) : (
                  <ChevronRight className="h-3.5 w-3.5" />
                )}
              </span>
            ) : (
              <span className="w-3.5 flex-shrink-0" />
            )}
            {node.icon && <span className="flex-shrink-0 opacity-70">{node.icon}</span>}
            <span>{node.label}</span>
          </button>

          {hasChildren && isExpanded && (
            <div role="group">{node.children!.map(child => renderNode(child, level + 1))}</div>
          )}
        </div>
      );
    };

    return (
      <div className="w-[280px] space-y-1 rounded-xl border bg-card p-3 shadow-sm">
        <p className="mb-2 px-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
          Explorer
        </p>
        <div role="tree">{fileTree.map(node => renderNode(node, 0))}</div>
        {selectedId && (
          <p className="mt-3 border-t pt-2 px-2 text-xs text-muted-foreground">
            Selected: <span className="font-medium text-foreground">{selectedId}</span>
          </p>
        )}
      </div>
    );
  },
};
