'use client';

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

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

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

type Node = Post | Folder;

// Helper to get folder details
async function getFolderDetails(path: string): Promise<{ created: string, items: number, size: number, error?: string }> {
  try {
    const res = await fetch(`/api/admin/folders/details?path=${encodeURIComponent(path)}`);
    if (!res.ok) throw new Error('API error');
    return await res.json();
  } catch (e) {
    console.error('Error fetching folder details:', e);
    return { created: '', items: 0, size: 0, error: 'Error loading details' };
  }
}

// Helper to get post size and creation date
async function getPostSize(slug: string): Promise<{ size: number | null, created: string | null }> {
  try {
    const res = await fetch(`/api/admin/posts/size?slug=${encodeURIComponent(slug)}`);
    if (!res.ok) throw new Error('API error');
    const data = await res.json();
    return { size: data.size, created: data.created };
  } catch (e) {
    console.error('Error fetching post size:', e);
    return { size: null, created: null };
  }
}

export default function ManagePage() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [nodes, setNodes] = useState<Node[]>([]);
  const [currentPath, setCurrentPath] = useState<string[]>([]);
  const [deleteConfirm, setDeleteConfirm] = useState<{ show: boolean; item: Node | null }>({
    show: false,
    item: null,
  });
  const [draggedPost, setDraggedPost] = useState<Node | null>(null);
  const [dragOverFolder, setDragOverFolder] = useState<string | null>(null);
  const [folderDetails, setFolderDetails] = useState<Record<string, { created: string, items: number, size: number, error?: string }>>({});
  const [deleteAllConfirm, setDeleteAllConfirm] = useState<{ show: boolean, folder: Folder | null }>({ show: false, folder: null });
  const [postSizes, setPostSizes] = useState<Record<string, { size: number | null, created: string | null }>>({});
  const router = useRouter();

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

  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 handleLogout = () => {
    setIsAuthenticated(false);
    localStorage.removeItem('adminAuth');
    router.push('/');
  };

  // 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: '/', path: [] },
    ...currentPath.map((name, idx) => ({
      name,
      path: currentPath.slice(0, idx + 1),
    })),
  ];

  const handleDelete = async (node: Node) => {
    setDeleteConfirm({ show: true, item: node });
  };

  const confirmDelete = async () => {
    if (!deleteConfirm.item) return;

    try {
      let itemPath = currentPath.join('/');
      let itemName = deleteConfirm.item.type === 'folder' ? deleteConfirm.item.name : deleteConfirm.item.slug;
      // For posts, if slug contains a path (e.g. subfolder/post), split it
      if (deleteConfirm.item.type === 'post' && itemName.includes('/')) {
        const parts = itemName.split('/');
        itemName = parts[parts.length - 1];
        itemPath = parts.slice(0, -1).join('/');
      }
      
      console.log('Deleting item:', {
        path: itemPath,
        name: itemName,
        type: deleteConfirm.item.type
      });

      const response = await fetch('/api/admin/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          path: itemPath,
          name: itemName,
          type: deleteConfirm.item.type,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to delete item');
      }

      console.log('Delete successful:', data);
      await loadContent();
      setDeleteConfirm({ show: false, item: null });
    } catch (error) {
      console.error('Error deleting item:', error);
      alert(error instanceof Error ? error.message : 'Error deleting item');
    }
  };

  // Move post API call
  const movePost = async (post: Post, targetFolder: string[]) => {
    try {
      const response = await fetch('/api/admin/posts/move', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          slug: post.slug,
          from: currentPath.join('/'),
          to: targetFolder.join('/'),
        }),
      });
      if (!response.ok) {
        const data = await response.json();
        alert(data.error || 'Error moving post');
      } else {
        loadContent();
      }
    } catch (error) {
      alert('Error moving post');
    }
  };

  // Fetch folder details only when navigating to a new directory
  useEffect(() => {
    async function fetchDetails() {
      const details: Record<string, { created: string, items: number, size: number, error?: string }> = {};
      const folders = currentNodes.filter(n => n.type === 'folder');
      
      // Only fetch for folders that don't already have details
      const foldersToFetch = folders.filter((folder: any) => !folderDetails[folder.path]);
      
      if (foldersToFetch.length > 0) {
        await Promise.all(foldersToFetch.map(async (folder: any) => {
          details[folder.path] = await getFolderDetails(folder.path);
        }));
        setFolderDetails(prev => ({ ...prev, ...details }));
      }
    }
    fetchDetails();
  }, [currentPath]); // Only trigger when path changes, not on every currentNodes change

  // Fetch post sizes only when navigating to a new directory
  useEffect(() => {
    async function fetchSizes() {
      const sizes: Record<string, { size: number | null, created: string | null }> = {};
      const posts = currentNodes.filter(n => n.type === 'post');
      
      // Only fetch for posts that don't already have sizes
      const postsToFetch = posts.filter((post: any) => postSizes[post.slug] === undefined);
      
      if (postsToFetch.length > 0) {
        await Promise.all(postsToFetch.map(async (post: any) => {
          sizes[post.slug] = await getPostSize(post.slug);
        }));
        setPostSizes(prev => ({ ...prev, ...sizes }));
      }
    }
    fetchSizes();
  }, [currentPath]); // Only trigger when path changes, not on every currentNodes change

  if (!isAuthenticated) {
    return null; // Will redirect in useEffect
  }

  return (
    <div className="min-h-screen bg-gray-100 p-3 sm:p-8">
      <div className="max-w-6xl mx-auto">
        {/* Mobile-friendly header */}
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-6 sm:mb-8 space-y-4 sm:space-y-0">
          <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4">
            <h1 className="text-2xl sm:text-3xl font-bold">Inhaltsverwaltung</h1>
            <Link
              href="/admin"
              className="px-4 py-3 sm:py-2 bg-gray-200 rounded hover:bg-gray-300 transition-colors text-base font-medium"
            >
              Zum Admin-Panel
            </Link>
          </div>
          <div className="flex gap-2">
            <button
              onClick={loadContent}
              className="px-4 py-3 sm:py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors text-base font-medium"
              title="Inhalt aktualisieren"
            >
              <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
            </button>
            <button
              onClick={handleLogout}
              className="px-4 py-3 sm:py-2 bg-red-600 text-white rounded hover:bg-red-700 text-base font-medium"
            >
              Abmelden
            </button>
          </div>
        </div>

        {/* Mobile-friendly breadcrumbs */}
        <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 mb-4 sm:mb-6">
          {currentPath.length > 0 && (
            <button
              onClick={() => setCurrentPath(currentPath.slice(0, -1))}
              className="flex items-center gap-2 px-3 sm:px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition-colors text-sm sm:text-base"
              title="Einen Ordner zurück"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-4 w-4 sm:h-5 sm:w-5"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fillRule="evenodd"
                  d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z"
                  clipRule="evenodd"
                />
              </svg>
              Zurück
            </button>
          )}
          <div className="flex flex-wrap items-center gap-1 sm:gap-2">
            {breadcrumbs.map((crumb, index) => (
              <div key={crumb.path.join('/')} className="flex items-center">
                {index > 0 && <span className="mx-1 sm:mx-2 text-gray-500">/</span>}
                <button
                  onClick={() => setCurrentPath(crumb.path)}
                  className={`px-2 py-1 rounded text-sm sm:text-base ${
                    index === breadcrumbs.length - 1
                      ? 'bg-blue-100 text-blue-800'
                      : 'hover:bg-gray-200'
                  }`}
                >
                  {crumb.name}
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Mobile-friendly content grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
          {currentNodes.map((node) => (
            node.type === 'folder' ? (
              <div
                key={node.name}
                className={`bg-white p-3 sm:p-4 rounded-lg shadow hover:shadow-md transition-shadow cursor-pointer ${dragOverFolder === node.name ? 'ring-2 ring-blue-400' : ''}`}
                onClick={() => setCurrentPath([...currentPath, node.name])}
                onDoubleClick={() => setDeleteAllConfirm({ show: true, folder: node })}
                onDragOver={e => { e.preventDefault(); setDragOverFolder(node.name); }}
                onDragLeave={() => setDragOverFolder(null)}
                onDrop={e => {
                  e.preventDefault();
                  setDragOverFolder(null);
                  if (draggedPost && draggedPost.type === 'post') {
                    movePost(draggedPost as Post, [...currentPath, node.name]);
                  }
                }}
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-bold text-sm sm:text-base truncate">{node.name}</h3>
                    <div className="text-xs text-gray-500 mt-1">
                      {folderDetails[node.path] ? (
                        folderDetails[node.path].error ? (
                          <span className="text-red-500">{folderDetails[node.path].error}</span>
                        ) : (
                          <>
                            <div>Created: {folderDetails[node.path].created || <span className="italic">Loading...</span>}</div>
                            <div>Items: {folderDetails[node.path].items}</div>
                            <div>Size: {folderDetails[node.path].size > 1024 ? `${(folderDetails[node.path].size/1024).toFixed(1)} KB` : `${folderDetails[node.path].size} B`}</div>
                          </>
                        )
                      ) : (
                        <span className="italic">Loading...</span>
                      )}
                    </div>
                  </div>
                  <button
                    onClick={e => { e.stopPropagation(); handleDelete(node); }}
                    className="text-red-600 hover:text-red-800 p-2 ml-2 flex-shrink-0"
                    title="Delete"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-4 w-4 sm:h-5 sm:w-5"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
                        clipRule="evenodd"
                      />
                    </svg>
                  </button>
                </div>
              </div>
            ) : (
              <div
                key={node.slug}
                className="bg-white p-3 sm:p-4 rounded-lg shadow hover:shadow-md transition-shadow"
                draggable
                onDragStart={() => setDraggedPost(node)}
                onDragEnd={() => setDraggedPost(null)}
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-bold text-sm sm:text-base truncate">{node.title}</h3>
                    <div className="text-xs text-gray-500 mt-1">
                      {postSizes[node.slug] === undefined
                        ? <span className="italic">Loading...</span>
                        : postSizes[node.slug].size === null
                          ? <span className="italic">Loading size...</span>
                          : <>
                              {postSizes[node.slug].created && (
                                <div>Created: {new Date(postSizes[node.slug].created!).toLocaleString()}</div>
                              )}
                              <span>Size: {postSizes[node.slug].size! > 1024 ? `${(postSizes[node.slug].size!/1024).toFixed(1)} KB` : `${postSizes[node.slug].size} B`}</span>
                            </>
                      }
                    </div>
                  </div>
                  <button
                    onClick={() => handleDelete(node)}
                    className="text-red-600 hover:text-red-800 p-2 ml-2 flex-shrink-0"
                    title="Delete"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-4 w-4 sm:h-5 sm:w-5"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
                        clipRule="evenodd"
                      />
                    </svg>
                  </button>
                </div>
              </div>
            )
          ))}
        </div>

        {/* Mobile-friendly delete confirmation modal */}
        {deleteConfirm.show && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white p-4 sm:p-6 rounded-lg shadow-xl max-w-sm w-full">
              <h3 className="text-lg font-bold mb-4">Confirm Delete</h3>
              <p className="mb-4 text-sm sm:text-base">
                Sind Sie sicher, dass Sie {deleteConfirm.item?.type === 'folder' ? 'Ordner' : 'Beitrag'} "{deleteConfirm.item?.type === 'folder' ? deleteConfirm.item.name : deleteConfirm.item?.title}" löschen möchten?
              </p>
              <div className="flex flex-col sm:flex-row justify-end gap-3 sm:gap-4">
                <button
                  onClick={() => setDeleteConfirm({ show: false, item: null })}
                  className="px-4 py-3 sm:py-2 bg-gray-200 rounded hover:bg-gray-300 text-base font-medium"
                >
                  Abbrechen
                </button>
                <button
                  onClick={confirmDelete}
                  className="px-4 py-3 sm:py-2 bg-red-600 text-white rounded hover:bg-red-700 text-base font-medium"
                >
                  Löschen
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Mobile-friendly delete full folder modal */}
        {deleteAllConfirm.show && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white p-4 sm:p-6 rounded-lg shadow-xl max-w-sm w-full">
              <h3 className="text-lg font-bold mb-4">Lösche Ordner</h3>
              <p className="mb-4 text-sm sm:text-base">
                Sind Sie sicher, dass Sie <b>den gesamten Ordner und alle Inhalte löschen</b> möchten?
                <br />
                <span className="text-red-600">This cannot be undone!</span>
              </p>
              <div className="flex flex-col sm:flex-row justify-end gap-3 sm:gap-4">
                <button
                  onClick={() => setDeleteAllConfirm({ show: false, folder: null })}
                  className="px-4 py-3 sm:py-2 bg-gray-200 rounded hover:bg-gray-300 text-base font-medium"
                >
                  Abbrechen
                </button>
                <button
                  onClick={async () => {
                    if (!deleteAllConfirm.folder) return;
                    // Call delete API with recursive flag
                    await fetch('/api/admin/delete', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({
                        path: deleteAllConfirm.folder.path,
                        name: deleteAllConfirm.folder.name,
                        type: 'folder',
                        recursive: true
                      })
                    });
                    setDeleteAllConfirm({ show: false, folder: null });
                    loadContent();
                  }}
                  className="px-4 py-3 sm:py-2 bg-red-600 text-white rounded hover:bg-red-700 text-base font-medium"
                >
                  Löschen
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
} 