import React, { useState, useEffect, useCallback } from 'react';
import { api } from '@/api';
import BankSyncSection from '@/components/data/BankSyncSection';
import ImportTransactionCsvSection from '@/components/data/ImportTransactionCsvSection';
import TransactionMatchingSection from '@/components/data/TransactionMatchingSection';
import ImportSpreadsheetSection from '@/components/data/ImportSpreadsheetSection';
import ImportMyDataSection from '@/components/data/ImportMyDataSection';
import SeedDemoDataSection from '@/components/data/SeedDemoDataSection';
import DownloadMyDataSection from '@/components/data/DownloadMyDataSection';
import ImportHistorySection from '@/components/data/ImportHistorySection';

export default function DataPage() {
  const [history, setHistory]               = useState(null);
  const [historyLoading, setHistoryLoading] = useState(true);
  const [transactionRefreshKey, setTransactionRefreshKey] = useState(0);
  const [simplefinConn, setSimplefinConn]   = useState(null);

  const loadHistory = async () => {
    setHistoryLoading(true);
    try {
      const { history } = await api.importHistory();
      setHistory(history);
    } catch {
      setHistory([]);
    } finally {
      setHistoryLoading(false);
    }
  };

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

  const handleTransactionImportComplete = () => {
    loadHistory();
    setTransactionRefreshKey(key => key + 1);
  };

  // Called by BankSyncSection when connection state changes (connect/sync/disconnect)
  const handleConnectionChange = useCallback((conn) => {
    setSimplefinConn(conn || null);
    setTransactionRefreshKey(key => key + 1);
  }, []);

  return (
    <div className="mx-auto w-full max-w-6xl space-y-5">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Data</h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            Import, export, and review your user-owned bill tracker records.
          </p>
        </div>
        <div className="rounded-full border border-border/70 bg-card/80 px-3 py-1.5 text-xs font-medium text-muted-foreground">
          User data only
        </div>
      </div>

      <div className="space-y-5">
        <BankSyncSection onConnectionChange={handleConnectionChange} />
        <ImportTransactionCsvSection onHistoryRefresh={handleTransactionImportComplete} />
        <TransactionMatchingSection refreshKey={transactionRefreshKey} simplefinConn={simplefinConn} />
        <ImportSpreadsheetSection onHistoryRefresh={loadHistory} />
        <ImportMyDataSection onHistoryRefresh={loadHistory} />
      </div>
      <SeedDemoDataSection onSeeded={loadHistory} />
      <DownloadMyDataSection />
      <ImportHistorySection history={history} loading={historyLoading} onRefresh={loadHistory} />
    </div>
  );
}
