/**
 * Site Dashboard (Advanced)
 * Phase 7: UI Components & Prompt Management
 * Site overview with statistics and analytics
 */
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import PageMeta from '../../components/common/PageMeta';
import PageHeader from '../../components/common/PageHeader';
import ComponentCard from '../../components/common/ComponentCard';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import EnhancedMetricCard from '../../components/dashboard/EnhancedMetricCard';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchAPI } from '../../services/api';
// import { fetchSiteBlueprints } from '../../services/api';
import SiteProgressWidget from '../../components/sites/SiteProgressWidget';
import { 
  EyeIcon, 
  FileIcon, 
  PlugInIcon, 
  ArrowUpIcon,
  CalendarIcon,
  GridIcon,
  BoltIcon,
  PageIcon,
  ArrowRightIcon
} from '../../icons';

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;
  domain?: string;
}

interface SiteStats {
  total_pages: number;
  published_pages: number;
  draft_pages: number;
  total_content: number;
  published_content: number;
  integrations_count: number;
  deployments_count: number;
  last_deployment?: string;
  views_count?: number;
  visitors_count?: number;
}

export default function SiteDashboard() {
  const { id: siteId } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToast();
  const [site, setSite] = useState<Site | null>(null);
  const [stats, setStats] = useState<SiteStats | null>(null);
  const [blueprints, setBlueprints] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (siteId) {
      loadSiteData();
    }
  }, [siteId]);

  const loadSiteData = async () => {
    try {
      setLoading(true);
      const [siteData, statsData] = await Promise.all([
        fetchAPI(`/v1/auth/sites/${siteId}/`),
        fetchSiteStats(),
        // fetchSiteBlueprints({ site_id: Number(siteId) }),
      ]);
      
      if (siteData) {
        setSite(siteData);
      }
      
      if (statsData) {
        setStats(statsData);
      }

      if (blueprintsData && blueprintsData.results) {
        setBlueprints(blueprintsData.results);
      }
    } catch (error: any) {
      toast.error(`Failed to load site data: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const fetchSiteStats = async (): Promise<SiteStats | null> => {
    try {
      // TODO: Create backend endpoint for site stats
      // For now, return mock data structure
      return {
        total_pages: 0,
        published_pages: 0,
        draft_pages: 0,
        total_content: 0,
        published_content: 0,
        integrations_count: 0,
        deployments_count: 0,
      };
    } catch (error) {
      console.error('Error fetching site stats:', error);
      return null;
    }
  };

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

  if (!site) {
    return (
      <div className="p-6">
        <PageMeta title="Site Not Found" />
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400 mb-4">Site not found</p>
          <Button onClick={() => navigate('/sites')} variant="outline">
            Back to Sites
          </Button>
        </Card>
      </div>
    );
  }

  const statCards = [
    {
      title: 'Total Pages',
      value: stats?.total_pages || 0,
      icon: <FileIcon />,
      accentColor: 'blue' as const,
      href: `/sites/${siteId}/pages`,
    },
    {
      title: 'Published Pages',
      value: stats?.published_pages || 0,
      icon: <GridIcon />,
      accentColor: 'success' as const,
      href: `/sites/${siteId}/pages?status=published`,
    },
    {
      title: 'Draft Pages',
      value: stats?.draft_pages || 0,
      icon: <FileIcon />,
      accentColor: 'orange' as const,
      href: `/sites/${siteId}/pages?status=draft`,
    },
    {
      title: 'Integrations',
      value: stats?.integrations_count || 0,
      icon: <PlugInIcon />,
      accentColor: 'purple' as const,
      href: `/sites/${siteId}/settings?tab=integrations`,
    },
    {
      title: 'Deployments',
      value: stats?.deployments_count || 0,
      icon: <ArrowUpIcon />,
      accentColor: 'blue' as const,
      href: `/sites/${siteId}/preview`,
    },
    {
      title: 'Total Content',
      value: stats?.total_content || 0,
      icon: <FileIcon />,
      accentColor: 'purple' as const,
      href: `/sites/${siteId}/content`,
    },
  ];

  return (
    <div className="p-6">
      <PageMeta title={`${site.name} - Dashboard`} />
      <PageHeader 
        title={site.name}
        badge={{ icon: <GridIcon />, color: 'blue' }}
      />
      
      {/* Site Info */}
      <div className="mb-6">
        <p className="text-sm text-gray-600 dark:text-gray-400">
          {site.slug} • {site.site_type} • {site.hosting_type}
        </p>
        {site.domain && (
          <p className="text-sm text-gray-500 dark:text-gray-500 mt-1">
            {site.domain}
          </p>
        )}
        <div className="flex gap-2 mt-4">
          <Button
            variant="primary"
            onClick={() => navigate(`/sites/${siteId}/settings`)}
          >
            Settings
          </Button>
        </div>
      </div>

      {/* Stage 3: Site Progress Widget */}
      {blueprints.length > 0 && (
        <div className="mb-6">
          {blueprints.map((blueprint) => (
            <SiteProgressWidget
              key={blueprint.id}
              blueprintId={blueprint.id}
              siteId={Number(siteId)}
            />
          ))}
        </div>
      )}

      {/* Stats Grid - Using EnhancedMetricCard */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        {statCards.map((stat, index) => (
          <EnhancedMetricCard
            key={index}
            title={stat.title}
            value={stat.value}
            icon={stat.icon}
            accentColor={stat.accentColor}
            href={stat.href}
          />
        ))}
      </div>


      {/* Quick Actions */}
      <ComponentCard title="Quick Actions" desc="Common site management tasks">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <button
            onClick={() => navigate(`/sites/${siteId}/pages`)}
            className="flex items-center gap-4 p-6 rounded-xl border-2 border-slate-200 bg-white hover:border-[var(--color-primary)] hover:shadow-lg transition-all group"
          >
            <div className="size-12 rounded-xl bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] flex items-center justify-center text-white shadow-lg">
              <PageIcon className="h-6 w-6" />
            </div>
            <div className="flex-1 text-left">
              <h4 className="font-semibold text-slate-900 mb-1">Manage Pages</h4>
              <p className="text-sm text-slate-600">View and edit pages</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-slate-400 group-hover:text-[var(--color-primary)] transition" />
          </button>

          <button
            onClick={() => navigate(`/sites/${siteId}/content`)}
            className="flex items-center gap-4 p-6 rounded-xl border-2 border-slate-200 bg-white hover:border-[var(--color-success)] hover:shadow-lg transition-all group"
          >
            <div className="size-12 rounded-xl bg-gradient-to-br from-[var(--color-success)] to-[var(--color-success-dark)] flex items-center justify-center text-white shadow-lg">
              <FileIcon className="h-6 w-6" />
            </div>
            <div className="flex-1 text-left">
              <h4 className="font-semibold text-slate-900 mb-1">Manage Content</h4>
              <p className="text-sm text-slate-600">View and edit content</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-slate-400 group-hover:text-[var(--color-success)] transition" />
          </button>

          <button
            onClick={() => navigate(`/sites/${siteId}/settings?tab=integrations`)}
            className="flex items-center gap-4 p-6 rounded-xl border-2 border-slate-200 bg-white hover:border-[var(--color-purple)] hover:shadow-lg transition-all group"
          >
            <div className="size-12 rounded-xl bg-gradient-to-br from-[var(--color-purple)] to-[var(--color-purple-dark)] flex items-center justify-center text-white shadow-lg">
              <PlugInIcon className="h-6 w-6" />
            </div>
            <div className="flex-1 text-left">
              <h4 className="font-semibold text-slate-900 mb-1">Integrations</h4>
              <p className="text-sm text-slate-600">Manage connections</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-slate-400 group-hover:text-[var(--color-purple)] transition" />
          </button>

          <button
            onClick={() => navigate(`/sites/${siteId}/sync`)}
            className="flex items-center gap-4 p-6 rounded-xl border-2 border-slate-200 bg-white hover:border-[var(--color-warning)] hover:shadow-lg transition-all group"
          >
            <div className="size-12 rounded-xl bg-gradient-to-br from-[var(--color-warning)] to-[var(--color-warning-dark)] flex items-center justify-center text-white shadow-lg">
              <BoltIcon className="h-6 w-6" />
            </div>
            <div className="flex-1 text-left">
              <h4 className="font-semibold text-slate-900 mb-1">Sync Dashboard</h4>
              <p className="text-sm text-slate-600">View sync status</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-slate-400 group-hover:text-[var(--color-warning)] transition" />
          </button>

          <button
            onClick={() => navigate(`/sites/${siteId}/deploy`)}
            className="flex items-center gap-4 p-6 rounded-xl border-2 border-slate-200 bg-white hover:border-[var(--color-primary)] hover:shadow-lg transition-all group"
          >
            <div className="size-12 rounded-xl bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] flex items-center justify-center text-white shadow-lg">
              <ArrowUpIcon className="h-6 w-6" />
            </div>
            <div className="flex-1 text-left">
              <h4 className="font-semibold text-slate-900 mb-1">Deploy Site</h4>
              <p className="text-sm text-slate-600">Deploy to production</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-slate-400 group-hover:text-[var(--color-primary)] transition" />
          </button>
        </div>
      </ComponentCard>

      {/* Recent Activity */}
      <Card className="p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Recent Activity
        </h2>
        <div className="space-y-3">
          {stats?.last_deployment ? (
            <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
              <div className="flex-shrink-0 size-10 rounded-lg bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] flex items-center justify-center text-white shadow-md">
                <CalendarIcon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900 dark:text-white">
                  Last Deployment
                </p>
                <p className="text-xs text-gray-600 dark:text-gray-400">
                  {new Date(stats.last_deployment).toLocaleString()}
                </p>
              </div>
            </div>
          ) : (
            <p className="text-sm text-gray-600 dark:text-gray-400">
              No recent activity
            </p>
          )}
        </div>
      </Card>
    </div>
  );
}

