import React, { useState, useEffect } from 'react';
import { KPICard } from '../components/KPICard';
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
import { getCategoryColor } from '../data/kpiData';
import { useSQLiteDatabase } from '../database/useSQLiteDatabase';
import { AlertTriangle, TrendingUp, BarChart3, CheckCircle2 } from 'lucide-react';

export const HomePage: React.FC = () => {
  const db = useSQLiteDatabase();
  const [timeRange, setTimeRange] = useState<'today' | 'week' | 'last7' | 'month' | 'year'>('today');
  const [stats, setStats] = useState({ total: 0, good: 0, warning: 0, critical: 0 });
  const [topKPIs, setTopKPIs] = useState<any>({});
  const [avgPerformance, setAvgPerformance] = useState(0);
  const [criticalAlerts, setCriticalAlerts] = useState<any[]>([]);

  const getDaysFromTimeRange = (range: 'today' | 'week' | 'last7' | 'month' | 'year'): number => {
    switch (range) {
      case 'today':
        return 0;
      case 'week': {
        const today = new Date();
        const dayOfWeek = today.getDay();
        const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
        return daysFromMonday;
      }
      case 'last7':
        return 7;
      case 'month':
        return 30;
      case 'year':
        return 365;
      default:
        return 0;
    }
  };

  useEffect(() => {
    if (db.loading || db.kpis.length === 0) return;

    const fetchData = async () => {
      const days = getDaysFromTimeRange(timeRange);
      const kpisWithStatus: any[] = [];
      const alertList: any[] = [];

      for (const kpi of db.kpis) {
        const measurements = await db.getMeasurementsForKPI(kpi.id, days);

        let status = 'good';
        let value = 0;

        if (measurements && measurements.length > 0) {
          const values = measurements.map((m: any) => m.value);
          value = Math.round((values.reduce((a: number, b: number) => a + b, 0) / values.length) * 100) / 100;

          const tolerance = kpi.target! * 0.1;

          if ([2, 4, 5, 6, 13, 16].includes(kpi.id)) {
            if (value > kpi.target! + tolerance * 2) status = 'critical';
            else if (value > kpi.target! + tolerance) status = 'warning';
            else status = 'good';
          } else {
            if (value < kpi.target! - tolerance * 2) status = 'critical';
            else if (value < kpi.target! - tolerance) status = 'warning';
            else status = 'good';
          }

          if (status === 'critical' || status === 'warning') {
            alertList.push({ ...kpi, status, value });
          }
        }

        kpisWithStatus.push({ ...kpi, status, value });
      }

      const statCounts = {
        total: kpisWithStatus.length,
        good: kpisWithStatus.filter(k => k.status === 'good').length,
        warning: kpisWithStatus.filter(k => k.status === 'warning').length,
        critical: kpisWithStatus.filter(k => k.status === 'critical').length
      };

      const topKPIsMap: any = {};
      [1, 2, 3, 4, 5].forEach(catId => {
        topKPIsMap[catId] = kpisWithStatus
          .filter(k => k.category_id === catId)
          .slice(0, 1);
      });

      const performance = Math.round(
        ((statCounts.good * 100 + statCounts.warning * 50) / (statCounts.total * 100)) * 100
      );

      setStats(statCounts);
      setTopKPIs(topKPIsMap);
      setAvgPerformance(performance);
      setCriticalAlerts(alertList.sort((a, b) => {
        if (a.status === 'critical' && b.status !== 'critical') return -1;
        if (a.status !== 'critical' && b.status === 'critical') return 1;
        return 0;
      }).slice(0, 3));
    };

    fetchData();
  }, [db, timeRange]);

  if (db.loading) {
    return (
      <div className="container mx-auto p-6">
        <Card className="border-2">
          <CardContent className="py-12">
            <div className="flex flex-col items-center gap-3">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-primary"></div>
              <p className="text-center text-muted-foreground">Loading data...</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (db.error) {
    return (
      <div className="container mx-auto p-6">
        <Card className="border-2 border-destructive">
          <CardContent className="py-12">
            <div className="flex flex-col items-center gap-3">
              <AlertTriangle className="h-12 w-12 text-destructive" />
              <p className="text-center text-destructive text-lg font-semibold">{db.error}</p>
              <p className="text-center text-sm text-muted-foreground max-w-md">
                Please ensure the API server is running: <code className="bg-muted px-2 py-1 rounded font-mono">npm run server</code>
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const timeRangeOptions = [
    { value: 'today', label: 'Today' },
    { value: 'week', label: 'Week' },
    { value: 'last7', label: 'Last 7D' },
    { value: 'month', label: 'Month' },
    { value: 'year', label: 'Year' },
  ] as const;

  return (
    <div className="h-[calc(100vh-180px)] overflow-hidden">
      <div className="container mx-auto p-6 h-full flex flex-col gap-4">
        {/* Compact Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">Performance Overview</h1>
            <p className="text-sm text-muted-foreground">Real-time SQDC Metrics</p>
          </div>
          <div className="flex gap-1">
            {timeRangeOptions.map(option => (
              <Button
                key={option.value}
                variant={timeRange === option.value ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTimeRange(option.value)}
                className="px-3"
              >
                {option.label}
              </Button>
            ))}
          </div>
        </div>

        {/* Compact Stats - Single Row */}
        <div className="grid grid-cols-5 gap-3">
          <Card className="border">
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <BarChart3 className="h-4 w-4 text-muted-foreground" />
                <span className="text-xs text-muted-foreground">Total</span>
              </div>
              <div className="text-2xl font-bold">{stats.total}</div>
            </CardContent>
          </Card>

          <Card className="border border-emerald-500/30">
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <CheckCircle2 className="h-4 w-4 text-emerald-500" />
                <span className="text-xs text-muted-foreground">On Target</span>
              </div>
              <div className="text-2xl font-bold text-emerald-500">{stats.good}</div>
            </CardContent>
          </Card>

          <Card className="border border-amber-500/30">
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <AlertTriangle className="h-4 w-4 text-amber-500" />
                <span className="text-xs text-muted-foreground">Warning</span>
              </div>
              <div className="text-2xl font-bold text-amber-500">{stats.warning}</div>
            </CardContent>
          </Card>

          <Card className="border border-red-500/30">
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <AlertTriangle className="h-4 w-4 text-red-500" />
                <span className="text-xs text-muted-foreground">Critical</span>
              </div>
              <div className="text-2xl font-bold text-red-500">{stats.critical}</div>
            </CardContent>
          </Card>

          <Card className="border border-primary/30">
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <TrendingUp className="h-4 w-4 text-primary" />
                <span className="text-xs text-muted-foreground">Score</span>
              </div>
              <div className="text-2xl font-bold text-primary">{avgPerformance}%</div>
            </CardContent>
          </Card>
        </div>

        {/* Main Content Grid */}
        <div className="grid grid-cols-3 gap-4 flex-1 min-h-0">
          {/* Left Column - Categories */}
          <div className="col-span-2 overflow-y-auto pr-2 space-y-3">
            {[1, 2, 3, 4, 5].map(catId => {
              const categoryKPIs = topKPIs[catId] || [];
              const category = db.categories.find(c => c.id === catId);

              if (!category || categoryKPIs.length === 0) return null;

              return (
                <div key={catId}>
                  <div className="flex items-center gap-2 mb-2">
                    <div className="h-1 w-8 rounded" style={{ backgroundColor: getCategoryColor(category.name) }}></div>
                    <h3 className="text-sm font-semibold" style={{ color: getCategoryColor(category.name) }}>
                      {category.name}
                    </h3>
                  </div>
                  <div className="grid gap-3">
                    {categoryKPIs.map((kpi: any) => (
                      <KPICard
                        key={kpi.id}
                        kpi={kpi}
                        color={getCategoryColor(category.name)}
                      />
                    ))}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Right Column - Alerts */}
          <div className="overflow-y-auto">
            <Card className="border-2 border-amber-500/30 bg-amber-500/5 h-full">
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <AlertTriangle className="h-5 w-5 text-amber-500" />
                  Alerts
                  {criticalAlerts.length > 0 && (
                    <Badge variant="warning" className="ml-auto">
                      {criticalAlerts.length}
                    </Badge>
                  )}
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {criticalAlerts.length === 0 ? (
                  <div className="text-center py-8">
                    <CheckCircle2 className="h-12 w-12 text-emerald-500 mx-auto mb-2" />
                    <p className="text-sm text-muted-foreground">All metrics on target</p>
                  </div>
                ) : (
                  criticalAlerts.map(alert => (
                    <div
                      key={alert.id}
                      className="p-3 border-2 rounded-lg bg-card"
                    >
                      <Badge variant={alert.status === 'critical' ? 'destructive' : 'warning'} className="mb-2">
                        {alert.status === 'critical' ? 'Critical' : 'Warning'}
                      </Badge>
                      <div className="font-semibold text-sm mb-1">{alert.name}</div>
                      <div className="text-xl font-bold">
                        {alert.value} <span className="text-xs text-muted-foreground font-normal">{alert.unit}</span>
                      </div>
                    </div>
                  ))
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
};
