
"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 { 
  MapPin, 
  TrendingUp, 
  Clock, 
  Search,
  Navigation,
  Calendar as CalendarIcon
} from "lucide-react";
import { DateRange } from "react-day-picker";
import { format } from "date-fns";

interface DispatchRecommendation {
  id: string;
  jobId: string;
  contractorName: string;
  location: string;
  distance: number;
  skillMatch: number;
  availability: string;
  estimatedTime: string;
  priority: "high" | "medium" | "low";
  region: string;
}

export function DispatchRouterDashboard({ 
  dateRange, 
  region 
}: { 
  dateRange: DateRange | undefined;
  region: string;
}) {
  const [recommendations, setRecommendations] = useState<DispatchRecommendation[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

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

  const loadRecommendations = 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/dispatch?${params}`);
      if (!res.ok) throw new Error("Failed to load dispatch data");
      
      const data = await res.json();
      setRecommendations(data.recommendations || []);
    } catch (error) {
      console.error("Error loading dispatch data:", error);
      toast.error("Failed to load dispatch recommendations");
    } finally {
      setLoading(false);
    }
  };

  const assignContractor = async (jobId: string, contractorId: string) => {
    try {
      const res = await fetch(`/api/dispatch/assign`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jobId, contractorId }),
      });
      
      if (!res.ok) throw new Error("Failed to assign contractor");
      toast.success("Contractor assigned successfully");
      loadRecommendations();
    } catch (error) {
      toast.error("Failed to assign contractor");
    }
  };

  const createCalendarEvent = async (recommendation: DispatchRecommendation) => {
    try {
      const res = await fetch("/api/calendar/events", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: `Job ${recommendation.jobId} - ${recommendation.contractorName}`,
          description: `Dispatch to ${recommendation.location}`,
          startTime: recommendation.estimatedTime,
          location: recommendation.location,
        }),
      });
      
      if (!res.ok) throw new Error("Failed to create calendar event");
      toast.success("Calendar event created");
    } catch (error) {
      toast.error("Failed to create calendar event");
    }
  };

  const filteredRecommendations = recommendations.filter(rec => 
    rec.contractorName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    rec.location.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getPriorityBadge = (priority: string) => {
    const variants = {
      high: { variant: "destructive" as const, label: "High Priority" },
      medium: { variant: "default" as const, label: "Medium Priority" },
      low: { variant: "secondary" as const, label: "Low Priority" },
    };
    const config = variants[priority as keyof typeof variants];
    return <Badge variant={config?.variant}>{config?.label}</Badge>;
  };

  const exportColumns = [
    { header: "Job ID", key: "jobId" },
    { header: "Contractor", key: "contractorName" },
    { header: "Location", key: "location" },
    { header: "Distance (km)", key: "distance" },
    { header: "Skill Match (%)", key: "skillMatch" },
    { header: "Availability", key: "availability" },
    { header: "Estimated Time", key: "estimatedTime" },
    { header: "Priority", key: "priority" },
  ];

  return (
    <div className="space-y-6">
      {/* Stats Overview */}
      <div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <TrendingUp className="h-4 w-4 text-blue-600" />
              Avg Skill Match
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {recommendations.length > 0 
                ? Math.round(recommendations.reduce((sum, r) => sum + r.skillMatch, 0) / recommendations.length)
                : 0}%
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <MapPin className="h-4 w-4 text-green-600" />
              Avg Distance
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {recommendations.length > 0 
                ? Math.round(recommendations.reduce((sum, r) => sum + r.distance, 0) / recommendations.length)
                : 0} km
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Clock className="h-4 w-4 text-purple-600" />
              Active Recommendations
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{recommendations.length}</div>
          </CardContent>
        </Card>
      </div>

      {/* Recommendations Table */}
      <Card>
        <CardHeader>
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <CardTitle>Dispatch Recommendations</CardTitle>
              <CardDescription>ML-powered contractor assignments</CardDescription>
            </div>
            <ExportButton
              data={filteredRecommendations}
              columns={exportColumns}
              filename={`dispatch-recommendations-${format(new Date(), "yyyy-MM-dd")}`}
              title="Dispatch Recommendations 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 contractors or locations..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9"
            />
          </div>

          {/* Recommendations 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">Job ID</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Contractor</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Location</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Distance</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Skill Match</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Priority</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Actions</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>
                  ) : filteredRecommendations.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                        No dispatch recommendations found
                      </td>
                    </tr>
                  ) : (
                    filteredRecommendations.map((rec) => (
                      <tr key={rec.id} className="hover:bg-muted/30">
                        <td className="px-4 py-3 text-sm font-medium">{rec.jobId}</td>
                        <td className="px-4 py-3 text-sm">{rec.contractorName}</td>
                        <td className="px-4 py-3 text-sm">
                          <div className="flex items-center gap-2">
                            <MapPin className="h-4 w-4 text-muted-foreground" />
                            {rec.location}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm">{rec.distance} km</td>
                        <td className="px-4 py-3 text-sm">
                          <div className="flex items-center gap-2">
                            <div className="w-16 bg-gray-200 rounded-full h-2">
                              <div 
                                className="bg-blue-600 h-2 rounded-full" 
                                style={{ width: `${rec.skillMatch}%` }}
                              />
                            </div>
                            <span className="text-xs font-medium">{rec.skillMatch}%</span>
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          {getPriorityBadge(rec.priority)}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <Button
                              variant="default"
                              size="sm"
                              onClick={() => assignContractor(rec.jobId, rec.id)}
                            >
                              <Navigation className="h-4 w-4 mr-1" />
                              Assign
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => createCalendarEvent(rec)}
                            >
                              <CalendarIcon className="h-4 w-4" />
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
