import React, { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { api } from '@/api';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Toggle } from './adminShared';

function timeAgo(iso) {
  if (!iso) return null;
  const secs = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (secs < 60)  return 'just now';
  if (secs < 3600) return `${Math.floor(secs / 60)}m ago`;
  if (secs < 86400) return `${Math.floor(secs / 3600)}h ago`;
  return `${Math.floor(secs / 86400)}d ago`;
}

function timeUntil(iso) {
  if (!iso) return null;
  const secs = Math.floor((new Date(iso).getTime() - Date.now()) / 1000);
  if (secs <= 0) return 'soon';
  if (secs < 60) return `${secs}s`;
  if (secs < 3600) return `${Math.floor(secs / 60)}m`;
  return `${Math.floor(secs / 3600)}h`;
}

export default function BankSyncAdminCard() {
  const [config, setConfig]   = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving]   = useState(false);
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    api.bankSyncConfig()
      .then(d => {
        setConfig(d);
        setEnabled(!!d.enabled);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    setSaving(true);
    try {
      const result = await api.setBankSyncConfig({ enabled });
      setConfig(result);
      setEnabled(!!result.enabled);
      toast.success(enabled ? 'Bank sync enabled.' : 'Bank sync disabled.');
    } catch (err) {
      toast.error(err.message || 'Failed to update bank sync setting.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <Card>
        <CardContent className="py-8 text-center text-muted-foreground text-sm">
          Loading…
        </CardContent>
      </Card>
    );
  }

  const changed = enabled !== !!config?.enabled;
  const worker = config?.worker;

  return (
    <Card>
      <CardHeader className="pb-4">
        <CardTitle>Bank Sync (SimpleFIN)</CardTitle>
        <p className="text-sm text-muted-foreground mt-1">
          Allow users to connect their own SimpleFIN Bridge account to sync
          read-only bank transactions. Each user manages their own connection
          from the Data page — no bank credentials are stored.
        </p>
      </CardHeader>
      <CardContent className="space-y-5">

        {/* Enable toggle */}
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium">Allow users to connect SimpleFIN</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              When enabled, users see a Bank Sync section on their Data page.
            </p>
          </div>
          <Toggle
            checked={enabled}
            onChange={v => setEnabled(v)}
            label="Enable bank sync"
          />
        </div>

        {/* Auto-sync worker status */}
        {config?.enabled && worker && (
          <div className="rounded-lg border border-border/60 bg-muted/20 px-4 py-3 space-y-2">
            <p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">Auto-sync worker</p>
            <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm sm:grid-cols-3">
              <div>
                <p className="text-xs text-muted-foreground">Status</p>
                <p className="font-medium flex items-center gap-1.5">
                  <span className={`h-1.5 w-1.5 rounded-full ${worker.running ? 'bg-amber-500 animate-pulse' : 'bg-emerald-500'}`} />
                  {worker.running ? 'Running' : 'Idle'}
                </p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Last run</p>
                <p className="font-medium">{worker.last_run_at ? timeAgo(worker.last_run_at) : '—'}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Next run</p>
                <p className="font-medium">{worker.next_run_at ? `in ${timeUntil(worker.next_run_at)}` : '—'}</p>
              </div>
            </div>
            <p className="text-xs text-muted-foreground">
              Syncs every {worker.interval_hours}h. Set <code className="font-mono">SIMPLEFIN_SYNC_INTERVAL_HOURS</code> to adjust.
            </p>
          </div>
        )}

        <div className="flex justify-end pt-2">
          <Button onClick={handleSave} disabled={saving || !changed}>
            {saving ? 'Saving…' : 'Save'}
          </Button>
        </div>

      </CardContent>
    </Card>
  );
}
