/**
 * Cluster Detail Page
 * Shows cluster information with tabs for Articles, Pages, Products, and Taxonomy
 * Route: /clusters/:id
 */

import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import PageMeta from '../../components/common/PageMeta';
import PageHeader from '../../components/common/PageHeader';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import Badge from '../../components/ui/badge/Badge';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchAPI, Cluster, Content } from '../../services/api';
import { 
  GridIcon, 
  FileIcon, 
  PageIcon, 
  TagIcon,
  ChevronLeftIcon,
  EyeIcon,
  PencilIcon
} from '../../icons';

type TabType = 'articles' | 'pages' | 'products' | 'taxonomy';

export default function ClusterDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToast();

  const [cluster, setCluster] = useState<Cluster | null>(null);
  const [content, setContent] = useState<Content[]>([]);
  const [loading, setLoading] = useState(true);
  const [contentLoading, setContentLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('articles');

  useEffect(() => {
    if (!id) {
      toast.error('Cluster ID is required');
      navigate('/planner/clusters');
      return;
    }

    const clusterId = parseInt(id, 10);
    if (isNaN(clusterId) || clusterId <= 0) {
      toast.error('Invalid cluster ID');
      navigate('/planner/clusters');
      return;
    }

    loadCluster(clusterId);
  }, [id, navigate, toast]);

  useEffect(() => {
    if (cluster) {
      loadContent(activeTab);
    }
  }, [cluster, activeTab]);

  const loadCluster = async (clusterId: number) => {
    try {
      setLoading(true);
      const data = await fetchAPI(`/v1/planner/clusters/${clusterId}/`);
      setCluster(data);
    } catch (error: any) {
      console.error('Error loading cluster:', error);
      toast.error(`Failed to load cluster: ${error.message || 'Unknown error'}`);
      navigate('/planner/clusters');
    } finally {
      setLoading(false);
    }
  };

  const loadContent = async (tab: TabType) => {
    if (!cluster) return;

    try {
      setContentLoading(true);
      const params = new URLSearchParams({
        cluster_id: cluster.id.toString(),
      });

      // Filter by content_type based on active tab
      switch (tab) {
        case 'articles':
          params.append('content_type', 'post');
          break;
        case 'pages':
          params.append('content_type', 'page');
          break;
        case 'products':
          params.append('content_type', 'product');
          break;
        case 'taxonomy':
          // Show categories and tags
          params.append('content_type', 'category');
          break;
      }

      const response = await fetchAPI(`/v1/writer/content/?${params.toString()}`);
      const contentList = Array.isArray(response?.results) 
        ? response.results 
        : Array.isArray(response) 
        ? response 
        : [];
      setContent(contentList);
    } catch (error: any) {
      console.error('Error loading content:', error);
      toast.error(`Failed to load content: ${error.message}`);
      setContent([]);
    } finally {
      setContentLoading(false);
    }
  };

  const handleTabChange = (tab: TabType) => {
    setActiveTab(tab);
  };

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Cluster Details" description="Loading cluster information" />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">Loading cluster...</div>
        </div>
      </div>
    );
  }

  if (!cluster) {
    return (
      <div className="p-6">
        <PageMeta title="Cluster Not Found" description="The requested cluster could not be found" />
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400 mb-4">Cluster not found</p>
          <Button onClick={() => navigate('/planner/clusters')} variant="solid">
            Back to Clusters
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6">
      <PageMeta 
        title={`${cluster.name} - Cluster Details - IGNY8`} 
        description={cluster.description || `View details for cluster: ${cluster.name}`}
      />

      {/* Back Button */}
      <div className="mb-4">
        <Button 
          variant="ghost" 
          size="sm" 
          onClick={() => navigate('/planner/clusters')}
          className="flex items-center gap-2"
        >
          <ChevronLeftIcon className="w-4 h-4" />
          Back to Clusters
        </Button>
      </div>

      <PageHeader 
        title={cluster.name}
        badge={{ icon: <GridIcon />, color: 'blue' }}
        hideSiteSector
      />

      {/* Cluster Summary */}
      <Card className="p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Keywords</div>
            <div className="text-2xl font-semibold text-gray-900 dark:text-white">
              {cluster.keywords_count}
            </div>
          </div>
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Total Volume</div>
            <div className="text-2xl font-semibold text-gray-900 dark:text-white">
              {cluster.volume.toLocaleString()}
            </div>
          </div>
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Avg Difficulty</div>
            <div className="text-2xl font-semibold text-gray-900 dark:text-white">
              {cluster.difficulty}
            </div>
          </div>
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Ideas</div>
            <div className="text-2xl font-semibold text-gray-900 dark:text-white">
              {cluster.ideas_count}
            </div>
          </div>
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Content</div>
            <div className="text-2xl font-semibold text-gray-900 dark:text-white">
              {cluster.content_count}
            </div>
          </div>
        </div>

        {cluster.description && (
          <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Description</div>
            <p className="text-gray-700 dark:text-gray-300">{cluster.description}</p>
          </div>
        )}

        <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex items-center gap-4">
          {cluster.sector_name && (
            <Badge variant="light" color="info">
              {cluster.sector_name}
            </Badge>
          )}
          <Badge 
            variant={cluster.status === 'active' ? 'soft' : 'light'}
            color={cluster.status === 'active' ? 'success' : 'neutral'}
          >
            {cluster.status}
          </Badge>
          <span className="text-xs text-gray-500 dark:text-gray-400">
            Created {new Date(cluster.created_at).toLocaleDateString()}
          </span>
        </div>
      </Card>

      {/* Tabs */}
      <div className="mb-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex gap-4">
          <button
            type="button"
            onClick={() => handleTabChange('articles')}
            className={`px-4 py-2 font-medium border-b-2 transition-colors ${
              activeTab === 'articles'
                ? 'border-brand-500 text-brand-600 dark:text-brand-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            <FileIcon className="w-4 h-4 inline mr-2" />
            Articles
          </button>
          <button
            type="button"
            onClick={() => handleTabChange('pages')}
            className={`px-4 py-2 font-medium border-b-2 transition-colors ${
              activeTab === 'pages'
                ? 'border-brand-500 text-brand-600 dark:text-brand-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            <PageIcon className="w-4 h-4 inline mr-2" />
            Pages
          </button>
          <button
            type="button"
            onClick={() => handleTabChange('products')}
            className={`px-4 py-2 font-medium border-b-2 transition-colors ${
              activeTab === 'products'
                ? 'border-brand-500 text-brand-600 dark:text-brand-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            <GridIcon className="w-4 h-4 inline mr-2" />
            Products
          </button>
          <button
            type="button"
            onClick={() => handleTabChange('taxonomy')}
            className={`px-4 py-2 font-medium border-b-2 transition-colors ${
              activeTab === 'taxonomy'
                ? 'border-brand-500 text-brand-600 dark:text-brand-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            <TagIcon className="w-4 h-4 inline mr-2" />
            Taxonomy
          </button>
        </div>
      </div>

      {/* Content List */}
      {contentLoading ? (
        <Card className="p-12 text-center">
          <div className="text-gray-500">Loading content...</div>
        </Card>
      ) : content.length === 0 ? (
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            No {activeTab} found for this cluster
          </p>
          <Button onClick={() => navigate('/writer/tasks')} variant="solid">
            Create Content
          </Button>
        </Card>
      ) : (
        <Card className="p-6">
          <div className="space-y-3">
            {content.map((item) => (
              <div
                key={item.id}
                className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
              >
                <div className="flex-1">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-1">
                    {item.title || `Content #${item.id}`}
                  </h3>
                  <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-500">
                    <Badge 
                      variant={item.status === 'published' ? 'soft' : 'light'}
                      color={item.status === 'published' ? 'success' : 'neutral'}
                      size="sm"
                    >
                      {item.status}
                    </Badge>
                    {item.content_type && (
                      <Badge variant="light" color="info" size="sm">
                        {item.content_type}
                      </Badge>
                    )}
                    {item.content_structure && (
                      <Badge variant="light" color="info" size="sm">
                        {item.content_structure}
                      </Badge>
                    )}
                    <span>{item.source}</span>
                    {item.external_url && (
                      <a 
                        href={item.external_url} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="text-brand-600 dark:text-brand-400 hover:underline"
                      >
                        View Live
                      </a>
                    )}
                    <span>
                      {new Date(item.created_at).toLocaleDateString()}
                    </span>
                  </div>
                </div>
                <div className="flex gap-2 ml-4">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => navigate(`/writer/content/${item.id}`)}
                  >
                    <EyeIcon className="w-4 h-4" />
                  </Button>
                  {item.external_url && (
                    <Button
                      variant="solid"
                      size="sm"
                      onClick={() => window.open(item.external_url!, '_blank')}
                    >
                      <PencilIcon className="w-4 h-4" />
                    </Button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}
