import { useState, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragOverlay, DragStartEvent, DragEndEvent, useDroppable } from "@dnd-kit/core";
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, rectSortingStrategy } from "@dnd-kit/sortable";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { Users, Trophy, Save, RotateCcw, Settings, Download, Camera } from "lucide-react";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
import { type Player, type Team } from "@shared/schema";

interface Formation {
  id: string;
  name: string;
  positions: Array<{
    id: string;
    name: string;
    x: number;
    y: number;
    required: boolean;
  }>;
}

interface PlayerAssignment {
  playerId: number;
  positionId: string;
  isStarter: boolean;
  orderIndex: number;
}

interface RosterState {
  teamId: number;
  formation: Formation;
  assignments: PlayerAssignment[];
  substitutes: number[];
}

// Rugby formations
const RUGBY_FORMATIONS: Formation[] = [
  {
    id: "15s-standard",
    name: "15s Standard",
    positions: [
      { id: "1", name: "Loosehead Prop", x: 20, y: 85, required: true },
      { id: "2", name: "Hooker", x: 50, y: 85, required: true },
      { id: "3", name: "Tighthead Prop", x: 80, y: 85, required: true },
      { id: "4", name: "Lock", x: 35, y: 75, required: true },
      { id: "5", name: "Lock", x: 65, y: 75, required: true },
      { id: "6", name: "Blindside Flanker", x: 25, y: 65, required: true },
      { id: "7", name: "Openside Flanker", x: 75, y: 65, required: true },
      { id: "8", name: "Number Eight", x: 50, y: 65, required: true },
      { id: "9", name: "Scrum-half", x: 50, y: 55, required: true },
      { id: "10", name: "Fly-half", x: 50, y: 45, required: true },
      { id: "11", name: "Left Wing", x: 15, y: 35, required: true },
      { id: "12", name: "Inside Centre", x: 40, y: 35, required: true },
      { id: "13", name: "Outside Centre", x: 60, y: 35, required: true },
      { id: "14", name: "Right Wing", x: 85, y: 35, required: true },
      { id: "15", name: "Fullback", x: 50, y: 20, required: true },
    ]
  },
  {
    id: "7s-standard",
    name: "7s Standard",
    positions: [
      { id: "1", name: "Prop", x: 30, y: 80, required: true },
      { id: "2", name: "Hooker", x: 50, y: 80, required: true },
      { id: "3", name: "Prop", x: 70, y: 80, required: true },
      { id: "4", name: "Scrum-half", x: 50, y: 60, required: true },
      { id: "5", name: "Fly-half", x: 50, y: 45, required: true },
      { id: "6", name: "Centre", x: 50, y: 30, required: true },
      { id: "7", name: "Fullback", x: 50, y: 15, required: true },
    ]
  }
];

