/**
 * Site Management Dashboard
 * Phase 6: Site Integration & Multi-Destination Publishing
 */
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { PlusIcon, EditIcon, SettingsIcon, EyeIcon, TrashIcon, PlugIcon } from 'lucide-react';
import PageMeta from '../../components/common/PageMeta';
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 SiteTypeBadge from '../../components/sites/SiteTypeBadge';
import Badge from '../../components/ui/badge/Badge';

interface Site {
  id: number;
  name: string;
  slug: string;
  site_type: string;
  hosting_type: string;
  status: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  page_count?: number;
  integration_count?: number;
  has_wordpress_integration?: boolean;
}

export default function SiteManagement() {
  const navigate = useNavigate();
  const toast = useToast();
  const [sites, setSites] = useState<Site[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadSites();
  }, []);

  const loadSites = async () => {
    try {
      setLoading(true);
      const data = await fetchAPI('/v1/auth/sites/');
      if (data && Array.isArray(data)) {
        // Check for WordPress integrations
        const sitesWithIntegrations = await Promise.all(
          data.map(async (site: Site) => {
            if (site.hosting_type === 'wordpress') {
              try {
                const integrations = await fetchAPI(`/v1/integration/integrations/?site=${site.id}&platform=wordpress`);
                return {
                  ...site,
                  has_wordpress_integration: integrations?.results?.length > 0 || integrations?.length > 0,
                };
              } catch {
                return { ...site, has_wordpress_integration: false };
              }
            }
            return site;
          })
        );
        setSites(sitesWithIntegrations);
      }
    } catch (error: any) {
      toast.error(`Failed to load sites: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleIntegration = (siteId: number) => {
    navigate(`/sites/${siteId}/settings?tab=integrations`);
  };

  const handleCreateSite = () => {
    navigate('/sites/builder');
  };

  const handleEdit = (siteId: number) => {
    navigate(`/sites/${siteId}/edit`);
  };

  const handleSettings = (siteId: number) => {
    navigate(`/sites/${siteId}/settings`);
  };

  const handleView = (siteId: number) => {
    navigate(`/sites/${siteId}`);
  };

  const handleDelete = async (siteId: number) => {
    if (!confirm('Are you sure you want to delete this site?')) return;

    try {
      await fetchAPI(`/v1/auth/sites/${siteId}/`, {
        method: 'DELETE',
      });
      toast.success('Site deleted successfully');
      loadSites();
    } catch (error: any) {
      toast.error(`Failed to delete site: ${error.message}`);
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Site Management" />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">Loading sites...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <PageMeta title="Site Management - IGNY8" />
      
      <div className="mb-6 flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            Site Management
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Manage your sites, pages, and content
          </p>
        </div>
        <Button onClick={handleCreateSite} variant="primary" startIcon={<PlusIcon className="w-4 h-4" />}>
          Create New Site
        </Button>
      </div>

      {sites.length === 0 ? (
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            No sites created yet
          </p>
          <Button onClick={handleCreateSite} variant="primary">
            Create Your First Site
          </Button>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {sites.map((site) => (
            <Card key={site.id} className="p-4 hover:shadow-lg transition-shadow">
              <div className="space-y-3">
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                      {site.name}
                    </h3>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      {site.slug}
                    </p>
                  </div>
                  <span
                    className={`px-2 py-1 text-xs rounded ${
                      site.is_active
                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                        : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
                    }`}
                  >
                    {site.is_active ? 'Active' : 'Inactive'}
                  </span>
                </div>

                <div className="flex flex-wrap gap-2 items-center">
                  <SiteTypeBadge hostingType={site.hosting_type} />
                  <Badge variant="soft" color="neutral" size="xs">
                    {site.site_type}
                  </Badge>
                </div>

                {/* WordPress Integration Button */}
                {site.hosting_type === 'wordpress' && (
                  <div className="pt-2">
                    <Button
                      variant={site.has_wordpress_integration ? "outline" : "primary"}
                      size="sm"
                      onClick={() => handleIntegration(site.id)}
                      className="w-full"
                      startIcon={<PlugIcon className="w-4 h-4" />}
                    >
                      {site.has_wordpress_integration ? 'Manage Integration' : 'Connect WordPress'}
                    </Button>
                  </div>
                )}

                <div className="flex items-center justify-between pt-3 border-t border-gray-200 dark:border-gray-700">
                  <div className="text-xs text-gray-600 dark:text-gray-400">
                    {site.page_count || 0} pages
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleView(site.id)}
                      title="View"
                    >
                      <EyeIcon className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(site.id)}
                      title="Edit"
                    >
                      <EditIcon className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleSettings(site.id)}
                      title="Settings"
                    >
                      <SettingsIcon className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(site.id)}
                      title="Delete"
                    >
                      <TrashIcon className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

