"use client";

import { useState } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Building2,
  Search,
  Filter,
  Eye,
  Trash2,
  ChevronLeft,
  ChevronRight,
  CircleMinus,
  Unlock,
  Lock,
} from "lucide-react";
import { CommunityDetailsDialog } from "@/components/community-details-dialog";
import {
  useCommunities,
  useBlockCommunity,
  useUnblockCommunity,
  useDeleteCommunity,
} from "@/hooks";
import { CommunityVisibility } from "@/types/api";

export default function CommunitiesPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [visibilityFilter, setVisibilityFilter] = useState("");
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  // Dialog state management
  const [selectedCommunityId, setSelectedCommunityId] = useState<string | null>(
    null
  );
  const [isCommunityDialogOpen, setIsCommunityDialogOpen] = useState(false);

  // Fetch communities with filters
  const { data: communitiesData, isLoading: communitiesLoading } =
    useCommunities({
      page: currentPage,
      limit: pageSize,
      search: searchTerm || undefined,
      status: statusFilter && statusFilter !== "all" ? statusFilter : undefined,
      sortBy,
      sortOrder,
      visibility:
        visibilityFilter && visibilityFilter !== "all"
          ? visibilityFilter
          : undefined,
    });

  // Community management mutations
  const blockCommunityMutation = useBlockCommunity();
  const unblockCommunityMutation = useUnblockCommunity();
  const deleteCommunityMutation = useDeleteCommunity();

  // Community action handlers
  const handleBlockCommunity = async (communityId: string) => {
    try {
      await blockCommunityMutation.mutateAsync({
        id: communityId,
        blockData: { reason: "Community blocked by admin" },
      });
    } catch (error) {
      console.error("Failed to block community:", error);
    }
  };

  const handleUnblockCommunity = async (communityId: string) => {
    try {
      await unblockCommunityMutation.mutateAsync(communityId);
    } catch (error) {
      console.error("Failed to unblock community:", error);
    }
  };

  const handleDeleteCommunity = async (communityId: string) => {
    if (
      confirm(
        "Are you sure you want to delete this community? This action cannot be undone."
      )
    ) {
      try {
        await deleteCommunityMutation.mutateAsync({
          id: communityId,
          deleteData: { reason: "Community deleted by admin" },
        });
      } catch (error) {
        console.error("Failed to delete community:", error);
      }
    }
  };

  // Dialog handlers
  const handleViewCommunity = (communityId: string) => {
    setSelectedCommunityId(communityId);
    setIsCommunityDialogOpen(true);
  };

  const handleCloseCommunityDialog = () => {
    setIsCommunityDialogOpen(false);
    setSelectedCommunityId(null);
  };

  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const handleFilterChange = (filterType: string, value: string) => {
    switch (filterType) {
      case "status":
        setStatusFilter(value);
        break;
      case "visibility":
        setVisibilityFilter(value);
        break;
      case "sortBy":
        setSortBy(value);
        break;
      case "sortOrder":
        setSortOrder(value as "asc" | "desc");
        break;
    }
    setCurrentPage(1);
  };

  const totalPages = Math.ceil((communitiesData?.data?.total || 0) / pageSize);

  return (
    <div className="flex-1 space-y-6 p-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">
            Community Management
          </h1>
          <p className="text-muted-foreground">
            Manage platform communities and their settings
          </p>
        </div>
        {/* <Button>
          <Plus className="h-4 w-4 mr-2" />
          Create Community
        </Button> */}
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filters & Search
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            {/* Search */}
            <div className="space-y-2">
              <Label htmlFor="search">Search</Label>
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Search communities..."
                  value={searchTerm}
                  onChange={(e) => handleSearch(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>

            {/* Status Filter */}
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select
                value={statusFilter}
                onValueChange={(value) => handleFilterChange("status", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="All statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All statuses</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="blocked">Blocked</SelectItem>
                  <SelectItem value="deleted">Deleted</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Visibility Filter */}
            <div className="space-y-2">
              <Label htmlFor="visibility">Visibility</Label>
              <Select
                value={visibilityFilter}
                onValueChange={(value) =>
                  handleFilterChange("visibility", value)
                }
              >
                <SelectTrigger>
                  <SelectValue placeholder="All visibility" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All visibility</SelectItem>
                  <SelectItem value={CommunityVisibility.public}>
                    Public
                  </SelectItem>
                  <SelectItem value={CommunityVisibility.private}>
                    Private
                  </SelectItem>
                  {/* <SelectItem value={CommunityVisibility.restricted}>
                    Restricted
                  </SelectItem> */}
                </SelectContent>
              </Select>
            </div>

            {/* Sort By */}
            <div className="space-y-2">
              <Label htmlFor="sortBy">Sort By</Label>
              <Select
                value={sortBy}
                onValueChange={(value) => handleFilterChange("sortBy", value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">Created Date</SelectItem>
                  <SelectItem value="name">Name</SelectItem>
                  {/* <SelectItem value="membersCount">Members</SelectItem>
                  <SelectItem value="postsCount">Posts</SelectItem> */}
                </SelectContent>
              </Select>
            </div>

            {/* Sort Order */}
            <div className="space-y-2">
              <Label htmlFor="sortOrder">Order</Label>
              <Select
                value={sortOrder}
                onValueChange={(value) =>
                  handleFilterChange("sortOrder", value)
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="desc">Descending</SelectItem>
                  <SelectItem value="asc">Ascending</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Communities List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Building2 className="h-5 w-5 mr-2" />
            Communities ({communitiesData?.data?.total || 0})
          </CardTitle>
          <CardDescription>
            Showing {communitiesData?.data?.communities?.length || 0} of{" "}
            {communitiesData?.data?.total || 0} communities
          </CardDescription>
        </CardHeader>
        <CardContent>
          {communitiesLoading ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="p-4 border rounded-lg animate-pulse">
                  <div className="space-y-2">
                    <div className="h-5 bg-gray-200 rounded w-1/3"></div>
                    <div className="h-4 bg-gray-200 rounded w-2/3"></div>
                    <div className="flex space-x-2">
                      <div className="h-6 w-16 bg-gray-200 rounded"></div>
                      <div className="h-6 w-16 bg-gray-200 rounded"></div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-3">
              {communitiesData?.data?.communities?.map((community) => (
                <div key={community._id} className="p-4 border rounded-lg">
                  <div className="flex items-start justify-between">
                    <div className="space-y-2 flex-1">
                      <div className="flex items-center space-x-2">
                        <h4 className="font-medium">{community.name}</h4>
                        <Badge
                          className="capitalize"
                          variant={
                            community.isBlocked ? "destructive" : "success"
                          }
                        >
                          {community.isBlocked ? "Blocked" : "Active"}
                        </Badge>
                        <Badge variant="outline" className="capitalize">
                          {community.communityVisibility}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {community.description}
                      </p>
                      <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                        <span>{community.membersCount} members</span>
                        <span>{community.postsCount} posts</span>
                        <span>
                          Created by {community.createdBy?.fullName || "N/A"}
                        </span>
                        <span>
                          {new Date(community.createdAt).toLocaleDateString()}
                        </span>
                      </div>
                      {community.tags && community.tags.length > 0 && (
                        <div className="flex space-x-1">
                          {community.tags?.map((tag, i) => (
                            <Badge key={i} className="text-xs capitalize">
                              {typeof tag === "string" ? tag : tag.tag}
                            </Badge>
                          ))}
                        </div>
                      )}
                    </div>
                    <div className="flex items-center space-x-2">
                      <Button
                        variant="outline"
                        size="sm"
                        title="View Community Details"
                        onClick={() => handleViewCommunity(community._id)}
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      {community.isBlocked ? (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleUnblockCommunity(community._id)}
                          disabled={unblockCommunityMutation.isPending}
                          title="Unblock Community"
                          className="hidden md:block"
                        >
                          <Unlock className="h-4 w-4 " />
                        </Button>
                      ) : (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleBlockCommunity(community._id)}
                          disabled={blockCommunityMutation.isPending}
                          title="Block Community"
                          className="hidden md:block"
                        >
                          <Lock className="h-4 w-4" />
                        </Button>
                      )}
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteCommunity(community._id)}
                        disabled={deleteCommunityMutation.isPending}
                        title="Delete Community"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {totalPages > 1 && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Label htmlFor="pageSize">Items per page:</Label>
                <Select
                  value={pageSize.toString()}
                  onValueChange={(value) => {
                    setPageSize(parseInt(value));
                    setCurrentPage(1);
                  }}
                >
                  <SelectTrigger className="w-20">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="5">5</SelectItem>
                    <SelectItem value="10">10</SelectItem>
                    <SelectItem value="20">20</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage - 1)}
                  disabled={currentPage === 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                  Previous
                </Button>
                <span className="text-sm text-muted-foreground">
                  Page {currentPage} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                >
                  Next
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Community Details Dialog */}
      <CommunityDetailsDialog
        communityId={selectedCommunityId}
        isOpen={isCommunityDialogOpen}
        onClose={handleCloseCommunityDialog}
      />
    </div>
  );
}
