'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';

interface Post {
  slug: string;
  title: string;
  date: string;
  tags: string[];
  summary: string;
  content: string;
}

interface Folder {
  type: 'folder';
  name: string;
  path: string;
  children: (Post | Folder)[];
}

interface Post {
  type: 'post';
  slug: string;
  title: string;
  date: string;
  tags: string[];
  summary: string;
  content: string;
}

type Node = Post | Folder;

export default function AdminPage() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [nodes, setNodes] = useState<Node[]>([]);
  const [currentPath, setCurrentPath] = useState<string[]>([]);
  const [newPost, setNewPost] = useState({
    title: '',
    date: new Date().toISOString().split('T')[0],
    tags: '',
    summary: '',
    content: '',
  });
  const [newFolderName, setNewFolderName] = useState('');
  const [isDragging, setIsDragging] = useState(false);
  const router = useRouter();

  useEffect(() => {
    // Check if already authenticated
    const auth = localStorage.getItem('adminAuth');
    if (auth === 'true') {
      setIsAuthenticated(true);
      loadContent();
    }
  }, []);

  const loadContent = async () => {
    try {
      const response = await fetch('/api/posts');
      const data = await response.json();
      setNodes(data);
    } catch (error) {
      console.error('Error loading content:', error);
    }
  };

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (username === 'admin' && password === 'admin') {
      setIsAuthenticated(true);
      localStorage.setItem('adminAuth', 'true');
      loadContent();
    } else {
      alert('Invalid credentials');
    }
  };

  const handleLogout = () => {
    setIsAuthenticated(false);
    localStorage.removeItem('adminAuth');
  };

  const handleCreatePost = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const response = await fetch('/api/admin/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...newPost,
          tags: newPost.tags.split(',').map(tag => tag.trim()),
          path: currentPath.join('/'),
        }),
      });

      if (response.ok) {
        setNewPost({
          title: '',
          date: new Date().toISOString().split('T')[0],
          tags: '',
          summary: '',
          content: '',
        });
        loadContent();
      } else {
        alert('Error creating post');
      }
    } catch (error) {
      console.error('Error creating post:', error);
      alert('Error creating post');
    }
  };

  const handleCreateFolder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFolderName.trim()) {
      alert('Please enter a folder name');
      return;
    }

    try {
      const response = await fetch('/api/admin/folders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: newFolderName,
          path: currentPath.join('/'),
        }),
      });

      if (response.ok) {
        setNewFolderName('');
        loadContent();
      } else {
        alert('Error creating folder');
      }
    } catch (error) {
      console.error('Error creating folder:', error);
      alert('Error creating folder');
    }
  };

  // Get current directory contents
  const getCurrentNodes = (): Node[] => {
    let currentNodes: Node[] = nodes;
    for (const segment of currentPath) {
      const folder = currentNodes.find(
        (n) => n.type === 'folder' && n.name === segment
      ) as Folder | undefined;
      if (folder) {
        currentNodes = folder.children;
      } else {
        break;
      }
    }
    return currentNodes;
  };

  const currentNodes = getCurrentNodes();

  // Breadcrumbs
  const breadcrumbs = [
    { name: 'Root', path: [] },
    ...currentPath.map((name, idx) => ({
      name,
      path: currentPath.slice(0, idx + 1),
    })),
  ];

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(async (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);

    const files = Array.from(e.dataTransfer.files);
    const markdownFiles = files.filter(file => file.name.endsWith('.md'));

    if (markdownFiles.length === 0) {
      alert('Please drop only Markdown files');
      return;
    }

    for (const file of markdownFiles) {
      try {
        const content = await file.text();
        const formData = new FormData();
        formData.append('file', file);
        formData.append('path', currentPath.join('/'));

        const response = await fetch('/api/admin/upload', {
          method: 'POST',
          body: formData,
        });

        if (!response.ok) {
          throw new Error(`Failed to upload ${file.name}`);
        }
      } catch (error) {
        console.error(`Error uploading ${file.name}:`, error);
        alert(`Error uploading ${file.name}`);
      }
    }

    loadContent();
  }, [currentPath]);

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="max-w-md w-full space-y-8 p-8 bg-white rounded-lg shadow">
          <h2 className="text-3xl font-bold text-center">Admin Login</h2>
          <form onSubmit={handleLogin} className="space-y-6">
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-gray-700">
                Username
              </label>
              <input
                type="text"
                id="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                required
              />
            </div>
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                Password
              </label>
              <input
                type="password"
                id="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                required
              />
            </div>
            <button
              type="submit"
              className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
            >
              Login
            </button>
          </form>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen p-8 bg-gray-50">
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-bold">Admin Dashboard</h1>
          <button
            onClick={handleLogout}
            className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
          >
            Logout
          </button>
        </div>

        {/* Breadcrumb Navigation */}
        <nav className="mb-6 text-sm text-gray-600 flex gap-2 items-center">
          {breadcrumbs.map((bc, idx) => (
            <span key={bc.path.join('/') + idx}>
              {idx > 0 && <span className="mx-1">/</span>}
              <button
                className="hover:underline"
                onClick={() => setCurrentPath(bc.path)}
                disabled={idx === breadcrumbs.length - 1}
              >
                {bc.name}
              </button>
            </span>
          ))}
        </nav>

        {/* Create Folder Form */}
        <div className="bg-white rounded-lg shadow p-6 mb-8">
          <h2 className="text-2xl font-bold mb-4">Create New Folder</h2>
          <form onSubmit={handleCreateFolder} className="flex gap-4">
            <input
              type="text"
              value={newFolderName}
              onChange={(e) => setNewFolderName(e.target.value)}
              placeholder="Folder name"
              className="flex-1 rounded-md border border-gray-300 px-3 py-2"
              required
            />
            <button
              type="submit"
              className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
            >
              Create Folder
            </button>
          </form>
        </div>

        {/* Drag and Drop Zone */}
        <div
          className={`mb-8 p-8 border-2 border-dashed rounded-lg text-center ${
            isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
          }`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
        >
          <div className="text-gray-600">
            <p className="text-lg font-medium">Drag and drop Markdown files here</p>
            <p className="text-sm">Files will be uploaded to: {currentPath.join('/') || 'root'}</p>
          </div>
        </div>

        {/* Create Post Form */}
        <div className="bg-white rounded-lg shadow p-6 mb-8">
          <h2 className="text-2xl font-bold mb-4">Create New Post</h2>
          <form onSubmit={handleCreatePost} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700">Title</label>
              <input
                type="text"
                value={newPost.title}
                onChange={(e) => setNewPost({ ...newPost, title: e.target.value })}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">Date</label>
              <input
                type="date"
                value={newPost.date}
                onChange={(e) => setNewPost({ ...newPost, date: e.target.value })}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">Tags (comma-separated)</label>
              <input
                type="text"
                value={newPost.tags}
                onChange={(e) => setNewPost({ ...newPost, tags: e.target.value })}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                placeholder="tag1, tag2, tag3"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">Summary</label>
              <textarea
                value={newPost.summary}
                onChange={(e) => setNewPost({ ...newPost, summary: e.target.value })}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2"
                rows={2}
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">Content (Markdown)</label>
              <textarea
                value={newPost.content}
                onChange={(e) => setNewPost({ ...newPost, content: e.target.value })}
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 font-mono"
                rows={10}
                required
              />
            </div>
            <button
              type="submit"
              className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
            >
              Create Post
            </button>
          </form>
        </div>

        {/* Content List */}
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-2xl font-bold mb-4">Content</h2>
          <div className="space-y-4">
            {/* Folders */}
            {currentNodes
              .filter((node): node is Folder => node.type === 'folder')
              .map((folder) => (
                <div
                  key={folder.path}
                  className="border rounded-lg p-4 cursor-pointer hover:bg-gray-50"
                  onClick={() => setCurrentPath([...currentPath, folder.name])}
                >
                  <div className="flex items-center gap-2">
                    <span className="text-2xl">📁</span>
                    <span className="font-semibold text-lg">{folder.name}</span>
                  </div>
                </div>
              ))}

            {/* Posts */}
            {currentNodes
              .filter((node): node is Post => node.type === 'post')
              .map((post) => (
                <div key={post.slug} className="border rounded-lg p-4">
                  <h3 className="text-xl font-semibold">{post.title}</h3>
                  <p className="text-gray-600">{post.date}</p>
                  <p className="text-sm text-gray-500">{post.summary}</p>
                  <div className="mt-2 flex gap-2">
                    {(post.tags || []).map((tag) => (
                      <span key={tag} className="bg-gray-100 px-2 py-1 rounded text-sm">
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              ))}
          </div>
        </div>
      </div>
    </div>
  );
} 