
"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 { Progress } from "@/components/ui/progress";
import { toast } from "sonner";
import { 
  Users, 
  CheckCircle2, 
  Clock, 
  Search,
  UserPlus,
  TrendingUp
} from "lucide-react";
import { DateRange } from "react-day-picker";
import { format } from "date-fns";

interface PartnerOnboarding {
  id: string;
  partnerName: string;
  email: string;
  startDate: string;
  progress: number;
  status: "pending" | "in_progress" | "completed";
  stepsCompleted: number;
  totalSteps: number;
  region: string;
}

export function PartnerOnboardingDashboard({ 
  dateRange, 
  region 
}: { 
  dateRange: DateRange | undefined;
  region: string;
}) {
  const [partners, setPartners] = useState<PartnerOnboarding[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

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

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

  const sendWelcomeEmail = async (partnerId: string, email: string) => {
    try {
      const res = await fetch(`/api/partners/onboarding/${partnerId}/welcome`, {
        method: "POST",
      });
      
      if (!res.ok) throw new Error("Failed to send welcome email");
      toast.success("Welcome email sent");
    } catch (error) {
      toast.error("Failed to send welcome email");
    }
  };

  const filteredPartners = partners.filter(partner => 
    partner.partnerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    partner.email.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = {
    total: partners.length,
    pending: partners.filter(p => p.status === "pending").length,
    inProgress: partners.filter(p => p.status === "in_progress").length,
    completed: partners.filter(p => p.status === "completed").length,
    avgProgress: partners.length > 0 
      ? Math.round(partners.reduce((sum, p) => sum + p.progress, 0) / partners.length)
      : 0,
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      pending: { variant: "secondary" as const, label: "Pending" },
      in_progress: { variant: "default" as const, label: "In Progress" },
      completed: { variant: "secondary" as const, label: "Completed" },
    };
    const config = variants[status as keyof typeof variants];
    return <Badge variant={config?.variant}>{config?.label}</Badge>;
  };

  const exportColumns = [
    { header: "Partner Name", key: "partnerName" },
    { header: "Email", key: "email" },
    { header: "Start Date", key: "startDate" },
    { header: "Progress (%)", key: "progress" },
    { header: "Steps Completed", key: "stepsCompleted" },
    { header: "Total Steps", key: "totalSteps" },
    { 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">
              <Users className="h-4 w-4 text-blue-600" />
              Total Partners
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
          </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" />
              Pending
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">{stats.pending}</div>
          </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">
              <TrendingUp className="h-4 w-4 text-blue-600" />
              In Progress
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{stats.inProgress}</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">
              <CheckCircle2 className="h-4 w-4 text-green-600" />
              Completed
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.completed}</div>
          </CardContent>
        </Card>
      </div>

      {/* Partners Table */}
      <Card>
        <CardHeader>
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <CardTitle>Partner Onboarding</CardTitle>
              <CardDescription>Track new partner setup and training progress</CardDescription>
            </div>
            <ExportButton
              data={filteredPartners}
              columns={exportColumns}
              filename={`partner-onboarding-${format(new Date(), "yyyy-MM-dd")}`}
              title="Partner Onboarding 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 partners..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9"
            />
          </div>

          {/* Partners 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">Partner</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Email</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Start Date</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Progress</th>
                    <th className="px-4 py-3 text-left text-sm font-medium">Steps</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={7} className="px-4 py-8 text-center text-muted-foreground">
                        Loading...
                      </td>
                    </tr>
                  ) : filteredPartners.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                        No partners found
                      </td>
                    </tr>
                  ) : (
                    filteredPartners.map((partner) => (
                      <tr key={partner.id} className="hover:bg-muted/30">
                        <td className="px-4 py-3 text-sm font-medium">{partner.partnerName}</td>
                        <td className="px-4 py-3 text-sm">{partner.email}</td>
                        <td className="px-4 py-3 text-sm">
                          {format(new Date(partner.startDate), "MMM dd, yyyy")}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-3">
                            <Progress value={partner.progress} className="w-24" />
                            <span className="text-sm font-medium">{partner.progress}%</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm">
                          {partner.stepsCompleted} / {partner.totalSteps}
                        </td>
                        <td className="px-4 py-3">
                          {getStatusBadge(partner.status)}
                        </td>
                        <td className="px-4 py-3">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => sendWelcomeEmail(partner.id, partner.email)}
                          >
                            <UserPlus className="h-4 w-4 mr-1" />
                            Welcome
                          </Button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
