
"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ExportButton } from "@/components/ui/export-button";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { 
  Clock, 
  TrendingDown, 
  AlertCircle, 
  Search,
  Zap,
  Target
} from "lucide-react";
import { DateRange } from "react-day-picker";
import { format } from "date-fns";

interface QuoteLatency {
  id: string;
  quoteId: string;
  customerName: string;
  requestDate: string;
  quoteDate: string;
  latencyHours: number;
  bottleneck: string;
  status: "fast" | "normal" | "slow";
  region: string;
}

export function QuoteLatencyDashboard({ 
  dateRange, 
  region 
}: { 
  dateRange: DateRange | undefined;
  region: string;
}) {
  const [latencies, setLatencies] = useState<QuoteLatency[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

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

  const loadLatencies = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        from: dateRange?.from?.toISOString() || "",
        to: dateRange?.to?.toISOString() || "",
        region: region !== "all" ? region : "",
      });
      
      const res = await fetch(`/api/quote-latency?${params}`);
      if (!res.ok) throw new Error("Failed to load latency data");
      
      const data = await res.json();
      setLatencies(data.latencies || []);
    } catch (error) {
      console.error("Error loading latency data:", error);
      toast.error("Failed to load quote latency data");
    } finally {
      setLoading(false);
    }
  };

  const filteredLatencies = latencies.filter(latency => 
    latency.customerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    latency.quoteId.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = {
    avgLatency: latencies.length > 0 
      ? Math.round(latencies.reduce((sum, l) => sum + l.latencyHours, 0) / latencies.length)
      : 0,
    fast: latencies.filter(l => l.status === "fast").length,
    normal: latencies.filter(l => l.status === "normal").length,
    slow: latencies.filter(l => l.status === "slow").length,
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      fast: { variant: "secondary" as const, icon: Zap, label: "Fast", color: "text-green-600" },
      normal: { variant: "default" as const, icon: Clock, label: "Normal", color: "text-blue-600" },
      slow: { variant: "destructive" as const, icon: AlertCircle, label: "Slow", color: "text-red-600" },
    };
    const config = variants[status as keyof typeof variants];
    if (!config) return null;
    
    const Icon = config.icon;
    return (
      <Badge variant={config.variant} className="flex items-center gap-1">
        <Icon className="h-3 w-3" />
        {config.label}
      </Badge>
    );
  };

  const exportColumns = [
    { header: "Quote ID", key: "quoteId" },
    { header: "Customer", key: "customerName" },
    { header: "Request Date", key: "requestDate" },
    { header: "Quote Date", key: "quoteDate" },
    { header: "Latency (hours)", key: "latencyHours" },
    { header: "Bottleneck", key: "bottleneck" },
    { header: "Status", key: "status" },
  ];

  return (
    <div className="space-y-6">
      {/* Stats Overview */}
      <div className="grid gap-4 grid-cols-1 sm:grid-cols-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Target className="h-4 w-4 text-blue-600" />
              Avg Latency
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.avgLatency}h</div>
          </CardContent>
        </Card>

        <Card className="border-green-200 bg-green-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Zap className="h-4 w-4 text-green-600" />
              Fast
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.fast}</div>
            <p className="text-xs text-muted-foreground mt-1">&lt; 12 hours</p>
          </CardContent>
        </Card>

        <Card className="border-blue-200 bg-blue-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Clock className="h-4 w-4 text-blue-600" />
              Normal
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{stats.normal}</div>
            <p className="text-xs text-muted-foreground mt-1">12-24 hours</p>
          </CardContent>
        </Card>

        <Card className="border-red-200 bg-red-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <AlertCircle className="h-4 w-4 text-red-600" />
              Slow
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.slow}</div>
            <p className="text-xs text-muted-foreground mt-1">&gt; 24 hours</p>
          </CardContent>
        </Card>
      </div>

      {/* Latency Table */}
      <Card>
        <CardHeader>
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <CardTitle>Quote Latency Analysis</CardTitle>
              <CardDescription>Identify and reduce quote response bottlenecks</CardDescription>
            </div>
            <ExportButton
              data={filteredLatencies}
              columns={exportColumns}
              filename={`quote-latency-${format(new Date(), "yyyy-MM-dd")}`}
              title="Quote Latency Report"
            />
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Search */}
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Search quotes or customers..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9"
            />
          </div>

          {/* Latency Table */}
          <div className="rounded-md border overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="px-4 py-3 text-left text-sm font-medium">Quote ID</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Customer</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Request Date</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Quote Date</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Latency</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Bottleneck</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {loading ? (
                    <tr>
                      <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                        Loading...
                      </td>
                    </tr>
                  ) : filteredLatencies.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                        No latency data found
                      </td>
                    </tr>
                  ) : (
                    filteredLatencies.map((latency) => (
                      <tr key={latency.id} className="hover:bg-muted/30">
                        <td className="px-4 py-3 text-sm font-medium">{latency.quoteId}</td>
                        <td className="px-4 py-3 text-sm">{latency.customerName}</td>
                        <td className="px-4 py-3 text-sm">
                          {format(new Date(latency.requestDate), "MMM dd, HH:mm")}
                        </td>
                        <td className="px-4 py-3 text-sm">
                          {format(new Date(latency.quoteDate), "MMM dd, HH:mm")}
                        </td>
                        <td className="px-4 py-3 text-sm font-medium">
                          {latency.latencyHours}h
                        </td>
                        <td className="px-4 py-3 text-sm">
                          <Badge variant="outline">{latency.bottleneck}</Badge>
                        </td>
                        <td className="px-4 py-3">
                          {getStatusBadge(latency.status)}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