// DraggablePlayer Component
function DraggablePlayerCard({ player, isDragging, isAssigned }: { 
  player: Player; 
  isDragging?: boolean;
  isAssigned?: boolean;
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ 
    id: player.id,
    data: {
      type: 'player',
      player,
    },
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className={`p-3 bg-white border rounded-lg shadow-sm cursor-grab active:cursor-grabbing transition-all hover:shadow-md ${
        isAssigned ? 'border-blue-500 bg-blue-50' : 'border-gray-200'
      }`}
    >
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-primary rounded-full flex items-center justify-center text-white text-sm font-semibold">
            {player.firstName[0]}{player.lastName[0]}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-gray-900 truncate">
              {player.firstName} {player.lastName}
            </p>
            <p className="text-xs text-gray-500">
              {player.position} • #{player.jerseyNumber || 'No #'}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

// FieldPosition Component
function FieldPositionSlot({ 
  position, 
  assignedPlayer 
}: { 
  position: { id: string; name: string; x: number; y: number; required: boolean }; 
  assignedPlayer?: Player; 
}) {
  const { setNodeRef, isOver } = useDroppable({
    id: `position-${position.id}`,
    data: {
      type: 'position',
      positionId: position.id,
    },
  });

  // Make assigned player draggable
  const {
    attributes,
    listeners,
    setNodeRef: setDragNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ 
    id: assignedPlayer ? `field-player-${assignedPlayer.id}` : `empty-position-${position.id}`,
    data: {
      type: 'player',
      player: assignedPlayer,
    },
    disabled: !assignedPlayer, // Only enable dragging if there's a player assigned
  });

  const dragStyle = {
    transform: transform ? `${CSS.Transform.toString(transform)} translate(-50%, -50%)` : 'translate(-50%, -50%)',
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  if (assignedPlayer) {
    // Render draggable player in position
    return (
      <div
        style={{
          position: 'absolute',
          left: `${position.x}%`,
          top: `${position.y}%`,
          ...dragStyle,
        }}
      >
        <div
          ref={(node) => {
            setNodeRef(node);
            setDragNodeRef(node);
          }}
          {...attributes}
          {...listeners}
          className={`w-12 h-12 rounded-full border-2 border-white flex items-center justify-center text-white text-xs font-bold cursor-grab active:cursor-grabbing transition-all ${
            isDragging ? 'bg-blue-400' : 'bg-blue-600 hover:bg-blue-700'
          }`}
          title={`${assignedPlayer.firstName} ${assignedPlayer.lastName} - ${position.name} (drag to reassign)`}
        >
          <div className="text-center">
            <div className="text-xs leading-none">
              {assignedPlayer.firstName[0]}{assignedPlayer.lastName[0]}
            </div>
            <div className="text-xs leading-none">
              {position.id}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Render empty position slot
  return (
    <div
      ref={setNodeRef}
      className={`absolute w-12 h-12 rounded-full border-2 border-white flex items-center justify-center text-white text-xs font-bold cursor-pointer transition-all ${
        isOver 
          ? 'bg-yellow-500 hover:bg-yellow-600 scale-110' 
          : 'bg-green-600 hover:bg-green-700'
      }`}
      style={{
        left: `${position.x}%`,
        top: `${position.y}%`,
        transform: 'translate(-50%, -50%)',
      }}
      title={`Empty ${position.name} position - drop a player here`}
    >
      <span>{position.id}</span>
    </div>
  );
}

// Droppable Substitutes Zone Component
function SubstitutesDropZone({ children }: { children: React.ReactNode }) {
  const { isOver, setNodeRef } = useDroppable({
    id: 'substitutes-drop-zone',
    data: {
      type: 'substitutes-zone',
    },
  });

  return (
    <div
      ref={setNodeRef}
      className={`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 min-h-[100px] p-2 border-2 border-dashed rounded-lg transition-colors ${
        isOver ? 'border-blue-400 bg-blue-50' : 'border-gray-200'
      }`}
    >
      {children}
    </div>
  );
}

// Droppable Available Players Zone Component
function AvailablePlayersDropZone({ children }: { children: React.ReactNode }) {
  const { isOver, setNodeRef } = useDroppable({
    id: 'available-players-drop-zone',
    data: {
      type: 'available-zone',
    },
  });

  return (
    <div
      ref={setNodeRef}
      className={`space-y-2 max-h-96 overflow-y-auto min-h-[200px] p-2 border-2 border-dashed rounded-lg transition-colors ${
        isOver ? 'border-green-400 bg-green-50' : 'border-gray-200'
      }`}
    >
      {children}
    </div>
  );
}

export default function RosterManagement() {
  const [selectedTeam, setSelectedTeam] = useState<number | null>(null);
  const [selectedFormation, setSelectedFormation] = useState<Formation>(RUGBY_FORMATIONS[0]);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [draggedPlayer, setDraggedPlayer] = useState<Player | undefined>(undefined);
  const [rosterState, setRosterState] = useState<RosterState>({
    teamId: 0,
    formation: RUGBY_FORMATIONS[0],
    assignments: [],
    substitutes: [],
  });
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [rosterName, setRosterName] = useState("");
  const [rosterNotes, setRosterNotes] = useState("");

  const { toast } = useToast();
  const queryClient = useQueryClient();

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

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

  const { data: players = [] } = useQuery<Player[]>({
    queryKey: ["/api/players"],
  });

  const teamPlayers = players.filter(player => 
    selectedTeam ? player.teamId === selectedTeam : false
  );

  const availablePlayers = teamPlayers.filter(player => 
    !rosterState.assignments.some(assignment => assignment.playerId === player.id) &&
    !rosterState.substitutes.includes(player.id)
  );

  const assignedPlayers = rosterState.assignments.map(assignment => ({
    ...assignment,
    player: players.find(p => p.id === assignment.playerId),
  }));

  const substitutePlayers = rosterState.substitutes.map(playerId => 
    players.find(p => p.id === playerId)
  ).filter(Boolean) as Player[];

  // Export functions
  const exportToPDF = async () => {
    try {
      const element = document.getElementById('roster-export-content');
      if (!element) {
        toast({
          title: "Export Error",
          description: "Could not find roster 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({
        orientation: 'landscape',
        unit: 'mm',
        format: 'a4',
      });

      const imgWidth = 297;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      
      pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
      
      const selectedTeamData = teams.find(t => t.id === selectedTeam);
      const teamName = selectedTeamData?.name || 'Team';
      const fileName = `${teamName}-roster-${new Date().toISOString().split('T')[0]}.pdf`;
      
      pdf.save(fileName);
      
      toast({
        title: "PDF Export Successful",
        description: `Roster exported as ${fileName}`,
      });
    } catch (error) {
      toast({
        title: "Export Failed",
        description: "Failed to generate PDF export",
        variant: "destructive",
      });
    }
  };

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

      const canvas = await html2canvas(element, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
      });
      
      const link = document.createElement('a');
      const selectedTeamData = teams.find(t => t.id === selectedTeam);
      const teamName = selectedTeamData?.name || 'Team';
      const fileName = `${teamName}-roster-${new Date().toISOString().split('T')[0]}.jpg`;
      
      link.download = fileName;
      link.href = canvas.toDataURL('image/jpeg', 0.9);
      link.click();
      
      toast({
        title: "JPG Export Successful",
        description: `Roster exported as ${fileName}`,
      });
    } catch (error) {
      toast({
        title: "Export Failed",
        description: "Failed to generate JPG export",
        variant: "destructive",
      });
    }
  };

  // Save roster mutation
  const saveRosterMutation = useMutation({
    mutationFn: async (rosterData: any) => {
      const res = await apiRequest("POST", "/api/rosters", rosterData);
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Roster saved",
        description: "The team roster has been saved successfully.",
      });
      setShowSaveDialog(false);
      queryClient.invalidateQueries({ queryKey: ["/api/rosters"] });
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to save roster",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id as string);
    
    // Find the player being dragged
    const activeId = String(event.active.id);
    let player: Player | undefined;
    
    // Check if it's a regular player card
    if (typeof event.active.id === 'number' || !activeId.startsWith('field-player-')) {
      player = players.find(p => p.id === parseInt(activeId));
    } else {
      // It's a field player - extract the player ID
      const playerId = parseInt(activeId.replace('field-player-', ''));
      player = players.find(p => p.id === playerId);
    }
    
    setDraggedPlayer(player);
  }, [players]);

  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event;
    setActiveId(null);
    setDraggedPlayer(undefined);

    if (!over) return;

    const activeType = active.data.current?.type;
    const overType = over.data.current?.type;
    const overPositionId = over.data.current?.positionId;
    
    // Extract player ID from either regular player cards or field players
    const activeId = String(active.id);
    let playerId: number;
    
    if (activeId.startsWith('field-player-')) {
      playerId = parseInt(activeId.replace('field-player-', ''));
    } else {
      playerId = parseInt(activeId);
    }

    // Player dropped on position
    if (activeType === 'player' && overType === 'position') {
      const positionId = overPositionId;

      // Remove player from current assignment if exists
      setRosterState(prev => ({
        ...prev,
        assignments: prev.assignments.filter(a => a.playerId !== playerId),
        substitutes: prev.substitutes.filter(id => id !== playerId),
      }));

      // Add new assignment
      setRosterState(prev => ({
        ...prev,
        assignments: [
          ...prev.assignments.filter(a => a.positionId !== positionId),
          {
            playerId,
            positionId,
            isStarter: true,
            orderIndex: 0,
          }
        ],
      }));
    }

    // Player dropped on substitutes zone
    if (activeType === 'player' && (over.id === 'substitutes-drop-zone' || overType === 'substitutes-zone')) {
      setRosterState(prev => ({
        ...prev,
        assignments: prev.assignments.filter(a => a.playerId !== playerId),
        substitutes: [...prev.substitutes.filter(id => id !== playerId), playerId],
      }));
    }

    // Player dropped on available players zone (remove from roster)
    if (activeType === 'player' && (over.id === 'available-players-drop-zone' || overType === 'available-zone')) {
      setRosterState(prev => ({
        ...prev,
        assignments: prev.assignments.filter(a => a.playerId !== playerId),
        substitutes: prev.substitutes.filter(id => id !== playerId),
      }));
    }
  }, []);

  const handleFormationChange = (formationId: string) => {
    const formation = RUGBY_FORMATIONS.find(f => f.id === formationId);
    if (formation) {
      setSelectedFormation(formation);
      setRosterState(prev => ({
        ...prev,
        formation,
        assignments: [], // Clear assignments when changing formation
      }));
    }
  };

  const handleSaveRoster = () => {
    if (!selectedTeam || !rosterName.trim()) return;

    const rosterData = {
      name: rosterName,
      teamId: selectedTeam,
      formation: selectedFormation.id,
      assignments: rosterState.assignments,
      substitutes: rosterState.substitutes,
      notes: rosterNotes,
    };

    saveRosterMutation.mutate(rosterData);
  };

  const clearRoster = () => {
    setRosterState(prev => ({
      ...prev,
      assignments: [],
      substitutes: [],
    }));
  };

  const autoFillRoster = () => {
    const availablePlayersCopy = [...availablePlayers];
    const newAssignments: PlayerAssignment[] = [];
    
    // Fill starting positions first
    selectedFormation.positions.forEach((position, index) => {
      if (availablePlayersCopy.length > 0) {
        const player = availablePlayersCopy.shift();
        if (player) {
          newAssignments.push({
            playerId: player.id,
            positionId: position.id,
            isStarter: true,
            orderIndex: index,
          });
        }
      }
    });

    setRosterState(prev => ({
      ...prev,
      assignments: newAssignments,
      substitutes: availablePlayersCopy.map(p => p.id),
    }));
  };

  return (
    <div className="container mx-auto p-6 space-y-6" id="roster-export-content">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Team Roster Management</h1>
          <p className="text-gray-600">Drag and drop players to create your team lineup</p>
        </div>
        
        <div className="flex gap-2">
          <Button variant="outline" onClick={exportToJPG} disabled={!selectedTeam}>
            <Camera className="h-4 w-4 mr-2" />
            Export JPG
          </Button>
          <Button variant="outline" onClick={exportToPDF} disabled={!selectedTeam}>
            <Download className="h-4 w-4 mr-2" />
            Export PDF
          </Button>
          <Button variant="outline" onClick={clearRoster}>
            <RotateCcw className="h-4 w-4 mr-2" />
            Clear
          </Button>
          <Button variant="outline" onClick={autoFillRoster}>
            <Settings className="h-4 w-4 mr-2" />
            Auto Fill
          </Button>
          <Button onClick={() => setShowSaveDialog(true)} disabled={!selectedTeam}>
            <Save className="h-4 w-4 mr-2" />
            Save Roster
          </Button>
        </div>
      </div>

      {/* Team and Formation Selection */}
      <Card>
        <CardHeader>
          <CardTitle>Setup</CardTitle>
          <CardDescription>Select team and formation to begin roster management</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="team">Team</Label>
              <Select value={selectedTeam?.toString() || ""} onValueChange={(value) => setSelectedTeam(parseInt(value))}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a team" />
                </SelectTrigger>
                <SelectContent>
                  {teams.map((team) => (
                    <SelectItem key={team.id} value={team.id.toString()}>
                      {team.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="formation">Formation</Label>
              <Select value={selectedFormation.id} onValueChange={handleFormationChange}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {RUGBY_FORMATIONS.map((formation) => (
                    <SelectItem key={formation.id} value={formation.id}>
                      {formation.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {selectedTeam && (
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragStart={handleDragStart}
          onDragEnd={handleDragEnd}
        >
          <SortableContext
            items={[
              ...availablePlayers.map(p => p.id),
              ...substitutePlayers.map(p => p.id),
              ...rosterState.assignments.map(a => `field-player-${a.playerId}`),
            ]}
            strategy={verticalListSortingStrategy}
          >
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Available Players */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  Available Players ({availablePlayers.length})
                </CardTitle>
              </CardHeader>
              <CardContent>
                <AvailablePlayersDropZone>
                  {availablePlayers.length > 0 ? (
                    availablePlayers.map((player) => (
                      <DraggablePlayerCard key={player.id} player={player} />
                    ))
                  ) : (
                    <div className="text-center text-gray-500 py-8">
                      All players have been assigned
                    </div>
                  )}
                </AvailablePlayersDropZone>
              </CardContent>
            </Card>

            {/* Field Formation */}
            <Card className="lg:col-span-2">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Trophy className="h-5 w-5" />
                  {selectedFormation.name} Formation
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="relative w-full h-96 bg-green-100 rounded-lg border-2 border-green-200">
                  {/* Field lines */}
                  <div className="absolute inset-0 opacity-30">
                    <div className="w-full h-px bg-white absolute top-1/4"></div>
                    <div className="w-full h-px bg-white absolute top-2/4"></div>
                    <div className="w-full h-px bg-white absolute top-3/4"></div>
                    <div className="w-px h-full bg-white absolute left-1/4"></div>
                    <div className="w-px h-full bg-white absolute left-2/4"></div>
                    <div className="w-px h-full bg-white absolute left-3/4"></div>
                  </div>

                  {/* Positions */}
                  <SortableContext 
                    items={selectedFormation.positions.map(p => `position-${p.id}`)}
                    strategy={rectSortingStrategy}
                  >
                    {selectedFormation.positions.map((position) => {
                      const assignment = rosterState.assignments.find(a => a.positionId === position.id);
                      const assignedPlayer = assignment ? players.find(p => p.id === assignment.playerId) : undefined;
                      
                      return (
                        <FieldPositionSlot
                          key={position.id}
                          position={position}
                          assignedPlayer={assignedPlayer}
                        />
                      );
                    })}
                  </SortableContext>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Substitutes */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Users className="h-5 w-5" />
                Substitutes ({substitutePlayers.length})
              </CardTitle>
            </CardHeader>
            <CardContent>
              <SubstitutesDropZone>
                {substitutePlayers.length > 0 ? (
                  substitutePlayers.map((player) => (
                    <DraggablePlayerCard key={player.id} player={player} isAssigned={true} />
                  ))
                ) : (
                  <div className="col-span-full text-center text-gray-500 py-8">
                    Drag players here to add them as substitutes
                  </div>
                )}
              </SubstitutesDropZone>
            </CardContent>
          </Card>

          <DragOverlay>
            {draggedPlayer ? (
              <DraggablePlayerCard player={draggedPlayer} isDragging />
            ) : null}
          </DragOverlay>
          </SortableContext>
        </DndContext>
      )}

      {/* Save Roster Dialog */}
      <Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Save Roster</DialogTitle>
            <DialogDescription>
              Save this roster configuration for future use.
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            <div>
              <Label htmlFor="rosterName">Roster Name</Label>
              <Input
                id="rosterName"
                value={rosterName}
                onChange={(e) => setRosterName(e.target.value)}
                placeholder="e.g., Starting XV vs Eagles"
              />
            </div>
            
            <div>
              <Label htmlFor="rosterNotes">Notes (Optional)</Label>
              <Textarea
                id="rosterNotes"
                value={rosterNotes}
                onChange={(e) => setRosterNotes(e.target.value)}
                placeholder="Add any notes about this roster configuration..."
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSaveDialog(false)}>
              Cancel
            </Button>
            <Button 
              onClick={handleSaveRoster} 
              disabled={!rosterName.trim() || saveRosterMutation.isPending}
            >
              {saveRosterMutation.isPending ? "Saving..." : "Save Roster"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}