'use client';

import { useState, useEffect, useCallback, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import {
  CheckCircle2, XCircle, AlertTriangle, RefreshCw, Loader2,
  Link2, Link2Off, FileText, CreditCard, Building2, ArrowDownToLine, BarChart3,
} from 'lucide-react';
import { PageHeader } from '@/components/navigation/page-header';

interface QboStatus {
  tokenStatus: 'valid' | 'expired' | 'missing';
  counts: {
    invoices: number;
    payments: number;
    deposits: number;
    transactions: number;
    reports: number;
  };
  lastSync: {
    invoices: string | null;
    payments: string | null;
    deposits: string | null;
    transactions: string | null;
    reports: string | null;
  };
}

function fmtDate(d: string | null) {
  if (!d) return 'Never';
  const date = new Date(d);
  const diff = Date.now() - date.getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
}

function fmtNum(n: number) {
  return n.toLocaleString();
}

const ENTITY_META = [
  { key: 'invoices',     label: 'Invoices',     icon: FileText,         color: 'text-blue-400' },
  { key: 'payments',     label: 'Payments',     icon: CreditCard,       color: 'text-green-400' },
  { key: 'deposits',     label: 'Deposits',     icon: Building2,        color: 'text-purple-400' },
  { key: 'transactions', label: 'Transactions', icon: ArrowDownToLine,  color: 'text-orange-400' },
  { key: 'reports',      label: 'Reports',      icon: BarChart3,        color: 'text-cyan-400' },
] as const;

function QboPageInner() {
  const searchParams = useSearchParams();
  const connected = searchParams.get('connected');
  const disconnected = searchParams.get('disconnected');
  const errorParam = searchParams.get('error');

  const [status, setStatus] = useState<QboStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);
  const [syncMessage, setSyncMessage] = useState<string | null>(null);
  const [banner, setBanner] = useState<{ type: 'success' | 'error' | 'info'; msg: string } | null>(null);

  const fetchStatus = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/qbo/sync');
      const data = await res.json();
      setStatus(data);
    } catch {
      setStatus(null);
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (connected === 'true') setBanner({ type: 'success', msg: 'QuickBooks Online connected successfully.' });
    else if (disconnected === 'true') setBanner({ type: 'info', msg: 'QuickBooks Online disconnected.' });
    else if (errorParam) setBanner({ type: 'error', msg: decodeURIComponent(errorParam) });
  }, [connected, disconnected, errorParam]);

  async function triggerSync(syncType: 'full' | 'incremental') {
    setSyncing(true);
    setSyncMessage(null);
    try {
      const res = await fetch('/api/qbo/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ syncType, triggeredBy: 'admin-ui' }),
      });
      const data = await res.json();
      if (res.ok) {
        setSyncMessage(`${syncType === 'full' ? 'Full' : 'Incremental'} sync started. This may take a few minutes.`);
        setTimeout(() => fetchStatus(), 10000);
        setTimeout(() => fetchStatus(), 30000);
        setTimeout(() => { fetchStatus(); setSyncing(false); }, 60000);
      } else {
        setSyncMessage(`Error: ${data.error}`);
        setSyncing(false);
      }
    } catch (err) {
      setSyncMessage(`Error: ${err instanceof Error ? err.message : String(err)}`);
      setSyncing(false);
    }
  }

  const tokenOk = status?.tokenStatus === 'valid';
  const tokenBadge = {
    valid:   { icon: CheckCircle2, label: 'Connected', cls: 'text-green-400' },
    expired: { icon: AlertTriangle, label: 'Token Expired', cls: 'text-yellow-400' },
    missing: { icon: XCircle, label: 'Not Connected', cls: 'text-red-400' },
  }[status?.tokenStatus ?? 'missing'];

  return (
    <>
      <PageHeader
        title="QuickBooks Online"
        description="Sync invoices, payments, deposits, transactions and financial reports"
        breadcrumbs={[{ label: 'Admin', href: '/admin' }, { label: 'QuickBooks Online' }]}
        accent
        actions={
          <Button variant="outline" size="sm" onClick={fetchStatus} disabled={loading}>
            <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        }
      />
      <div className="p-6 max-w-4xl mx-auto space-y-6">
      {/* Banner */}
      {banner && (
        <div className={`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${
          banner.type === 'success' ? 'bg-green-500/10 border-green-500/30 text-green-300' :
          banner.type === 'error'   ? 'bg-red-500/10 border-red-500/30 text-red-300' :
                                      'bg-blue-500/10 border-blue-500/30 text-blue-300'
        }`}>
          {banner.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> :
           banner.type === 'error'   ? <XCircle className="w-4 h-4 shrink-0" /> :
                                       <AlertTriangle className="w-4 h-4 shrink-0" />}
          {banner.msg}
          <button className="ml-auto opacity-60 hover:opacity-100" onClick={() => setBanner(null)}>✕</button>
        </div>
      )}

      {/* Connection Status */}
      <div className="rounded-xl border bg-card p-5 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="font-semibold text-base">Connection Status</h2>
          {loading ? (
            <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
          ) : (
            <div className={`flex items-center gap-1.5 text-sm font-medium ${tokenBadge.cls}`}>
              <tokenBadge.icon className="w-4 h-4" />
              {tokenBadge.label}
            </div>
          )}
        </div>

        <div className="flex gap-3 flex-wrap">
          <a href="/api/qbo/auth">
            <Button variant="outline" size="sm" className="gap-2">
              <Link2 className="w-4 h-4" />
              {tokenOk ? 'Reconnect' : 'Connect to QuickBooks'}
            </Button>
          </a>
          {tokenOk && (
            <a href="/api/qbo/disconnect">
              <Button variant="outline" size="sm" className="gap-2 text-red-400 border-red-500/30 hover:bg-red-500/10">
                <Link2Off className="w-4 h-4" />
                Disconnect
              </Button>
            </a>
          )}
        </div>
      </div>

      {/* Sync Controls */}
      <div className="rounded-xl border bg-card p-5 space-y-4">
        <h2 className="font-semibold text-base">Sync</h2>
        <div className="flex gap-3 flex-wrap">
          <Button
            onClick={() => triggerSync('full')}
            disabled={syncing || !tokenOk}
            size="sm"
            className="gap-2"
          >
            {syncing ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
            Full Sync
          </Button>
          <Button
            onClick={() => triggerSync('incremental')}
            disabled={syncing || !tokenOk}
            variant="outline"
            size="sm"
            className="gap-2"
          >
            {syncing ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
            Incremental Sync
          </Button>
        </div>
        {syncMessage && (
          <p className="text-sm text-muted-foreground">{syncMessage}</p>
        )}
      </div>

      {/* Entity Counts */}
      <div className="rounded-xl border bg-card p-5 space-y-4">
        <h2 className="font-semibold text-base">Synced Data</h2>
        {loading ? (
          <div className="flex items-center gap-2 text-muted-foreground text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading...
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {ENTITY_META.map(({ key, label, icon: Icon, color }) => (
              <div key={key} className="flex items-center gap-3 p-3 rounded-lg bg-muted/30 border border-border">
                <Icon className={`w-5 h-5 shrink-0 ${color}`} />
                <div>
                  <div className="text-lg font-semibold leading-none">
                    {fmtNum(status?.counts[key] ?? 0)}
                  </div>
                  <div className="text-xs text-muted-foreground mt-0.5">{label}</div>
                  <div className="text-xs text-muted-foreground/60 mt-0.5">
                    {fmtDate(status?.lastSync[key] ?? null)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      </div>
    </>
  );
}

export default function QboAdminPage() {
  return (
    <Suspense fallback={<div className="p-6 text-muted-foreground text-sm">Loading...</div>}>
      <QboPageInner />
    </Suspense>
  );
}
