import { useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Pencil, Trash, ChevronLeft, ChevronRight, Search } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import type { Jump } from "@shared/schema";
import { format } from "date-fns";

interface JumpTableProps {
  onEdit?: (jump: Jump) => void;
}

export default function JumpTable({ onEdit }: JumpTableProps) {
  const { toast } = useToast();
  const [searchTerm, setSearchTerm] = useState("");
  const [dropzoneFilter, setDropzoneFilter] = useState("");
  const [page, setPage] = useState(1);
  const [sortField, setSortField] = useState("jumpNumber");
  const [sortDirection, setSortDirection] = useState("desc");
  const limit = 10;

  // Function to handle sorting changes
  const handleSort = (field: string) => {
    if (field === sortField) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  // Construct query parameters
  const queryParams = new URLSearchParams();
  if (searchTerm) queryParams.append("search", searchTerm);
  if (dropzoneFilter) queryParams.append("dropzone", dropzoneFilter);
  queryParams.append("sort", `${sortField}:${sortDirection}`);
  queryParams.append("page", page.toString());
  queryParams.append("limit", limit.toString());

  // Fetch jumps from API
  const { data, isLoading, isError } = useQuery<{ jumps: Jump[], total: number }>({
    queryKey: [`/api/jumps?${queryParams.toString()}`],
  });

  // Fetch dropzones for filter dropdown
  const { data: allJumpsData } = useQuery<{ jumps: Jump[], total: number }>({
    queryKey: ['/api/jumps'],
  });
  
  // Extract the jumps array
  const allJumps = allJumpsData?.jumps || [];

  // Get unique dropzones for the filter using a regular object
  const dropzonesObj: Record<string, boolean> = {};
  // allJumps is always an array (empty if no data)
  allJumps.forEach(jump => {
    if (jump.dropzone) {
      dropzonesObj[jump.dropzone] = true;
    }
  });
  const dropzones = Object.keys(dropzonesObj);

  // Delete jump mutation
  const deleteJumpMutation = useMutation({
    mutationFn: async (id: number) => {
      await apiRequest('DELETE', `/api/jumps/${id}`);
    },
    onSuccess: () => {
      toast({
        title: "Jump deleted",
        description: "The jump has been deleted successfully.",
      });
      // Invalidate jump queries to refresh the data
      queryClient.invalidateQueries({ queryKey: ['/api/jumps'] });
      queryClient.invalidateQueries({ queryKey: [`/api/jumps?${queryParams.toString()}`] });
      queryClient.invalidateQueries({ queryKey: ['/api/stats'] });
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: `Failed to delete jump: ${error instanceof Error ? error.message : 'Unknown error'}`,
        variant: "destructive",
      });
    }
  });

  // Handle delete jump
  const handleDelete = (id: number) => {
    if (window.confirm("Are you sure you want to delete this jump?")) {
      deleteJumpMutation.mutate(id);
    }
  };

  // Calculate total pages
  const totalPages = data ? Math.ceil(data.total / limit) : 0;

  if (isError) {
    return (
      <div className="text-center py-8">
        <p className="text-red-500">Error loading jumps. Please try again later.</p>
      </div>
    );
  }

  return (
    <div>
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
        <h2 className="text-2xl font-bold text-gray-800" style={{ fontFamily: "Montserrat, sans-serif" }}>Jump Log</h2>
        
        <div className="flex flex-col sm:flex-row gap-4 w-full sm:w-auto">
          <div className="relative">
            <Input
              placeholder="Search jumps..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 w-full sm:w-auto"
            />
            <Search className="h-5 w-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
          </div>
          
          <Select value={dropzoneFilter} onValueChange={setDropzoneFilter}>
            <SelectTrigger className="w-full sm:w-[180px]">
              <SelectValue placeholder="All Dropzones" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="">All Dropzones</SelectItem>
              {dropzones.map((dz) => (
                <SelectItem key={dz} value={dz}>{dz}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("jumpNumber")}
                >
                  Jump # {sortField === "jumpNumber" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("jumpDate")}
                >
                  Date {sortField === "jumpDate" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("jumpType")}
                >
                  Type of Jump {sortField === "jumpType" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("dropzone")}
                >
                  DZ {sortField === "dropzone" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("altitude")}
                >
                  Altitude {sortField === "altitude" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("aircraft")}
                >
                  Aircraft {sortField === "aircraft" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead 
                  className="cursor-pointer" 
                  onClick={() => handleSort("equipment")}
                >
                  Equipment {sortField === "equipment" && (sortDirection === "asc" ? "↑" : "↓")}
                </TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8">Loading...</TableCell>
                </TableRow>
              ) : data?.jumps.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8">No jumps found. Add your first jump!</TableCell>
                </TableRow>
              ) : (
                data?.jumps.map((jump) => (
                  <TableRow key={jump.id} className="hover:bg-gray-50">
                    <TableCell className="font-medium text-gray-900">{jump.jumpNumber}</TableCell>
                    <TableCell>
                      {jump.jumpDate ? format(new Date(jump.jumpDate), "MMM d, yyyy") : "-"}
                    </TableCell>
                    <TableCell>{jump.jumpType}</TableCell>
                    <TableCell>{jump.dropzone}</TableCell>
                    <TableCell>{jump.altitude}</TableCell>
                    <TableCell>{jump.aircraft}</TableCell>
                    <TableCell>{jump.equipment}</TableCell>
                    <TableCell>
                      <div className="flex space-x-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => onEdit && onEdit(jump)}
                          className="text-blue-500 hover:text-blue-700"
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDelete(jump.id)}
                          className="text-red-500 hover:text-red-700"
                        >
                          <Trash className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
        
        {/* Pagination */}
        {totalPages > 0 && (
          <div className="bg-gray-50 px-4 py-3 border-t border-gray-200 sm:px-6">
            <div className="flex items-center justify-between">
              <div className="flex-1 flex justify-between sm:hidden">
                <Button
                  variant="outline"
                  onClick={() => setPage(Math.max(1, page - 1))}
                  disabled={page === 1}
                >
                  Previous
                </Button>
                <Button
                  variant="outline"
                  onClick={() => setPage(Math.min(totalPages, page + 1))}
                  disabled={page === totalPages}
                >
                  Next
                </Button>
              </div>
              <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                  <p className="text-sm text-gray-700">
                    Showing <span className="font-medium">{data ? (page - 1) * limit + 1 : 0}</span> to{" "}
                    <span className="font-medium">
                      {data ? Math.min(page * limit, data.total) : 0}
                    </span>{" "}
                    of <span className="font-medium">{data?.total || 0}</span> results
                  </p>
                </div>
                <div>
                  <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                    <Button
                      variant="outline"
                      className="rounded-l-md"
                      onClick={() => setPage(Math.max(1, page - 1))}
                      disabled={page === 1}
                    >
                      <span className="sr-only">Previous</span>
                      <ChevronLeft className="h-5 w-5" />
                    </Button>
                    
                    {/* Page numbers */}
                    {[...Array(totalPages)].map((_, i) => (
                      <Button
                        key={i}
                        variant={page === i + 1 ? "default" : "outline"}
                        className={`border ${page === i + 1 ? 'bg-[#3B82F6] text-white' : ''}`}
                        onClick={() => setPage(i + 1)}
                      >
                        {i + 1}
                      </Button>
                    ))}
                    
                    <Button
                      variant="outline"
                      className="rounded-r-md"
                      onClick={() => setPage(Math.min(totalPages, page + 1))}
                      disabled={page === totalPages}
                    >
                      <span className="sr-only">Next</span>
                      <ChevronRight className="h-5 w-5" />
                    </Button>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
