import { useState, useMemo } from 'react';
import { Drawer, Input, List, theme, Typography } from 'antd';
import { FolderOutlined, HomeOutlined } from '@ant-design/icons';
import type { FileNode } from '@/types/api';

interface DirEntry {
  path: string;
  depth: number;
}

function collectDirs(nodes: FileNode[], exclude?: string, depth = 0): DirEntry[] {
  const dirs: DirEntry[] = [];
  for (const node of nodes) {
    if (!node.isDirectory) continue;
    if (exclude && (node.path === exclude || node.path.startsWith(exclude + '/'))) continue;
    dirs.push({ path: node.path, depth });
    if (node.children) dirs.push(...collectDirs(node.children, exclude, depth + 1));
  }
  return dirs;
}

interface MoveToModalProps {
  open: boolean;
  fileTree: FileNode[];
  sourcePath: string;
  onMove: (targetDir: string) => void;
  onClose: () => void;
}

export function MoveToModal({ open, fileTree, sourcePath, onMove, onClose }: MoveToModalProps) {
  const { token } = theme.useToken();
  const [search, setSearch] = useState('');

  const currentParent = useMemo(() => {
    const lastSlash = sourcePath.lastIndexOf('/');
    return lastSlash >= 0 ? sourcePath.substring(0, lastSlash) : '';
  }, [sourcePath]);

  const isSourceDir = useMemo(() => {
    function find(nodes: FileNode[]): boolean {
      for (const n of nodes) {
        if (n.path === sourcePath) return n.isDirectory;
        if (n.isDirectory && n.children && find(n.children)) return true;
      }
      return false;
    }
    return find(fileTree);
  }, [fileTree, sourcePath]);

  const allDirs = useMemo(
    () => collectDirs(fileTree, isSourceDir ? sourcePath : undefined),
    [fileTree, sourcePath, isSourceDir],
  );

  const filtered = useMemo(() => {
    if (!search.trim()) return allDirs;
    const q = search.toLowerCase();
    return allDirs.filter(d => d.path.toLowerCase().includes(q));
  }, [allDirs, search]);

  const handleSelect = (dir: string) => {
    onMove(dir);
    setSearch('');
  };

  const handleClose = () => {
    onClose();
    setSearch('');
  };

  const fileName = sourcePath.split('/').pop() || sourcePath;

  return (
    <Drawer
      title={`Move "${fileName}"`}
      open={open}
      onClose={handleClose}
      width={420}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
    >
      <Input.Search
        placeholder="Search directories..."
        value={search}
        onChange={e => setSearch(e.target.value)}
        allowClear
        autoFocus
        style={{ marginBottom: 12 }}
      />

      <div style={{ maxHeight: 360, overflow: 'auto' }}>
        {/* Root directory option */}
        {(!search.trim() || '/ (root)'.includes(search.toLowerCase())) && (
          <div
            style={{
              padding: '8px 12px',
              cursor: currentParent === '' ? 'not-allowed' : 'pointer',
              opacity: currentParent === '' ? 0.5 : 1,
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              borderRadius: 4,
              transition: 'background 0.15s',
            }}
            onClick={() => currentParent !== '' && handleSelect('')}
            onMouseEnter={e => { if (currentParent !== '') (e.currentTarget.style.background = token.colorBgTextHover); }}
            onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
          >
            <HomeOutlined style={{ color: token.colorTextSecondary }} />
            <span style={{ flex: 1 }}>/ (root)</span>
            {currentParent === '' && (
              <Typography.Text type="secondary" style={{ fontSize: 11 }}>current</Typography.Text>
            )}
          </div>
        )}

        <List
          size="small"
          dataSource={filtered}
          locale={{ emptyText: 'No matching directories' }}
          renderItem={item => {
            const isCurrent = item.path === currentParent;
            return (
              <div
                style={{
                  padding: '8px 12px',
                  paddingLeft: 12 + item.depth * 16,
                  cursor: isCurrent ? 'not-allowed' : 'pointer',
                  opacity: isCurrent ? 0.5 : 1,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                  borderRadius: 4,
                  transition: 'background 0.15s',
                }}
                onClick={() => !isCurrent && handleSelect(item.path)}
                onMouseEnter={e => { if (!isCurrent) (e.currentTarget.style.background = token.colorBgTextHover); }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
              >
                <FolderOutlined style={{ color: token.colorTextSecondary, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {item.path}
                </div>
                {isCurrent && (
                  <Typography.Text type="secondary" style={{ fontSize: 11, flexShrink: 0 }}>current</Typography.Text>
                )}
              </div>
            );
          }}
        />
      </div>
    </Drawer>
  );
}
