import React, { useEffect, useState } from 'react';
import { StatCard } from '../components/StatCard';
import { LiveOrdersTable } from '../components/LiveOrdersTable';
import { SystemStatusCard } from '../components/SystemStatusCard';
import { SupabaseService } from '../services/supabaseService';
import { ScheduleItem, SystemStatus, DashboardMetrics } from '../types';

export const DashboardView: React.FC = () => {
  const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
  const [liveOrders, setLiveOrders] = useState<ScheduleItem[]>([]);
  const [systemStatus, setSystemStatus] = useState<SystemStatus | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      const metricsData = await SupabaseService.getMetrics();
      const ordersData = await SupabaseService.getLiveOrders();
      const statusData = await SupabaseService.testConnection();

      setMetrics(metricsData);
      setLiveOrders(ordersData);
      setSystemStatus(statusData);
    };

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

  return (
    <>
      <header className="header-bar">
        <h1 className="header-title">Cockpit</h1>
        <div className="supabase-live-badge">
          <span className="status-dot"></span>
          <span>Verbunden</span>
        </div>
      </header>

      <section className="kpi-grid">
        <StatCard label="Aktive Aufträge" value={metrics ? `${metrics.activeOrdersCount}` : '12'} />
        <StatCard
          label="Monteure im Einsatz"
          value={metrics ? `${metrics.techniciansInField.active} / ${metrics.techniciansInField.total}` : '8 / 10'}
        />
        <StatCard
          label="Offene Rechnungen"
          value={metrics ? `€ ${metrics.openInvoicesAmount.toLocaleString('de-DE')}` : '€ 14.250'}
        />
        <StatCard
          label="Lagerwarnungen"
          value={metrics ? `${metrics.inventoryWarningsCount} Teile` : '2 Teile'}
          isWarning={true}
        />
      </section>

      <section className="dashboard-grid">
        <LiveOrdersTable orders={liveOrders} />
        <SystemStatusCard status={systemStatus} />
      </section>
    </>
  );
};
