/**
 * Admin Sync Page
 * Main page for controlling and monitoring Autotask PostgreSQL sync operations
 */

'use client';

import { useState, useEffect } from 'react';
import SyncControlPanel from '@/components/admin/SyncControlPanel';
import SyncDashboard from '@/components/admin/SyncDashboard';
import SyncHistoryTable from '@/components/admin/SyncHistoryTable';
import { EntityType } from '@/lib/types/sync';
import { Button } from '@/components/ui/button';
import { ArrowLeft, Home } from 'lucide-react';
import Link from 'next/link';

export default function AdminSyncPage() {
  const [selectedEntities, setSelectedEntities] = useState<EntityType[]>([]);
  const [isSyncing, setIsSyncing] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  // Auto-refresh during sync and check if sync completed
  useEffect(() => {
    if (isSyncing) {
      const interval = setInterval(async () => {
        setRefreshKey(prev => prev + 1);
        
        // Check if sync is still in progress
        try {
          const response = await fetch('/api/sync/status');
          if (response.ok) {
            const data = await response.json();
            // If no sync in progress, mark as complete
            if (!data.inProgress) {
              setIsSyncing(false);
            }
          }
        } catch (error) {
          console.error('Failed to check sync status:', error);
        }
      }, 5000); // Refresh every 5 seconds

      return () => clearInterval(interval);
    }
  }, [isSyncing]);

  const handleSyncStart = () => {
    setIsSyncing(true);
  };

  const handleSyncComplete = () => {
    setIsSyncing(false);
    setRefreshKey(prev => prev + 1);
  };

  return (
    <div className="container mx-auto py-4 md:py-8 px-4 space-y-6 md:space-y-8">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/">
            <Button variant="outline" size="sm" className="gap-2">
              <ArrowLeft className="w-4 h-4" />
              <Home className="w-4 h-4" />
              <span className="hidden sm:inline">Back to Dashboard</span>
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl md:text-3xl font-bold">Autotask Sync</h1>
            <p className="text-sm md:text-base text-muted-foreground mt-1">
              Sync Autotask data to PostgreSQL database
            </p>
          </div>
        </div>
      </div>

      {/* Sync Control Panel */}
      <SyncControlPanel
        selectedEntities={selectedEntities}
        onSelectedEntitiesChange={setSelectedEntities}
        onSyncStart={handleSyncStart}
        onSyncComplete={handleSyncComplete}
        isSyncing={isSyncing}
      />

      {/* Sync Dashboard */}
      <SyncDashboard refreshKey={refreshKey} />

      {/* Sync History */}
      <SyncHistoryTable refreshKey={refreshKey} />
    </div>
  );
}
