'use client';

import { useState } from 'react';
import { Header, SearchBar, ServiceCard, BookmarkCard, CategorySection, Icon } from '@/components';
import { usePortal } from '@/lib/PortalContext';
import { categoryLabels, categoryOrder, bookmarkCategoryLabels, bookmarkCategoryOrder, ServiceCategory, BookmarkCategory } from '@/lib/services';

type TabId = 'services' | 'bookmarks' | 'ai' | 'whyrating' | 'settings';

const tabs: { id: TabId; label: string; icon: string }[] = [
  { id: 'whyrating', label: 'WhyRating', icon: 'star' },
  { id: 'services', label: 'Services', icon: 'server' },
  { id: 'ai', label: 'AI', icon: 'bot' },
  { id: 'bookmarks', label: 'Bookmarks', icon: 'external-link' },
  { id: 'settings', label: 'Settings', icon: 'settings' },
];

const aiTools = [
  { name: 'Claude', url: 'https://claude.ai', icon: 'bot', description: 'Anthropic AI assistant' },
  { name: 'ChatGPT', url: 'https://chat.openai.com', icon: 'message-square', description: 'OpenAI chat assistant' },
  { name: 'Perplexity', url: 'https://perplexity.ai', icon: 'search', description: 'AI-powered search' },
  { name: 'Phind', url: 'https://phind.com', icon: 'code', description: 'AI for developers' },
  { name: 'Cursor', url: 'https://cursor.com', icon: 'terminal', description: 'AI-first code editor' },
  { name: 'v0', url: 'https://v0.dev', icon: 'layout', description: 'Vercel AI UI generator' },
  { name: 'Replicate', url: 'https://replicate.com', icon: 'cpu', description: 'ML model hosting' },
  { name: 'Hugging Face', url: 'https://huggingface.co', icon: 'smile', description: 'ML models & datasets' },
  { name: 'Together AI', url: 'https://together.ai', icon: 'users', description: 'Open model inference' },
];

const whyratingLinks = [
  { name: 'WhyRating Hub', url: 'http://whyrating.nuc.lan', icon: 'star', description: 'WhyRating project hub and quick links' },
  { name: 'Brand Site', url: 'http://brand.nuc.lan', icon: 'palette', description: 'WhyRating brand guidelines and assets' },
  { name: 'Templates Site', url: 'http://templates.nuc.lan', icon: 'layout', description: 'WhyRating email and document templates' },
  { name: 'Outline Docs', url: 'http://192.168.1.3:3080', icon: 'file-text', description: 'Project documentation and notes' },
];

