'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,
  Building2, Package, Boxes,
} from 'lucide-react';
import { toast } from 'sonner';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

interface Pax8SyncHistoryEntry {
  id: string;
  sync_type: string;
  status: string;
  started_at: string;
  completed_at: string | null;
  records_added: number;
  records_updated: number;
  records_deleted: number;
  error_message: string | null;
  triggered_by: string;
}

interface Pax8SyncData {
  inProgress: boolean;
  counts: { companies: number; subscriptions: number; products: number };
  history: Pax8SyncHistoryEntry[];
}

function fmtDate(d: string | null, tz: string) {
  if (!d) return '—';
  return new Date(d).toLocaleString(undefined, { timeZone: tz });
}

function fmtDuration(started: string | null, completed: string | null) {
  if (!started || !completed) return '—';
  const ms = new Date(completed).getTime() - new Date(started).getTime();
  if (!Number.isFinite(ms) || ms < 0) return '—';
  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
  return `${(ms / 60000).toFixed(1)}m`;
}

function totalRecords(h: Pax8SyncHistoryEntry) {
  return (h.records_added ?? 0) + (h.records_updated ?? 0) + (h.records_deleted ?? 0);
}

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

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch('/api/pax8/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 {
      const res = await fetch('/api/pax8/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ triggeredBy: 'manual' }),
      });
      if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        toast.error(json.message || json.error || 'Failed to start PAX8 sync');
        setSyncing(false);
        return;
      }
      toast.success('PAX8 sync started');
      const poll = setInterval(async () => {
        const r = await fetch('/api/pax8/sync');
        if (r.ok) {
          const d = await r.json();
          if (!d.inProgress) {
            clearInterval(poll);
            setSyncing(false);
            fetchData();
          }
        }
      }, 5000);
    } catch (e) {
      console.error(e);
      toast.error('Failed to start PAX8 sync');
      setSyncing(false);
    }
  };

  const lastSync = data?.history?.[0];
  const counts = data?.counts ?? { companies: 0, subscriptions: 0, products: 0 };
  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 className="flex items-center gap-3">
            <img src="/logos/pax8.ico" alt="PAX8" className="w-8 h-8 rounded" />
            <div>
              <h1 className="text-2xl font-bold">PAX8 Sync</h1>
              <p className="text-sm text-muted-foreground">Companies, subscriptions, and products synced to pax8_* tables</p>
            </div>
          </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-3 gap-4">
        {[
          { label: 'Companies', value: counts.companies, icon: Building2, color: 'text-blue-500' },
          { label: 'Subscriptions', value: counts.subscriptions, icon: Package, color: 'text-green-500' },
          { label: 'Products', value: counts.products, icon: Boxes, color: 'text-purple-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.started_at, lastSync.completed_at)} · {totalRecords(lastSync).toLocaleString()} records
                </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) => (
              <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>{totalRecords(h).toLocaleString()} records</span>
                  <span>{fmtDuration(h.started_at, h.completed_at)}</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>
  );
}
