import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import TeamForm from "@/components/forms/team-form";
import TeamEditForm from "@/components/forms/team-edit-form";
import { Plus, Edit, Trash2, Users, Search, Eye, UserPlus, Mail, Phone, MapPin, BarChart3, PieChart, Grid3X3, List } from "lucide-react";
import { Link } from "wouter";
import type { Team } from "@shared/schema";
import { getSportIcon, getSportIconColor } from "@/lib/sport-icons";
import type { SportType } from "@shared/sports";

export default function Teams() {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedTeam, setSelectedTeam] = useState<Team | null>(null);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: teams, isLoading } = useQuery({
    queryKey: ["/api/teams"],
  });

  const deleteTeamMutation = useMutation({
    mutationFn: async (teamId: number) => {
      console.log("Deleting team with ID:", teamId);
      return await apiRequest("DELETE", `/api/teams/${teamId}`);
    },
    onSuccess: (data, teamId) => {
      console.log("Team deleted successfully:", teamId);
      queryClient.invalidateQueries({ queryKey: ["/api/teams"] });
      toast({
        title: "Success",
        description: "Team deleted successfully",
      });
    },
    onError: (error: any, teamId) => {
      console.error("Failed to delete team:", teamId, error);
      toast({
        title: "Error",
        description: error.message || "Failed to delete team",
        variant: "destructive",
      });
    },
  });

  const filteredTeams = (teams as Team[] || []).filter((team: Team) =>
    team.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    team.sport.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleEdit = (team: Team) => {
    console.log("Edit clicked for team:", team);
    console.log("Current dialog state:", showEditDialog);
    setSelectedTeam(team);
    setShowEditDialog(true);
    console.log("Dialog should now be open:", true);
  };

  const handleDelete = (teamId: number) => {
    console.log("Delete clicked for team ID:", teamId);
    if (window.confirm("Are you sure you want to delete this team?")) {
      deleteTeamMutation.mutate(teamId);
    }
  };

  if (isLoading) {
    return (
      <div className="p-4 sm:p-6">
        <div className="animate-pulse space-y-4 sm:space-y-6">
          <div className="h-8 bg-gray-200 rounded w-48"></div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-48 bg-gray-200 rounded-xl"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6">
      {/* Header */}
      <div className="mb-6 sm:mb-8">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between mb-4 gap-4">
          <div>
            <h2 className="text-2xl sm:text-3xl font-bold text-gray-900">Teams</h2>
            <p className="text-gray-600">Manage your sports teams and their information</p>
          </div>
          <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
            <DialogTrigger asChild>
              <Button className="w-full sm:w-auto">
                <Plus className="h-4 w-4 mr-2" />
                Create Team
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>Create New Team</DialogTitle>
                <DialogDescription>
                  Add a new team to your sports organization
                </DialogDescription>
              </DialogHeader>
              <TeamForm onSuccess={() => setShowCreateDialog(false)} />
            </DialogContent>
          </Dialog>
        </div>

        {/* Search and View Controls */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="relative flex-1 sm:max-w-md">
            <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
            <Input
              placeholder="Search teams..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
          
          <div className="flex items-center gap-2">
            <Button
              variant={viewMode === "grid" ? "default" : "outline"}
              size="sm"
              onClick={() => setViewMode("grid")}
            >
              <Grid3X3 className="h-4 w-4" />
            </Button>
            <Button
              variant={viewMode === "list" ? "default" : "outline"}
              size="sm"
              onClick={() => setViewMode("list")}
            >
              <List className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Teams Display */}
      {filteredTeams.length === 0 ? (
        <Card className="text-center py-12">
          <CardContent>
            <Users className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">No teams found</h3>
            <p className="text-gray-500 mb-4">
              {searchQuery ? "No teams match your search criteria" : "Get started by creating your first team"}
            </p>
            {!searchQuery && (
              <Button onClick={() => setShowCreateDialog(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Create Team
              </Button>
            )}
          </CardContent>
        </Card>
      ) : viewMode === "grid" ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
          {filteredTeams.map((team: Team) => (
            <Card key={team.id} className="hover:shadow-lg transition-shadow">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={team.logoUrl || undefined} alt={team.name} />
                      <AvatarFallback className="bg-primary text-white">
                        {team.name.slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <CardTitle className="text-lg">{team.name}</CardTitle>
                      <div className="flex items-center gap-1.5 mt-1">
                        {(() => {
                          const SportIcon = getSportIcon(team.sport as SportType);
                          const colors = getSportIconColor(team.sport as SportType);
                          return (
                            <>
                              <SportIcon className={`h-3.5 w-3.5 ${colors.text}`} />
                              <CardDescription className="capitalize">{team.sport}</CardDescription>
                            </>
                          );
                        })()}
                      </div>
                    </div>
                  </div>
                  <Badge variant={team.status === "active" ? "default" : "secondary"}>
                    {team.status}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                {team.description && (
                  <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                    {team.description}
                  </p>
                )}
                
                {/* Action Buttons */}
                <div className="space-y-3 mb-4">
                  <Link to={`/teams/${team.id}`}>
                    <Button className="w-full" variant="outline">
                      <UserPlus className="h-4 w-4 mr-2" />
                      Manage Staff & View Details
                    </Button>
                  </Link>
                </div>
                
                <div className="flex items-center justify-between">
                  <p className="text-xs text-gray-500">
                    Created {new Date(team.createdAt!).toLocaleDateString()}
                  </p>
                  <div className="flex space-x-1">
                    <Link to={`/teams/${team.id}`}>
                      <Button
                        variant="ghost"
                        size="sm"
                        title="View team details"
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                    </Link>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(team)}
                      title="Edit team information"
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(team.id)}
                      disabled={deleteTeamMutation.isPending}
                      title="Delete team"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <div className="space-y-4">
          {filteredTeams.map((team: Team) => (
            <Card key={team.id} className="hover:shadow-md transition-shadow">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-4">
                    <Avatar className="w-16 h-16">
                      <AvatarImage src={team.logoUrl || undefined} alt={team.name} />
                      <AvatarFallback className="bg-primary text-white text-lg">
                        {team.name.slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-xl font-semibold">{team.name}</h3>
                        <Badge variant={team.status === "active" ? "default" : "secondary"}>
                          {team.status}
                        </Badge>
                      </div>
                      <div className="flex items-center gap-2 mb-1">
                        {(() => {
                          const SportIcon = getSportIcon(team.sport as SportType);
                          const colors = getSportIconColor(team.sport as SportType);
                          return (
                            <>
                              <div className={`p-1 ${colors.bg} ${colors.darkBg} rounded`}>
                                <SportIcon className={`h-3.5 w-3.5 ${colors.text} ${colors.darkText}`} />
                              </div>
                              <p className="text-gray-600 capitalize font-medium">{team.sport}</p>
                            </>
                          );
                        })()}
                      </div>
                      {team.description && (
                        <p className="text-gray-500 text-sm line-clamp-2 max-w-2xl">
                          {team.description}
                        </p>
                      )}
                      <p className="text-xs text-gray-400 mt-2">
                        Created {new Date(team.createdAt!).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Link to={`/teams/${team.id}`}>
                      <Button variant="outline">
                        <UserPlus className="h-4 w-4 mr-2" />
                        Manage Team
                      </Button>
                    </Link>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(team)}
                      title="Edit team information"
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(team.id)}
                      disabled={deleteTeamMutation.isPending}
                      title="Delete team"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Edit Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Edit Team</DialogTitle>
            <DialogDescription>
              Update the team information
            </DialogDescription>
          </DialogHeader>
          {selectedTeam && (
            <TeamEditForm
              team={selectedTeam}
              onSuccess={() => {
                setShowEditDialog(false);
                setSelectedTeam(null);
              }}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