export default function Home() {
  const [activeTab, setActiveTab] = useState<TabId>('whyrating');
  const { filteredServices, filteredBookmarks, healthStatus, searchQuery, darkMode, setDarkMode, services } = usePortal();

  // Group services by category
  const servicesByCategory = categoryOrder.reduce((acc, category) => {
    const categoryServices = filteredServices.filter(s => s.category === category);
    if (categoryServices.length > 0) {
      acc[category] = categoryServices;
    }
    return acc;
  }, {} as Record<ServiceCategory, typeof filteredServices>);

  // Group bookmarks by category
  const bookmarksByCategory = bookmarkCategoryOrder.reduce((acc, category) => {
    const categoryBookmarks = filteredBookmarks.filter(b => b.category === category);
    if (categoryBookmarks.length > 0) {
      acc[category] = categoryBookmarks;
    }
    return acc;
  }, {} as Record<BookmarkCategory, typeof filteredBookmarks>);

  const hasServices = Object.keys(servicesByCategory).length > 0;
  const hasBookmarks = Object.keys(bookmarksByCategory).length > 0;
  const noResults = searchQuery && !hasServices && !hasBookmarks;

  // Count running services
  const runningCount = services.filter(s => healthStatus[s.name] === 'running').length;
  const totalServices = services.length;

  const renderTabContent = () => {
    switch (activeTab) {
      case 'services':
        return (
          <>
            {/* Search */}
            <div className="mb-8 max-w-xl">
              <SearchBar />
            </div>

            {/* Status summary */}
            <div className="mb-6 flex items-center gap-4 text-sm">
              <div className="flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-emerald-500" />
                <span className="text-slate-600 dark:text-stone-400">
                  {runningCount} of {totalServices} services running
                </span>
              </div>
            </div>

            {/* No results message */}
            {noResults && (
              <div className="text-center py-12">
                <p className="text-slate-500 dark:text-stone-500">
                  No services found for &quot;{searchQuery}&quot;
                </p>
              </div>
            )}

            {/* Services */}
            {hasServices && (
              <div>
                {Object.entries(servicesByCategory).map(([category, services]) => (
                  <CategorySection
                    key={category}
                    title={categoryLabels[category as ServiceCategory]}
                    count={services.length}
                    columns={3}
                  >
                    {services.map(service => (
                      <ServiceCard
                        key={service.name}
                        service={service}
                        status={healthStatus[service.name] || 'unknown'}
                      />
                    ))}
                  </CategorySection>
                ))}
              </div>
            )}
          </>
        );

      case 'bookmarks':
        return (
          <>
            {/* Search */}
            <div className="mb-8 max-w-xl">
              <SearchBar />
            </div>

            {/* No results message */}
            {searchQuery && !hasBookmarks && (
              <div className="text-center py-12">
                <p className="text-slate-500 dark:text-stone-500">
                  No bookmarks found for &quot;{searchQuery}&quot;
                </p>
              </div>
            )}

            {/* Bookmarks */}
            {hasBookmarks && (
              <div>
                {Object.entries(bookmarksByCategory).map(([category, bookmarks]) => (
                  <CategorySection
                    key={category}
                    title={bookmarkCategoryLabels[category as BookmarkCategory]}
                    count={bookmarks.length}
                    columns={4}
                  >
                    {bookmarks.map(bookmark => (
                      <BookmarkCard
                        key={bookmark.name}
                        bookmark={bookmark}
                      />
                    ))}
                  </CategorySection>
                ))}
              </div>
            )}
          </>
        );

      case 'ai':
        return (
          <div className="max-w-4xl">
            <div className="mb-6">
              <h2 className="text-xl font-semibold text-slate-900 dark:text-stone-100 mb-2">
                AI Tools & Platforms
              </h2>
              <p className="text-sm text-slate-500 dark:text-stone-500">
                Quick access to AI assistants and platforms
              </p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {aiTools.map(tool => (
                <a
                  key={tool.name}
                  href={tool.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-3 p-4 bg-white dark:bg-stone-900 rounded-xl border border-slate-100 dark:border-stone-700/50 shadow-sm hover:shadow-md hover:border-slate-200 dark:hover:border-stone-600/50 transition-all"
                >
                  <div className="w-10 h-10 flex items-center justify-center rounded-lg bg-slate-100 dark:bg-stone-800">
                    <Icon name={tool.icon} size={20} className="text-slate-600 dark:text-stone-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-medium text-slate-900 dark:text-stone-100">{tool.name}</h3>
                    <p className="text-xs text-slate-500 dark:text-stone-500 truncate">{tool.description}</p>
                  </div>
                </a>
              ))}
            </div>
          </div>
        );

      case 'whyrating':
        return (
          <div className="max-w-2xl">
            <div className="mb-6">
              <h2 className="text-xl font-semibold text-slate-900 dark:text-stone-100 mb-2">
                WhyRating.com
              </h2>
              <p className="text-sm text-slate-500 dark:text-stone-500">
                Project resources and documentation
              </p>
            </div>
            <div className="grid gap-4">
              {whyratingLinks.map(link => (
                <a
                  key={link.name}
                  href={link.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-4 p-4 bg-white dark:bg-stone-900 rounded-xl border border-slate-100 dark:border-stone-700/50 shadow-sm hover:shadow-md hover:border-slate-200 dark:hover:border-stone-600/50 transition-all"
                >
                  <div className="w-12 h-12 flex items-center justify-center rounded-lg bg-slate-100 dark:bg-stone-800">
                    <Icon name={link.icon} size={24} className="text-slate-600 dark:text-stone-400" />
                  </div>
                  <div className="flex-1">
                    <h3 className="font-medium text-slate-900 dark:text-stone-100">{link.name}</h3>
                    <p className="text-sm text-slate-500 dark:text-stone-500">{link.description}</p>
                  </div>
                  <Icon name="external-link" size={16} className="text-slate-400 dark:text-stone-600" />
                </a>
              ))}
            </div>
          </div>
        );

      case 'settings':
        return (
          <div className="max-w-2xl">
            <div className="bg-white dark:bg-stone-900 rounded-xl border border-slate-100 dark:border-stone-700/50 shadow-sm p-6">
              <h2 className="text-lg font-semibold text-slate-900 dark:text-stone-100 mb-6">
                Appearance
              </h2>

              {/* Dark Mode Toggle */}
              <div className="flex items-center justify-between py-4 border-b border-slate-100 dark:border-stone-800">
                <div>
                  <h3 className="font-medium text-slate-900 dark:text-stone-100">Dark Mode</h3>
                  <p className="text-sm text-slate-500 dark:text-stone-500">
                    Use dark theme for the portal
                  </p>
                </div>
                <button
                  onClick={() => setDarkMode(!darkMode)}
                  className={`relative w-12 h-6 rounded-full transition-colors ${
                    darkMode ? 'bg-emerald-500' : 'bg-slate-300 dark:bg-stone-600'
                  }`}
                >
                  <span
                    className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${
                      darkMode ? 'translate-x-6' : 'translate-x-0'
                    }`}
                  />
                </button>
              </div>

              <h2 className="text-lg font-semibold text-slate-900 dark:text-stone-100 mt-8 mb-6">
                About
              </h2>

              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-500 dark:text-stone-500">Version</span>
                  <span className="text-slate-900 dark:text-stone-100">1.0.0</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500 dark:text-stone-500">Server IP</span>
                  <span className="text-slate-900 dark:text-stone-100 font-mono">192.168.1.3</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500 dark:text-stone-500">Services</span>
                  <span className="text-slate-900 dark:text-stone-100">{totalServices}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500 dark:text-stone-500">Bookmarks</span>
                  <span className="text-slate-900 dark:text-stone-100">{filteredBookmarks.length}</span>
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-slate-100 dark:border-stone-800">
                <a
                  href="http://192.168.1.3:3030/nuc/nuc-portal"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 text-sm text-slate-500 dark:text-stone-500 hover:text-slate-700 dark:hover:text-stone-300"
                >
                  <Icon name="git-branch" size={16} />
                  View on Gitea
                </a>
              </div>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-stone-950">
      <Header activeTab={activeTab} onTabChange={(tab) => setActiveTab(tab as TabId)} tabs={tabs} />

      <main className="max-w-6xl mx-auto px-4 sm:px-6 py-8">
        {renderTabContent()}
      </main>

      {/* Footer */}
      <footer className="text-center py-8 text-sm text-slate-400 dark:text-stone-600">
        <span>NUC Portal</span>
        <span className="mx-2">•</span>
        <span>192.168.1.3</span>
      </footer>
    </div>
  );
}
