
"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DateRangePicker } from "@/components/ui/date-range-picker";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { 
  Activity, 
  AlertTriangle, 
  TrendingUp, 
  Users, 
  Clock,
  RefreshCw,
  Settings
} from "lucide-react";
import { DateRange } from "react-day-picker";
import { addDays, startOfMonth, endOfMonth } from "date-fns";
import { BadgeRenewalDashboard } from "./badge-renewal-dashboard";
import { DispatchRouterDashboard } from "./dispatch-router-dashboard";
import { QuoteLatencyDashboard } from "./quote-latency-dashboard";
import { PartnerOnboardingDashboard } from "./partner-onboarding-dashboard";

interface CockpitData {
  activeProjects: number;
  pendingBadges: number;
  avgQuoteTime: number;
  dispatchEfficiency: number;
  onboardingPartners: number;
}

export function EnhancedCockpitDashboard({ userRole }: { userRole: string }) {
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: startOfMonth(new Date()),
    to: endOfMonth(new Date()),
  });
  const [region, setRegion] = useState<string>("all");
  const [data, setData] = useState<CockpitData | null>(null);
  const [loading, setLoading] = useState(true);
  const [autoRefresh, setAutoRefresh] = useState(false);

  const loadData = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        from: dateRange?.from?.toISOString() || "",
        to: dateRange?.to?.toISOString() || "",
        region,
      });
      
      const res = await fetch(`/api/cockpit?${params}`);
      if (!res.ok) throw new Error("Failed to load cockpit data");
      
      const result = await res.json();
      setData(result);
    } catch (error) {
      console.error("Error loading cockpit data:", error);
      toast.error("Failed to load dashboard data");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [dateRange, region]);

  useEffect(() => {
    if (!autoRefresh) return;
    const interval = setInterval(loadData, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, [autoRefresh, dateRange, region]);

  const stats = [
    {
      title: "Active Projects",
      value: data?.activeProjects || 0,
      icon: Activity,
      color: "text-blue-600",
      bgColor: "bg-blue-50",
    },
    {
      title: "Pending Badges",
      value: data?.pendingBadges || 0,
      icon: AlertTriangle,
      color: "text-orange-600",
      bgColor: "bg-orange-50",
    },
    {
      title: "Avg Quote Time",
      value: `${data?.avgQuoteTime || 0}h`,
      icon: Clock,
      color: "text-green-600",
      bgColor: "bg-green-50",
    },
    {
      title: "Dispatch Efficiency",
      value: `${data?.dispatchEfficiency || 0}%`,
      icon: TrendingUp,
      color: "text-purple-600",
      bgColor: "bg-purple-50",
    },
  ];

  return (
    <div className="space-y-6">
      {/* Header with Filters */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Operations Cockpit</h1>
          <p className="text-muted-foreground">
            Real-time operational intelligence and performance monitoring
          </p>
        </div>
        
        <div className="flex flex-wrap items-center gap-3">
          <DateRangePicker value={dateRange} onChange={setDateRange} />
          
          <Select value={region} onValueChange={setRegion}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Select region" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Regions</SelectItem>
              <SelectItem value="south-africa">South Africa</SelectItem>
              <SelectItem value="usa">USA</SelectItem>
              <SelectItem value="uk">United Kingdom</SelectItem>
              <SelectItem value="australia">Australia</SelectItem>
            </SelectContent>
          </Select>
          
          <Button
            variant={autoRefresh ? "default" : "outline"}
            size="icon"
            onClick={() => setAutoRefresh(!autoRefresh)}
            title={autoRefresh ? "Disable auto-refresh" : "Enable auto-refresh"}
          >
            <RefreshCw className={`h-4 w-4 ${autoRefresh ? "animate-spin" : ""}`} />
          </Button>
          
          <Button variant="outline" size="icon">
            <Settings className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
        {stats.map((stat, index) => (
          <Card key={index} className="hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
              <div className={`p-2 rounded-lg ${stat.bgColor}`}>
                <stat.icon className={`h-4 w-4 ${stat.color}`} />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stat.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Feature Tabs */}
      <Tabs defaultValue="badges" className="space-y-4">
        <TabsList className="grid w-full grid-cols-2 lg:grid-cols-4">
          <TabsTrigger value="badges">Badge Renewals</TabsTrigger>
          <TabsTrigger value="dispatch">Dispatch Router</TabsTrigger>
          <TabsTrigger value="latency">Quote Latency</TabsTrigger>
          <TabsTrigger value="onboarding">Partner Onboarding</TabsTrigger>
        </TabsList>

        <TabsContent value="badges" className="space-y-4">
          <BadgeRenewalDashboard dateRange={dateRange} region={region} />
        </TabsContent>

        <TabsContent value="dispatch" className="space-y-4">
          <DispatchRouterDashboard dateRange={dateRange} region={region} />
        </TabsContent>

        <TabsContent value="latency" className="space-y-4">
          <QuoteLatencyDashboard dateRange={dateRange} region={region} />
        </TabsContent>

        <TabsContent value="onboarding" className="space-y-4">
          <PartnerOnboardingDashboard dateRange={dateRange} region={region} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
