/**
 * Site Content Manager (Advanced)
 * Phase 7: Advanced Site Management
 * Features: Search, filters, content listing for a site
 */
import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate } 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 { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchAPI } from '../../services/api';
import { Search } from 'lucide-react';
import { 
  PencilIcon, 
  EyeIcon, 
  TrashBinIcon, 
  PlusIcon,
  FileIcon,
  GridIcon
} from '../../icons';

interface ContentItem {
  id: number;
  title: string;
  status: string;
  updated_at: string;
  source: string;
  content_type?: string;
  content_structure?: string;
  cluster_name?: string;
  external_url?: string;
  created_at: string;
}

export default function SiteContentManager() {
  const { id: siteId } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToast();
  const [content, setContent] = useState<ContentItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [sourceFilter, setSourceFilter] = useState('');
  const [sortBy, setSortBy] = useState<'created_at' | 'updated_at' | 'title'>('created_at');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const pageSize = 20;

  useEffect(() => {
    if (siteId) {
      loadContent();
    }
  }, [siteId, currentPage, statusFilter, sourceFilter, searchTerm, sortBy, sortDirection]);

  const loadContent = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        site_id: siteId!,
        page: currentPage.toString(),
        page_size: pageSize.toString(),
        ordering: sortDirection === 'desc' ? `-${sortBy}` : sortBy,
      });

      if (searchTerm) {
        params.append('search', searchTerm);
      }
      if (statusFilter) {
        params.append('status', statusFilter);
      }
      if (sourceFilter) {
        params.append('source', sourceFilter);
      }

      const data = await fetchAPI(`/v1/writer/content/?${params.toString()}`);
      const contentList = Array.isArray(data?.results) ? data.results : Array.isArray(data) ? data : [];
      setContent(contentList);
      setTotalCount(data?.count || contentList.length);
      setTotalPages(data?.total_pages || Math.ceil((data?.count || contentList.length) / pageSize));
    } catch (error: any) {
      toast.error(`Failed to load content: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this content?')) return;
    
    try {
      await fetchAPI(`/v1/writer/content/${id}/`, {
        method: 'DELETE',
      });
      toast.success('Content deleted successfully');
      loadContent();
    } catch (error: any) {
      toast.error(`Failed to delete content: ${error.message}`);
    }
  };

  const filteredContent = useMemo(() => {
    return content;
  }, [content]);

  const STATUS_OPTIONS = [
    { value: '', label: 'All Statuses' },
    { value: 'draft', label: 'Draft' },
    { value: 'published', label: 'Published' },
  ];

  const SOURCE_OPTIONS = [
    { value: '', label: 'All Sources' },
    { value: 'igny8', label: 'IGNY8 Generated' },
    { value: 'wordpress', label: 'WordPress' },
    { value: 'shopify', label: 'Shopify' },
    { value: 'custom', label: 'Custom API' },
  ];

  return (
    <div className="p-6">
      <PageMeta title="Site Content Manager - IGNY8" />
      
      <PageHeader 
        title={`Content Manager (${totalCount} items)`}
        badge={{ icon: <FileIcon />, color: 'blue' }}
        hideSiteSector
      />
      <div className="mb-6 flex justify-end">
        <Button onClick={() => navigate(`/sites/${siteId}/posts/new`)} variant="primary" startIcon={<PlusIcon className="w-4 h-4" />}>
          New Post
        </Button>
      </div>

      {/* Filters */}
      <Card className="p-4 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search content..."
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg dark:bg-gray-800 dark:text-white"
            />
          </div>

          <select
            value={statusFilter}
            onChange={(e) => {
              setStatusFilter(e.target.value);
              setCurrentPage(1);
            }}
            className="px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-white"
          >
            {STATUS_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>

          <select
            value={sourceFilter}
            onChange={(e) => {
              setSourceFilter(e.target.value);
              setCurrentPage(1);
            }}
            className="px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-white"
          >
            {SOURCE_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>

          <select
            value={`${sortBy}-${sortDirection}`}
            onChange={(e) => {
              const [field, direction] = e.target.value.split('-');
              setSortBy(field as typeof sortBy);
              setSortDirection(direction as 'asc' | 'desc');
            }}
            className="px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-white"
          >
            <option value="created_at-desc">Newest First</option>
            <option value="created_at-asc">Oldest First</option>
            <option value="updated_at-desc">Recently Updated</option>
            <option value="title-asc">Title A-Z</option>
            <option value="title-desc">Title Z-A</option>
          </select>
        </div>
      </Card>

      {/* Content List */}
      {loading ? (
        <Card className="p-12 text-center">
          <div className="text-gray-500">Loading content...</div>
        </Card>
      ) : filteredContent.length === 0 ? (
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            No content found
          </p>
          <Button onClick={() => navigate(`/sites/${siteId}/posts/new`)} variant="primary">
            Create Your First Post
          </Button>
        </Card>
      ) : (
        <>
          <Card className="p-6">
            <div className="space-y-3">
              {filteredContent.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">
                      <span className={`px-2 py-1 rounded ${item.status === 'published' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'}`}>
                        {item.status}
                      </span>
                      {item.content_type && <span>{item.content_type}</span>}
                      {item.content_structure && <span>{item.content_structure}</span>}
                      <span>{item.source}</span>
                      {item.cluster_name && <span>Cluster: {item.cluster_name}</span>}
                      <span>
                        {new Date(item.updated_at).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                  <div className="flex gap-2 ml-4">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => navigate(`/sites/${siteId}/posts/${item.id}`)}
                      title="View"
                    >
                      <EyeIcon className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="primary"
                      size="sm"
                      onClick={() => navigate(`/sites/${siteId}/posts/${item.id}/edit`)}
                      title="Edit"
                    >
                      <PencilIcon className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(item.id)}
                      title="Delete"
                    >
                      <TrashBinIcon className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="mt-6 flex justify-center items-center gap-2">
              <Button
                variant="outline"
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
              >
                Previous
              </Button>
              <span className="text-sm text-gray-600 dark:text-gray-400">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
              >
                Next
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

