import React, { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest } from "@/lib/queryClient";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
import { 
  Play, 
  Square, 
  Clock, 
  Users, 
  TrendingUp, 
  MessageSquare, 
  BarChart3,
  Plus,
  Eye,
  Timer,
  Download,
  Filter
} from "lucide-react";
import { format } from "date-fns";

interface CoachingFeedbackReaction {
  id: number;
  name: string;
  emoji: string;
  category: string;
  color: string;
  isActive: boolean;
  sortOrder: number;
}

interface FeedbackSession {
  id: number;
  name: string;
  type: string;
  teamId?: number;
  coachId: string;
  startTime: Date;
  endTime?: Date;
  status: string;
  location?: string;
  description?: string;
  totalFeedbacks: number;
  participantCount: number;
  team?: {
    id: number;
    name: string;
  };
  coach: {
    id: string;
    firstName: string;
    lastName: string;
  };
}

interface PlayerFeedbackLog {
  id: number;
  playerId: number;
  coachId: string;
  reactionId: number;
  sessionType: string;
  sessionId?: number;
  context?: string;
  intensity: number;
  timestamp: Date;
  location?: string;
  tags?: string[];
  reaction: CoachingFeedbackReaction;
  player: {
    id: number;
    firstName: string;
    lastName: string;
  };
  coach: {
    id: string;
    firstName: string;
    lastName: string;
  };
}

interface Player {
  id: number;
  firstName: string;
  lastName: string;
  position?: string;
  jerseyNumber?: number;
}

