import { useState } 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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import {
  AlertTriangle,
  Heart,
  Clock,
  Calendar,
  Plus,
  Edit,
  CheckCircle,
  XCircle,
  Activity,
  FileText,
  TrendingUp,
  User
} from "lucide-react";

interface Injury {
  id: number;
  playerId: number;
  playerName: string;
  injuryType: string;
  bodyPart: string;
  severity: "minor" | "moderate" | "severe";
  status: "active" | "recovering" | "healed";
  dateOccurred: string;
  expectedRecovery: string;
  description: string;
  treatment: string;
  medicalStaff: string;
}

interface Treatment {
  id: number;
  injuryId: number;
  date: string;
  type: string;
  description: string;
  provider: string;
  notes: string;
}

export default function Injuries() {
  const [selectedStatus, setSelectedStatus] = useState("");
  const [selectedSeverity, setSelectedSeverity] = useState("");
  const [showAddInjury, setShowAddInjury] = useState(false);
  const [selectedInjury, setSelectedInjury] = useState<Injury | null>(null);
  const [showTreatmentDialog, setShowTreatmentDialog] = useState(false);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Fetch players for dropdown
  const { data: players = [] } = useQuery({
    queryKey: ["/api/players"],
  });

  // Mock injury data
  const { data: injuries = [], isLoading } = useQuery({
    queryKey: ["/api/injuries"],
    queryFn: async () => {
      return [
        {
          id: 1,
          playerId: 22,
          playerName: "John Doe",
          injuryType: "Muscle Strain",
          bodyPart: "Hamstring",
          severity: "moderate",
          status: "recovering",
          dateOccurred: "2024-12-10",
          expectedRecovery: "2025-01-15",
          description: "Grade 2 hamstring strain during training session",
          treatment: "Rest, physiotherapy, gradual return to training",
          medicalStaff: "Dr. Sarah Wilson"
        },
        {
          id: 2,
          playerId: 23,
          playerName: "Jane Smith",
          injuryType: "Sprain",
          bodyPart: "Ankle",
          severity: "minor",
          status: "healed",
          dateOccurred: "2024-11-28",
          expectedRecovery: "2024-12-15",
          description: "Minor ankle sprain during match",
          treatment: "Ice, compression, elevation, physiotherapy",
          medicalStaff: "Dr. Michael Brown"
        },
        {
          id: 3,
          playerId: 24,
          playerName: "Mike Johnson",
          injuryType: "Fracture",
          bodyPart: "Wrist",
          severity: "severe",
          status: "active",
          dateOccurred: "2024-12-20",
          expectedRecovery: "2025-03-01",
          description: "Hairline fracture in left wrist",
          treatment: "Cast immobilization, regular monitoring",
          medicalStaff: "Dr. Sarah Wilson"
        }
      ];
    },
  });

  const { data: treatments = [] } = useQuery({
    queryKey: ["/api/treatments", selectedInjury?.id],
    queryFn: async () => {
      if (!selectedInjury) return [];
      return [
        {
          id: 1,
          injuryId: selectedInjury.id,
          date: "2024-12-15",
          type: "Physiotherapy",
          description: "Range of motion exercises",
          provider: "Physical Therapist",
          notes: "Good progress, continue current program"
        },
        {
          id: 2,
          injuryId: selectedInjury.id,
          date: "2024-12-22",
          type: "Medical Checkup",
          description: "Progress assessment",
          provider: "Dr. Sarah Wilson",
          notes: "Healing well, can increase activity level"
        }
      ];
    },
    enabled: !!selectedInjury
  });

  const addInjuryMutation = useMutation({
    mutationFn: async (data: any) => {
      await apiRequest("POST", "/api/injuries", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/injuries"] });
      toast({
        title: "Success",
        description: "Injury record added successfully",
      });
      setShowAddInjury(false);
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to add injury record",
        variant: "destructive",
      });
    },
  });

  const filteredInjuries = injuries.filter(injury => {
    const statusMatch = selectedStatus ? injury.status === selectedStatus : true;
    const severityMatch = selectedSeverity ? injury.severity === selectedSeverity : true;
    return statusMatch && severityMatch;
  });

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case "minor": return "bg-yellow-500";
      case "moderate": return "bg-orange-500";
      case "severe": return "bg-red-500";
      default: return "bg-gray-500";
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "active": return "bg-red-500";
      case "recovering": return "bg-yellow-500";
      case "healed": return "bg-green-500";
      default: return "bg-gray-500";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "active": return <XCircle className="h-4 w-4" />;
      case "recovering": return <Clock className="h-4 w-4" />;
      case "healed": return <CheckCircle className="h-4 w-4" />;
      default: return <Activity className="h-4 w-4" />;
    }
  };

  const getDaysUntilRecovery = (expectedDate: string) => {
    const today = new Date();
    const recovery = new Date(expectedDate);
    const diffTime = recovery.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Injury Management</h1>
          <p className="text-gray-600">Track and manage player injuries and recovery</p>
        </div>
        <Button onClick={() => setShowAddInjury(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Report Injury
        </Button>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Active Injuries</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <XCircle className="h-8 w-8 text-red-500" />
              <span className="text-3xl font-bold">
                {injuries.filter(i => i.status === "active").length}
              </span>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Recovering</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <Clock className="h-8 w-8 text-yellow-500" />
              <span className="text-3xl font-bold">
                {injuries.filter(i => i.status === "recovering").length}
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Healed (This Month)</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <CheckCircle className="h-8 w-8 text-green-500" />
              <span className="text-3xl font-bold">
                {injuries.filter(i => i.status === "healed").length}
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Avg Recovery Time</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <TrendingUp className="h-8 w-8 text-blue-500" />
              <span className="text-3xl font-bold">21</span>
              <span className="text-sm text-gray-600">days</span>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <AlertTriangle className="h-5 w-5 mr-2" />
            Injury Filters
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="status-filter">Status</Label>
              <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                <SelectTrigger>
                  <SelectValue placeholder="All statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All statuses</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="recovering">Recovering</SelectItem>
                  <SelectItem value="healed">Healed</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="severity-filter">Severity</Label>
              <Select value={selectedSeverity} onValueChange={setSelectedSeverity}>
                <SelectTrigger>
                  <SelectValue placeholder="All severities" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All severities</SelectItem>
                  <SelectItem value="minor">Minor</SelectItem>
                  <SelectItem value="moderate">Moderate</SelectItem>
                  <SelectItem value="severe">Severe</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-end">
              <Button variant="outline" onClick={() => {
                setSelectedStatus("");
                setSelectedSeverity("");
              }}>
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Injuries List */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {filteredInjuries.map((injury) => (
          <Card key={injury.id} className="hover:shadow-md transition-shadow">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center">
                  <User className="h-5 w-5 mr-2" />
                  {injury.playerName}
                </CardTitle>
                <div className="flex space-x-2">
                  <Badge className={getSeverityColor(injury.severity)}>
                    {injury.severity}
                  </Badge>
                  <Badge className={getStatusColor(injury.status)}>
                    {getStatusIcon(injury.status)}
                    <span className="ml-1">{injury.status}</span>
                  </Badge>
                </div>
              </div>
              <CardDescription>
                {injury.injuryType} - {injury.bodyPart}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="text-sm text-gray-600">
                <p><strong>Occurred:</strong> {new Date(injury.dateOccurred).toLocaleDateString()}</p>
                <p><strong>Expected Recovery:</strong> {new Date(injury.expectedRecovery).toLocaleDateString()}</p>
                {injury.status !== "healed" && (
                  <p><strong>Days Remaining:</strong> {getDaysUntilRecovery(injury.expectedRecovery)}</p>
                )}
                <p><strong>Medical Staff:</strong> {injury.medicalStaff}</p>
              </div>
              
              <div className="text-sm">
                <p><strong>Description:</strong> {injury.description}</p>
              </div>

              <div className="flex space-x-2">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => {
                    setSelectedInjury(injury);
                    setShowTreatmentDialog(true);
                  }}
                >
                  <FileText className="h-4 w-4 mr-1" />
                  View Treatments
                </Button>
                <Button variant="outline" size="sm">
                  <Edit className="h-4 w-4 mr-1" />
                  Update
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Add Injury Dialog */}
      <Dialog open={showAddInjury} onOpenChange={setShowAddInjury}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Report New Injury</DialogTitle>
            <DialogDescription>
              Record a new injury for tracking and management
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="player">Player</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select player" />
                </SelectTrigger>
                <SelectContent>
                  {players.map((player: any) => (
                    <SelectItem key={player.id} value={player.id.toString()}>
                      {player.firstName} {player.lastName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="injuryType">Injury Type</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select injury type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Muscle Strain">Muscle Strain</SelectItem>
                  <SelectItem value="Sprain">Sprain</SelectItem>
                  <SelectItem value="Fracture">Fracture</SelectItem>
                  <SelectItem value="Contusion">Contusion</SelectItem>
                  <SelectItem value="Concussion">Concussion</SelectItem>
                  <SelectItem value="Dislocation">Dislocation</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="bodyPart">Body Part</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select body part" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Head">Head</SelectItem>
                  <SelectItem value="Neck">Neck</SelectItem>
                  <SelectItem value="Shoulder">Shoulder</SelectItem>
                  <SelectItem value="Arm">Arm</SelectItem>
                  <SelectItem value="Wrist">Wrist</SelectItem>
                  <SelectItem value="Hand">Hand</SelectItem>
                  <SelectItem value="Back">Back</SelectItem>
                  <SelectItem value="Chest">Chest</SelectItem>
                  <SelectItem value="Abdomen">Abdomen</SelectItem>
                  <SelectItem value="Hip">Hip</SelectItem>
                  <SelectItem value="Thigh">Thigh</SelectItem>
                  <SelectItem value="Knee">Knee</SelectItem>
                  <SelectItem value="Shin">Shin</SelectItem>
                  <SelectItem value="Calf">Calf</SelectItem>
                  <SelectItem value="Ankle">Ankle</SelectItem>
                  <SelectItem value="Foot">Foot</SelectItem>
                  <SelectItem value="Hamstring">Hamstring</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="severity">Severity</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select severity" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="minor">Minor</SelectItem>
                  <SelectItem value="moderate">Moderate</SelectItem>
                  <SelectItem value="severe">Severe</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="dateOccurred">Date Occurred</Label>
              <Input type="date" />
            </div>
            <div>
              <Label htmlFor="expectedRecovery">Expected Recovery</Label>
              <Input type="date" />
            </div>
            <div className="md:col-span-2">
              <Label htmlFor="description">Description</Label>
              <Textarea placeholder="Describe the injury and circumstances" />
            </div>
            <div className="md:col-span-2">
              <Label htmlFor="treatment">Treatment Plan</Label>
              <Textarea placeholder="Initial treatment and recovery plan" />
            </div>
            <div>
              <Label htmlFor="medicalStaff">Medical Staff</Label>
              <Input placeholder="Attending physician/therapist" />
            </div>
            <div className="md:col-span-2 flex space-x-2">
              <Button onClick={() => setShowAddInjury(false)} variant="outline" className="flex-1">
                Cancel
              </Button>
              <Button className="flex-1">
                Report Injury
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Treatment History Dialog */}
      <Dialog open={showTreatmentDialog} onOpenChange={setShowTreatmentDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>Treatment History</DialogTitle>
            <DialogDescription>
              {selectedInjury?.playerName} - {selectedInjury?.injuryType}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {treatments.map((treatment) => (
              <Card key={treatment.id}>
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-lg">{treatment.type}</CardTitle>
                    <Badge variant="outline">
                      {new Date(treatment.date).toLocaleDateString()}
                    </Badge>
                  </div>
                  <CardDescription>{treatment.provider}</CardDescription>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600 mb-2">{treatment.description}</p>
                  <p className="text-sm"><strong>Notes:</strong> {treatment.notes}</p>
                </CardContent>
              </Card>
            ))}
            <Button className="w-full">
              <Plus className="h-4 w-4 mr-2" />
              Add Treatment Session
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}