import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { getCurrentISOWeek } from "@/lib/utils";
// Sidebar handled in App.tsx
// import Sidebar from "@/components/layout/sidebar";
import AddActivityModal from "@/components/modals/add-activity-modal";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Plus, Download, Edit, Eye, Filter, TrendingUp, Calendar, Target, DollarSign, RefreshCw } from "lucide-react";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import type { Trainer, NewHire, Activity } from "@shared/schema";
import { getTrainingPairName } from "@/lib/historical-report-data";

export default function Activities() {
  const [showAddActivity, setShowAddActivity] = useState(false);
  const [selectedWeek, setSelectedWeek] = useState("all");
  const [selectedPair, setSelectedPair] = useState("all");
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: activities = [], isLoading: activitiesLoading } = useQuery<Activity[]>({
    queryKey: ["/api/activities"],
    staleTime: 5 * 60 * 1000, // Data is fresh for 5 minutes
    gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes
    refetchOnWindowFocus: false, // Don't refetch when window regains focus
    refetchInterval: false, // Disable automatic refetching
  });

  const { data: trainers = [], isLoading: trainersLoading } = useQuery<Trainer[]>({
    queryKey: ["/api/trainers"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
  });

  const { data: newHires = [], isLoading: hiresLoading } = useQuery<NewHire[]>({
    queryKey: ["/api/new-hires"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
  });

  // The active roster is kept separate from the historical roster. The
  // former feeds the activity-entry modal; the latter is needed to resolve
  // pair ids for records logged before a Prime Rep graduated.
  const {
    data: historicalNewHires = [],
    isLoading: historicalHiresLoading,
  } = useQuery<NewHire[]>({
    queryKey: ["/api/new-hires?includeGraduated=true"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
  });

  const activeNewHires = newHires.filter((hire) => !hire.graduatedAt);
  const isLoading = activitiesLoading || trainersLoading || hiresLoading || historicalHiresLoading;

  const handleRefresh = () => {
    queryClient.invalidateQueries({ queryKey: ["/api/activities"] });
    queryClient.invalidateQueries({ queryKey: ["/api/trainers"] });
    queryClient.invalidateQueries({ queryKey: ["/api/new-hires"] });
    queryClient.invalidateQueries({ queryKey: ["/api/new-hires?includeGraduated=true"] });
    toast({
      title: "Refreshing",
      description: "Updating activity data...",
    });
  };

  const getPairNames = (pairId: string) => {
    if (!pairId) return 'No Pair ID';

    return getTrainingPairName(pairId, trainers, historicalNewHires);
  };

  const getUniqueWeeks = () => {
    const weeks = Array.from(new Set(activities.map(a => a.week))).filter(week => week && week.trim() !== '').sort().reverse();
    return weeks;
  };

  const getUniquePairs = () => {
    const pairs = Array.from(new Set(activities.map(a => a.pairId))).filter(pairId => pairId && pairId.trim() !== '');
    return pairs.map(pairId => ({
      id: pairId,
      name: getPairNames(pairId)
    }));
  };

  const filteredActivities = activities.filter(activity => {
    const weekMatch = selectedWeek === "all" || activity.week === selectedWeek;
    const pairMatch = selectedPair === "all" || activity.pairId === selectedPair;
    return weekMatch && pairMatch;
  });

  const totalMetrics = filteredActivities.reduce(
    (acc, activity) => ({
      doors: acc.doors + (activity.doors || 0),
      appointments: acc.appointments + (activity.appointments || 0),
      loisSigned: acc.loisSigned + (activity.loisSigned || 0),
      contractsSigned: acc.contractsSigned + (activity.contractsSigned || 0),
      kwSold: acc.kwSold + (activity.kwSold || 0),
    }),
    { doors: 0, appointments: 0, loisSigned: 0, contractsSigned: 0, kwSold: 0 }
  );

  const deleteActivity = useMutation({
    mutationFn: (id: string) => apiRequest("DELETE", `/api/activities/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/activities"] });
      toast({
        title: "Success",
        description: "Activity deleted successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete activity",
        variant: "destructive",
      });
    },
  });

  const handleExport = () => {
    const csvContent = [
      ['Training Pair', 'Week', 'Doors', 'Appointments', 'LOIs Signed', 'Contracts Signed', 'KWs Sold', 'Notes'],
      ...filteredActivities.map(activity => [
        getPairNames(activity.pairId),
        activity.week,
        activity.doors || 0,
        activity.appointments || 0,
        activity.loisSigned || 0,
        activity.contractsSigned || 0,
        activity.kwSold || 0,
        activity.notes || ''
      ])
    ].map(row => row.join(',')).join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `activities_${selectedWeek}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  if (isLoading) {
    return (
      <div className="flex h-screen">
        {/* <Sidebar /> */}
        <div className="flex-1 p-6">
          <div className="animate-pulse">Loading activities...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 overflow-auto">
        <header className="bg-card border-b border-border px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-2xl font-bold text-foreground">Training Activities</h2>
              <p className="text-muted-foreground">Track and analyze training performance metrics</p>
            </div>
            <div className="flex items-center space-x-4">
              <Button
                data-testid="refresh-activities-button"
                variant="secondary"
                onClick={handleRefresh}
                size="sm"
                className="bg-white dark:bg-gray-700 text-gray-900 dark:text-white border border-gray-400 dark:border-gray-500 hover:bg-gray-100 dark:hover:bg-gray-600"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                Refresh
              </Button>
              <Button
                data-testid="export-activities-button"
                variant="outline"
                onClick={handleExport}
              >
                <Download className="w-4 h-4 mr-2" />
                Export
              </Button>
              <Button
                data-testid="add-activity-page-button"
                onClick={() => setShowAddActivity(true)}
              >
                <Plus className="w-4 h-4 mr-2" />
                Log Activity
              </Button>
            </div>
          </div>
        </header>

        <main className="p-6">
          {/* Summary Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
            <Card className="bg-card border border-border card-hover shimmer-effect" data-testid="metric-doors">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center animate-bounce-gentle">
                    <Target className="w-5 h-5 text-orange-600" />
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Total Doors</p>
                    <p className="text-2xl font-bold text-foreground">{totalMetrics.doors}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-card border border-border card-hover shimmer-effect" data-testid="metric-appointments">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center animate-bounce-gentle">
                    <Calendar className="w-5 h-5 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Appointments</p>
                    <p className="text-2xl font-bold text-foreground">{totalMetrics.appointments}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-card border border-border card-hover shimmer-effect" data-testid="metric-lois">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center animate-bounce-gentle">
                    <TrendingUp className="w-5 h-5 text-purple-600" />
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">LOIs Signed</p>
                    <p className="text-2xl font-bold text-foreground">{totalMetrics.loisSigned}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-card border border-border" data-testid="metric-contracts">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <TrendingUp className="w-5 h-5 text-green-600" />
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Contracts Signed</p>
                    <p className="text-2xl font-bold text-foreground">{totalMetrics.contractsSigned}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-card border border-border" data-testid="metric-kw-sold">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <DollarSign className="w-5 h-5 text-green-600" />
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">KWs Sold</p>
                    <p className="text-2xl font-bold text-foreground">{totalMetrics.kwSold.toLocaleString()}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Filters */}
          <Card className="mb-6">
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Filter className="w-5 h-5" />
                <span>Filters</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-4">
                <div className="flex items-center space-x-2">
                  <label className="text-sm font-medium">Week:</label>
                  <Select value={selectedWeek} onValueChange={setSelectedWeek}>
                    <SelectTrigger data-testid="week-filter" className="w-40">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Weeks</SelectItem>
                      {getUniqueWeeks().map(week => (
                        <SelectItem key={week} value={week}>{week}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="flex items-center space-x-2">
                  <label className="text-sm font-medium">Training Pair:</label>
                  <Select value={selectedPair} onValueChange={setSelectedPair}>
                    <SelectTrigger data-testid="pair-filter" className="w-60">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Pairs</SelectItem>
                      {getUniquePairs().map(pair => (
                        <SelectItem key={pair.id} value={pair.id}>{pair.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Activities Table */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>Activity Records</CardTitle>
                <Badge variant="secondary" data-testid="activity-count">
                  {filteredActivities.length} activities
                </Badge>
              </div>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Training Pair</TableHead>
                      <TableHead>Week</TableHead>
                      <TableHead className="text-right">Doors</TableHead>
                      <TableHead className="text-right">Appointments</TableHead>
                      <TableHead className="text-right">LOIs Signed</TableHead>
                      <TableHead className="text-right">Contracts</TableHead>
                      <TableHead className="text-right">KWs Sold</TableHead>
                      <TableHead>Notes</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredActivities.map((activity) => (
                      <TableRow key={activity.id} className="hover:bg-muted/30" data-testid={`activity-row-${activity.id}`}>
                        <TableCell>
                          <div className="flex items-center space-x-3">
                            <div className="flex -space-x-1">
                              <div className="w-6 h-6 bg-accent rounded-full border border-background"></div>
                              <div className="w-6 h-6 bg-primary rounded-full border border-background"></div>
                            </div>
                            <span className="font-medium">{getPairNames(activity.pairId)}</span>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">{activity.week}</Badge>
                        </TableCell>
                        <TableCell className="text-right font-medium">{activity.doors}</TableCell>
                        <TableCell className="text-right font-medium">{activity.appointments}</TableCell>
                        <TableCell className="text-right font-medium">{activity.loisSigned}</TableCell>
                        <TableCell className="text-right font-medium">{activity.contractsSigned}</TableCell>
                        <TableCell className="text-right">
                          <span className="font-medium text-green-600">
                            {(activity.kwSold || 0).toLocaleString()}
                          </span>
                        </TableCell>
                        <TableCell className="max-w-xs">
                          <div className="truncate" title={activity.notes || ""}>
                            {activity.notes || "No notes"}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-2">
                            <button 
                              data-testid={`edit-activity-${activity.id}`}
                              className="text-accent hover:text-accent/80 p-1"
                            >
                              <Edit className="w-4 h-4" />
                            </button>
                            <button 
                              data-testid={`view-activity-${activity.id}`}
                              className="text-muted-foreground hover:text-foreground p-1"
                            >
                              <Eye className="w-4 h-4" />
                            </button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                    
                    {filteredActivities.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                          <div>
                            <Target className="w-12 h-12 mx-auto mb-4 text-muted-foreground/50" />
                            <p className="text-lg font-medium mb-2">No activities found</p>
                            <p className="text-sm">
                              {selectedWeek !== "all" || selectedPair !== "all" 
                                ? "Try adjusting your filters or log new activities"
                                : "Start logging training activities to see data here"
                              }
                            </p>
                          </div>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </main>

        <AddActivityModal 
          open={showAddActivity}
          onOpenChange={setShowAddActivity}
          trainers={trainers}
          newHires={activeNewHires}
          selectedWeek={selectedWeek === "all" ? getCurrentISOWeek() : selectedWeek}
        />
      </div>
    );
}
