'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ArrowLeft, RefreshCw, Play, CheckCircle2, XCircle, Clock,
  Shield, Monitor, AlertTriangle, Activity,
} from 'lucide-react';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

function fmtDate(d: string | null, tz: string) {
  if (!d) return '—';
  return new Date(d).toLocaleString(undefined, { timeZone: tz });
}
function fmtDuration(ms: number | null) {
  if (!ms) return '—';
  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
  return `${(ms / 60000).toFixed(1)}m`;
}

export default function SentinelOneSyncPage() {
  const tz = useUserTimezone();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch('/api/sentinelone/sync');
      if (res.ok) setData(await res.json());
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 10000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const triggerSync = async () => {
    setSyncing(true);
    try {
      await fetch('/api/sentinelone/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ triggeredBy: 'manual' }),
      });
      setTimeout(fetchData, 2000);
    } finally {
      setSyncing(false);
    }
  };

  const lastSync = data?.history?.[0];
  const counts = data?.counts ?? {};
  const inProgress = data?.inProgress ?? false;

  return (
    <div className="container mx-auto py-8 space-y-6 max-w-5xl">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/sync">
            <Button variant="ghost" size="sm"><ArrowLeft className="w-4 h-4 mr-1" />Back</Button>
          </Link>
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <Shield className="w-6 h-6 text-purple-500" />
              SentinelOne Sync
            </h1>
            <p className="text-sm text-muted-foreground">Sites, agents, and threats synced to s1_* tables</p>
          </div>
        </div>
        <Button onClick={triggerSync} disabled={syncing || inProgress}>
          {syncing || inProgress
            ? <><RefreshCw className="w-4 h-4 mr-2 animate-spin" />Syncing...</>
            : <><Play className="w-4 h-4 mr-2" />Sync Now</>}
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        {[
          { label: 'Sites', value: counts.sites, icon: Shield, color: 'text-purple-500' },
          { label: 'Agents', value: counts.agents, icon: Monitor, color: 'text-blue-500' },
          { label: 'Active', value: counts.active_agents, icon: Activity, color: 'text-green-500' },
          { label: 'Infected', value: counts.infected, icon: AlertTriangle, color: 'text-red-500' },
          { label: 'Threats', value: counts.threats, icon: XCircle, color: 'text-orange-500' },
        ].map(({ label, value, icon: Icon, color }) => (
          <Card key={label}>
            <CardHeader className="pb-2">
              <CardTitle className="text-xs text-muted-foreground flex items-center gap-1">
                <Icon className={`w-3 h-3 ${color}`} />{label}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {loading ? '—' : (Number(value ?? 0)).toLocaleString()}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Last sync status */}
      {lastSync && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm">Last Sync</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex items-center gap-3">
              {lastSync.status === 'completed'
                ? <CheckCircle2 className="w-5 h-5 text-green-500" />
                : lastSync.status === 'running'
                ? <RefreshCw className="w-5 h-5 text-blue-500 animate-spin" />
                : <XCircle className="w-5 h-5 text-red-500" />}
              <div>
                <div className="font-medium capitalize">{lastSync.status}</div>
                <div className="text-xs text-muted-foreground">
                  {fmtDate(lastSync.completed_at || lastSync.started_at, tz)} · {fmtDuration(lastSync.duration_ms)} · {lastSync.total_upserted?.toLocaleString()} records
                </div>
              </div>
            </div>
            {lastSync.entity_results && (
              <div className="grid grid-cols-3 gap-2">
                {(Array.isArray(lastSync.entity_results)
                  ? lastSync.entity_results
                  : JSON.parse(lastSync.entity_results)
                ).map((e: any) => (
                  <div key={e.entity} className="flex items-center justify-between text-sm border rounded p-2">
                    <span className="capitalize">{e.entity}</span>
                    <div className="flex items-center gap-1">
                      {e.success
                        ? <Badge variant="secondary">{e.recordsUpserted.toLocaleString()}</Badge>
                        : <Badge variant="destructive">failed</Badge>}
                    </div>
                  </div>
                ))}
              </div>
            )}
            {lastSync.error_message && (
              <div className="text-xs text-red-500 bg-red-500/10 rounded p-2">{lastSync.error_message}</div>
            )}
          </CardContent>
        </Card>
      )}

      {/* History */}
      <Card>
        <CardHeader><CardTitle className="text-sm">Sync History</CardTitle></CardHeader>
        <CardContent>
          <div className="space-y-2">
            {(data?.history ?? []).map((h: any) => (
              <div key={h.id} className="flex items-center justify-between text-sm border-b pb-2 last:border-0">
                <div className="flex items-center gap-2">
                  {h.status === 'completed' ? <CheckCircle2 className="w-4 h-4 text-green-500" />
                    : h.status === 'running' ? <RefreshCw className="w-4 h-4 text-blue-500 animate-spin" />
                    : <XCircle className="w-4 h-4 text-red-500" />}
                  <span className="text-muted-foreground">{fmtDate(h.started_at, tz)}</span>
                </div>
                <div className="flex items-center gap-3 text-muted-foreground">
                  <span>{h.total_upserted?.toLocaleString() ?? 0} records</span>
                  <span>{fmtDuration(h.duration_ms)}</span>
                  <Badge variant="outline" className="text-xs">{h.triggered_by}</Badge>
                </div>
              </div>
            ))}
            {!loading && (data?.history ?? []).length === 0 && (
              <p className="text-sm text-muted-foreground text-center py-4">No sync history yet — run a sync to get started</p>
            )}
          </div>
        </CardContent>
      </Card>

      <div className="flex gap-3">
        <Link href="/sentinelone/coverage">
          <Button variant="outline"><Shield className="w-4 h-4 mr-2" />Coverage Report</Button>
        </Link>
        <Link href="/sentinelone/mappings">
          <Button variant="outline"><Monitor className="w-4 h-4 mr-2" />Company Mappings</Button>
        </Link>
      </div>
    </div>
  );
}