export default function CoachingFeedbackPage() {
  const { toast } = useToast();
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [activeSession, setActiveSession] = useState<FeedbackSession | null>(null);
  const [selectedPlayer, setSelectedPlayer] = useState<Player | null>(null);
  const [feedbackContext, setFeedbackContext] = useState("");
  const [isSessionDialogOpen, setIsSessionDialogOpen] = useState(false);
  const [sessionType, setSessionType] = useState("");
  const [selectedTeam, setSelectedTeam] = useState<string>("");

  // Fetch coaching reactions
  const { data: reactions = [] } = useQuery<CoachingFeedbackReaction[]>({
    queryKey: ["/api/coaching-reactions?active=true"],
  });

  // Fetch active sessions
  const { data: activeSessions = [] } = useQuery<FeedbackSession[]>({
    queryKey: ["/api/feedback-sessions?active=true"],
    refetchInterval: 5000, // Refresh every 5 seconds
  });

  // Fetch all sessions
  const { data: allSessions = [] } = useQuery<FeedbackSession[]>({
    queryKey: ["/api/feedback-sessions"],
  });

  // Fetch teams
  const { data: teams = [] } = useQuery<any[]>({
    queryKey: ["/api/teams"],
  });

  // Fetch players (filtered by selected team if applicable)
  const { data: players = [] } = useQuery<Player[]>({
    queryKey: selectedTeam && selectedTeam !== "all" ? ["/api/teams", selectedTeam, "players"] : ["/api/players"],
  });

  // Fetch recent feedback logs
  const { data: recentFeedback = [] } = useQuery<PlayerFeedbackLog[]>({
    queryKey: [`/api/feedback-logs?startDate=${new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()}&endDate=${new Date().toISOString()}`],
  });

  // Create feedback log mutation
  const createFeedbackMutation = useMutation({
    mutationFn: (feedbackData: any) => 
      apiRequest("POST", "/api/feedback-logs", feedbackData).then(res => res.json()),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/feedback-logs"] });
      toast({
        title: "Feedback Recorded",
        description: "Player feedback has been logged successfully.",
      });
      setFeedbackContext("");
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to record feedback",
        variant: "destructive",
      });
    },
  });

  // Start session mutation
  const startSessionMutation = useMutation({
    mutationFn: (sessionData: any) => 
      apiRequest("POST", "/api/feedback-sessions", sessionData).then(res => res.json()),
    onSuccess: (newSession) => {
      queryClient.invalidateQueries({ queryKey: ["/api/feedback-sessions"] });
      queryClient.invalidateQueries({ queryKey: ["/api/feedback-sessions?active=true"] });
      setActiveSession(newSession);
      setIsSessionDialogOpen(false);
      setSessionType("");
      toast({
        title: "Session Started",
        description: "Feedback session has been started successfully.",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Failed to Start Session",
        description: error.message || "There was an error creating the session. Please try again.",
        variant: "destructive",
      });
    },
  });

  // End session mutation
  const endSessionMutation = useMutation({
    mutationFn: (sessionId: number) => 
      apiRequest("POST", `/api/feedback-sessions/${sessionId}/end`).then(res => res.json()),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/feedback-sessions"] });
      setActiveSession(null);
      toast({
        title: "Session Ended",
        description: "Feedback session has been ended successfully.",
      });
    },
  });

  const handleQuickFeedback = (reaction: CoachingFeedbackReaction, intensity: number = 1) => {
    if (!selectedPlayer) {
      toast({
        title: "Select Player",
        description: "Please select a player first.",
        variant: "destructive",
      });
      return;
    }

    const feedbackData = {
      playerId: selectedPlayer.id,
      reactionId: reaction.id,
      sessionType: activeSession?.type || 'training',
      sessionId: activeSession?.id,
      context: feedbackContext.trim() || null,
      intensity,
      location: activeSession?.location,
      tags: []
    };

    createFeedbackMutation.mutate(feedbackData);
  };

  // PDF Export function
  const exportToPDF = async () => {
    try {
      const element = document.getElementById('feedback-export-content');
      if (!element) {
        toast({
          title: "Export Error",
          description: "Could not find content to export",
          variant: "destructive",
        });
        return;
      }

      const canvas = await html2canvas(element, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
      });

      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      
      const imgWidth = 210;
      const pageHeight = 295;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      const teamName = selectedTeam ? teams.find(t => t.id.toString() === selectedTeam)?.name || 'All Teams' : 'All Teams';
      const fileName = `coaching-feedback-${teamName}-${format(new Date(), 'yyyy-MM-dd')}.pdf`;
      
      pdf.save(fileName);
      
      toast({
        title: "Export Successful",
        description: `Feedback report exported as ${fileName}`,
      });
    } catch (error) {
      toast({
        title: "Export Failed",
        description: "Failed to generate PDF export",
        variant: "destructive",
      });
    }
  };

  const startNewSession = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    
    if (!user || !(user as any).id) {
      toast({
        title: "Authentication Error",
        description: "You must be logged in to start a session.",
        variant: "destructive",
      });
      return;
    }

    if (!sessionType) {
      toast({
        title: "Missing Information",
        description: "Please select a session type.",
        variant: "destructive",
      });
      return;
    }

    const sessionData = {
      name: formData.get('name') as string,
      type: sessionType,
      teamId: formData.get('teamId') ? parseInt(formData.get('teamId') as string) : null,
      coachId: (user as any).id,
      startTime: new Date(),
      location: formData.get('location') as string,
      description: formData.get('description') as string,
      participantCount: formData.get('participantCount') ? parseInt(formData.get('participantCount') as string) : 0,
    };

    startSessionMutation.mutate(sessionData);
  };

  // Group reactions by category
  const reactionsByCategory = reactions.reduce((acc, reaction) => {
    if (!acc[reaction.category]) {
      acc[reaction.category] = [];
    }
    acc[reaction.category].push(reaction);
    return acc;
  }, {} as Record<string, CoachingFeedbackReaction[]>);

  const categoryColors = {
    positive: "bg-green-50 border-green-200",
    negative: "bg-red-50 border-red-200",
    neutral: "bg-blue-50 border-blue-200",
    instruction: "bg-yellow-50 border-yellow-200"
  };

  return (
    <div className="container mx-auto p-6 space-y-6" id="feedback-export-content">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Quick Reaction Coaching Feedback</h1>
          <p className="text-muted-foreground">Provide instant feedback during training and matches</p>
        </div>
        <div className="flex gap-2">
          <div className="flex items-center gap-2">
            <Filter className="h-4 w-4" />
            <Select value={selectedTeam} onValueChange={setSelectedTeam}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Select team" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Teams</SelectItem>
                {teams.map((team) => (
                  <SelectItem key={team.id} value={team.id.toString()}>
                    {team.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <Button onClick={exportToPDF} variant="outline" className="flex items-center gap-2">
            <Download className="h-4 w-4" />
            Export PDF
          </Button>
          <Dialog open={isSessionDialogOpen} onOpenChange={setIsSessionDialogOpen}>
            <DialogTrigger asChild>
              <Button className="flex items-center gap-2">
                <Plus className="h-4 w-4" />
                Start Session
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Start New Feedback Session</DialogTitle>
              </DialogHeader>
              <form onSubmit={startNewSession} className="space-y-4">
                <div>
                  <Label htmlFor="name">Session Name</Label>
                  <Input id="name" name="name" placeholder="Training Session - Morning" required />
                </div>
                <div>
                  <Label htmlFor="type">Session Type</Label>
                  <Select value={sessionType} onValueChange={setSessionType} required>
                    <SelectTrigger>
                      <SelectValue placeholder="Select session type" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="training">Training</SelectItem>
                      <SelectItem value="match">Match</SelectItem>
                      <SelectItem value="drill">Drill</SelectItem>
                      <SelectItem value="individual">Individual</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="location">Location</Label>
                  <Input id="location" name="location" placeholder="Main Field" />
                </div>
                <div>
                  <Label htmlFor="participantCount">Number of Participants</Label>
                  <Input id="participantCount" name="participantCount" type="number" min="1" defaultValue="20" />
                </div>
                <div>
                  <Label htmlFor="description">Description</Label>
                  <Textarea id="description" name="description" placeholder="Session objectives and notes..." />
                </div>
                <Button type="submit" className="w-full">
                  Start Session
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      <Tabs defaultValue="feedback" className="space-y-6">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="feedback">Quick Feedback</TabsTrigger>
          <TabsTrigger value="sessions">Sessions</TabsTrigger>
          <TabsTrigger value="history">Feedback History</TabsTrigger>
        </TabsList>

        <TabsContent value="feedback" className="space-y-6">
          {/* Session Status */}
          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    {activeSession ? (
                      <>
                        <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse" />
                        Live Session
                      </>
                    ) : (
                      <>
                        <div className="w-3 h-3 bg-gray-400 rounded-full" />
                        No Active Session
                      </>
                    )}
                  </CardTitle>
                  {activeSession && (
                    <CardDescription>
                      {activeSession.name} • {activeSession.location} • Started {format(new Date(activeSession.startTime), "HH:mm")}
                    </CardDescription>
                  )}
                </div>
                {activeSession && (
                  <Button 
                    variant="destructive" 
                    onClick={() => endSessionMutation.mutate(activeSession.id)}
                    disabled={endSessionMutation.isPending}
                  >
                    <Square className="h-4 w-4 mr-2" />
                    End Session
                  </Button>
                )}
              </div>
            </CardHeader>
          </Card>

          {/* Player Selection */}
          <Card>
            <CardHeader>
              <CardTitle>Select Player</CardTitle>
              <CardDescription>Choose a player to provide feedback to</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                {players.map((player) => (
                  <Button
                    key={player.id}
                    variant={selectedPlayer?.id === player.id ? "default" : "outline"}
                    onClick={() => setSelectedPlayer(player)}
                    className="h-auto p-3 flex flex-col items-center gap-1"
                  >
                    <div className="font-semibold">{player.firstName}</div>
                    <div className="text-sm text-muted-foreground">{player.lastName}</div>
                    {player.jerseyNumber && (
                      <Badge variant="secondary" className="text-xs">#{player.jerseyNumber}</Badge>
                    )}
                  </Button>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Context Input */}
          <Card>
            <CardHeader>
              <CardTitle>Additional Context (Optional)</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea
                placeholder="Add specific notes about the feedback situation..."
                value={feedbackContext}
                onChange={(e) => setFeedbackContext(e.target.value)}
                className="min-h-20"
              />
            </CardContent>
          </Card>

          {/* Quick Reaction Buttons */}
          <div className="space-y-4">
            {Object.entries(reactionsByCategory).map(([category, categoryReactions]) => (
              <Card key={category} className={categoryColors[category as keyof typeof categoryColors]}>
                <CardHeader className="pb-3">
                  <CardTitle className="text-lg capitalize">{category} Feedback</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                    {categoryReactions.map((reaction) => (
                      <div key={reaction.id} className="space-y-2">
                        <Button
                          onClick={() => handleQuickFeedback(reaction, 1)}
                          disabled={!selectedPlayer || createFeedbackMutation.isPending}
                          className="w-full h-auto p-4 flex flex-col items-center gap-2"
                          style={{ backgroundColor: reaction.color }}
                        >
                          <span className="text-2xl">{reaction.emoji}</span>
                          <span className="text-sm font-medium">{reaction.name}</span>
                        </Button>
                        
                        {/* Intensity buttons for important feedback */}
                        {(category === 'positive' || category === 'negative') && (
                          <div className="flex gap-1">
                            {[2, 3, 4, 5].map((intensity) => (
                              <Button
                                key={intensity}
                                size="sm"
                                variant="outline"
                                onClick={() => handleQuickFeedback(reaction, intensity)}
                                disabled={!selectedPlayer || createFeedbackMutation.isPending}
                                className="flex-1 text-xs"
                              >
                                {intensity}x
                              </Button>
                            ))}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="sessions" className="space-y-6">
          <div className="grid gap-4">
            <div>
              <h3 className="text-lg font-semibold mb-3">Active Sessions</h3>
              {activeSessions.length === 0 ? (
                <Card>
                  <CardContent className="p-6 text-center text-muted-foreground">
                    No active feedback sessions
                  </CardContent>
                </Card>
              ) : (
                <div className="grid gap-4">
                  {activeSessions.map((session) => (
                    <Card key={session.id}>
                      <CardContent className="p-4">
                        <div className="flex justify-between items-start">
                          <div>
                            <h4 className="font-semibold">{session.name}</h4>
                            <p className="text-sm text-muted-foreground">
                              {session.type} • {session.location} • {session.participantCount} participants
                            </p>
                            <p className="text-sm text-muted-foreground">
                              Started {format(new Date(session.startTime), "PPP 'at' HH:mm")}
                            </p>
                          </div>
                          <div className="flex items-center gap-2">
                            <Badge variant="secondary">
                              {session.totalFeedbacks} feedback(s)
                            </Badge>
                            <Button 
                              size="sm" 
                              onClick={() => setActiveSession(session)}
                            >
                              <Eye className="h-4 w-4 mr-2" />
                              View
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </div>

            <Separator />

            <div>
              <h3 className="text-lg font-semibold mb-3">Recent Sessions</h3>
              <div className="grid gap-4">
                {allSessions.slice(0, 10).map((session) => (
                  <Card key={session.id}>
                    <CardContent className="p-4">
                      <div className="flex justify-between items-start">
                        <div>
                          <h4 className="font-semibold">{session.name}</h4>
                          <p className="text-sm text-muted-foreground">
                            {session.type} • {session.location} • {session.participantCount} participants
                          </p>
                          <p className="text-sm text-muted-foreground">
                            {format(new Date(session.startTime), "PPP 'at' HH:mm")}
                            {session.endTime && ` - ${format(new Date(session.endTime), "HH:mm")}`}
                          </p>
                        </div>
                        <div className="flex items-center gap-2">
                          <Badge variant={session.status === 'active' ? 'default' : 'secondary'}>
                            {session.status}
                          </Badge>
                          <Badge variant="outline">
                            {session.totalFeedbacks} feedback(s)
                          </Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="history" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Recent Feedback History</CardTitle>
              <CardDescription>Last 7 days of coaching feedback</CardDescription>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-96">
                <div className="space-y-4">
                  {recentFeedback.map((feedback) => (
                    <div key={feedback.id} className="flex items-start gap-3 p-3 border rounded-lg">
                      <span className="text-2xl">{feedback.reaction.emoji}</span>
                      <div className="flex-1">
                        <div className="flex justify-between items-start">
                          <div>
                            <p className="font-medium">
                              {feedback.player.firstName} {feedback.player.lastName}
                            </p>
                            <p className="text-sm text-muted-foreground">
                              {feedback.reaction.name} • Intensity: {feedback.intensity}
                            </p>
                            {feedback.context && (
                              <p className="text-sm mt-1">{feedback.context}</p>
                            )}
                          </div>
                          <div className="text-right">
                            <p className="text-sm text-muted-foreground">
                              {format(new Date(feedback.timestamp), "MMM d, HH:mm")}
                            </p>
                            <Badge variant="outline" className="text-xs">
                              {feedback.sessionType}
                            </Badge>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}