
"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { 
  AlertTriangle, 
  CheckCircle2, 
  Clock, 
  Search,
  Calendar,
  Mail
} from "lucide-react";
import { DateRange } from "react-day-picker";
import { format } from "date-fns";

interface BadgeRenewal {
  id: string;
  contractorName: string;
  badgeType: string;
  expiryDate: string;
  status: "critical" | "warning" | "ok";
  daysUntilExpiry: number;
  region: string;
  email: string;
}

export function BadgeRenewalDashboard({ 
  dateRange, 
  region 
}: { 
  dateRange: DateRange | undefined;
  region: string;
}) {
  const [renewals, setRenewals] = useState<BadgeRenewal[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

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

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

  const sendReminder = async (renewalId: string, email: string) => {
    try {
      const res = await fetch(`/api/badges/renewals/${renewalId}/remind`, {
        method: "POST",
      });
      
      if (!res.ok) throw new Error("Failed to send reminder");
      toast.success("Reminder sent successfully");
    } catch (error) {
      toast.error("Failed to send reminder");
    }
  };

  const filteredRenewals = renewals.filter(renewal => {
    const matchesSearch = renewal.contractorName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         renewal.badgeType.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === "all" || renewal.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const stats = {
    critical: renewals.filter(r => r.status === "critical").length,
    warning: renewals.filter(r => r.status === "warning").length,
    ok: renewals.filter(r => r.status === "ok").length,
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      critical: { variant: "destructive" as const, icon: AlertTriangle, label: "Critical" },
      warning: { variant: "default" as const, icon: Clock, label: "Warning" },
      ok: { variant: "secondary" as const, icon: CheckCircle2, label: "OK" },
    };
    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: "Contractor", key: "contractorName" },
    { header: "Badge Type", key: "badgeType" },
    { header: "Expiry Date", key: "expiryDate" },
    { header: "Days Until Expiry", key: "daysUntilExpiry" },
    { header: "Status", key: "status" },
    { header: "Region", key: "region" },
    { header: "Email", key: "email" },
  ];

  return (
    <div className="space-y-6">
      {/* Stats Overview */}
      <div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
        <Card className="border-red-200 bg-red-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <AlertTriangle className="h-4 w-4 text-red-600" />
              Critical
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.critical}</div>
            <p className="text-xs text-muted-foreground mt-1">Expiring within 7 days</p>
          </CardContent>
        </Card>

        <Card className="border-orange-200 bg-orange-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Clock className="h-4 w-4 text-orange-600" />
              Warning
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">{stats.warning}</div>
            <p className="text-xs text-muted-foreground mt-1">Expiring within 30 days</p>
          </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">
              <CheckCircle2 className="h-4 w-4 text-green-600" />
              OK
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.ok}</div>
            <p className="text-xs text-muted-foreground mt-1">Valid for 30+ days</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters and Export */}
      <Card>
        <CardHeader>
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <CardTitle>Badge Renewals</CardTitle>
              <CardDescription>Monitor and manage contractor badge expirations</CardDescription>
            </div>
            <ExportButton
              data={filteredRenewals}
              columns={exportColumns}
              filename={`badge-renewals-${format(new Date(), "yyyy-MM-dd")}`}
              title="Badge Renewal Report"
            />
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Search and Filter */}
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search contractors or badge types..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-[180px]">
                <SelectValue placeholder="Filter by status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                <SelectItem value="critical">Critical</SelectItem>
                <SelectItem value="warning">Warning</SelectItem>
                <SelectItem value="ok">OK</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Renewals 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">Contractor</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Badge Type</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Expiry Date</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Days Left</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Status</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={6} className="px-4 py-8 text-center text-muted-foreground">
                        Loading...
                      </td>
                    </tr>
                  ) : filteredRenewals.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
                        No badge renewals found
                      </td>
                    </tr>
                  ) : (
                    filteredRenewals.map((renewal) => (
                      <tr key={renewal.id} className="hover:bg-muted/30">
                        <td className="px-4 py-3 text-sm font-medium">{renewal.contractorName}</td>
                        <td className="px-4 py-3 text-sm">{renewal.badgeType}</td>
                        <td className="px-4 py-3 text-sm">
                          <div className="flex items-center gap-2">
                            <Calendar className="h-4 w-4 text-muted-foreground" />
                            {format(new Date(renewal.expiryDate), "MMM dd, yyyy")}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm font-medium">
                          {renewal.daysUntilExpiry} days
                        </td>
                        <td className="px-4 py-3">
                          {getStatusBadge(renewal.status)}
                        </td>
                        <td className="px-4 py-3">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => sendReminder(renewal.id, renewal.email)}
                          >
                            <Mail className="h-4 w-4 mr-1" />
                            Remind
                          </Button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
