"use client";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Building2,
  Calendar,
  Shield,
  Users,
  MessageSquare,
  Eye,
  Trash2,
  Lock,
  Unlock,
  User,
  Tag,
  FileText,
  ExternalLink,
} from "lucide-react";
import {
  useCommunity,
  useBlockCommunity,
  useUnblockCommunity,
  useDeleteCommunity,
} from "@/hooks";
import { CommunityVisibility } from "@/types/api";
import Image from "next/image";
import { useRouter } from "next/navigation";

interface CommunityDetailsDialogProps {
  communityId: string | null;
  isOpen: boolean;
  onClose: () => void;
}

export function CommunityDetailsDialog({
  communityId,
  isOpen,
  onClose,
}: CommunityDetailsDialogProps) {
  const router = useRouter();
  const {
    data: communityData,
    isLoading,
    error,
  } = useCommunity(communityId || "");

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

  const getVisibilityColor = (visibility: string) => {
    switch (visibility) {
      case CommunityVisibility.public:
        return "bg-green-100 text-green-800 capitalize";
      case CommunityVisibility.private:
        return "bg-blue-100 text-blue-800 capitalize";
      case CommunityVisibility.restricted:
        return "bg-yellow-100 text-yellow-800 capitalize";
      default:
        return "bg-gray-100 text-gray-800 capitalize";
    }
  };

  const getStatusColor = (isBlocked: boolean, isDeleted: boolean) => {
    if (isDeleted) return "bg-red-100 text-red-800 capitalize";
    if (isBlocked) return "bg-orange-100 text-orange-800 capitalize";
    return "bg-green-100 text-green-800 capitalize";
  };

  // 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" },
        });
        onClose(); // Close dialog after successful deletion
      } catch (error) {
        console.error("Failed to delete community:", error);
      }
    }
  };

  if (!communityId) return null;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto gradient-bg">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <span>Community Details</span>
          </DialogTitle>
          <DialogDescription>
            View detailed information about this community
          </DialogDescription>
        </DialogHeader>

        {isLoading ? (
          <div className="space-y-4">
            <div className="flex items-center space-x-4">
              <div className="h-16 w-16 bg-gray-200 rounded-full animate-pulse"></div>
              <div className="space-y-2">
                <div className="h-4 bg-gray-200 rounded w-32 animate-pulse"></div>
                <div className="h-3 bg-gray-200 rounded w-24 animate-pulse"></div>
              </div>
            </div>
            <div className="space-y-2">
              {[...Array(6)].map((_, i) => (
                <div
                  key={i}
                  className="h-3 bg-gray-200 rounded animate-pulse"
                ></div>
              ))}
            </div>
          </div>
        ) : error ? (
          <div className="text-center py-8">
            <p className="text-red-500">Failed to load community details</p>
            <Button variant="outline" onClick={onClose} className="mt-4">
              Close
            </Button>
          </div>
        ) : communityData?.data?.community ? (
          <div className="space-y-6">
            {/* Community Header */}
            <div className="space-y-4">
              {communityData.data.community.coverPhoto?.url && (
                <div className="relative h-32 w-full rounded-lg overflow-hidden">
                  <Image
                    src={communityData.data.community.coverPhoto.url}
                    alt="Cover photo"
                    fill
                    className="object-cover"
                  />
                </div>
              )}
              <div className="flex items-center space-x-4">
                <Avatar className="h-16 w-16">
                  <AvatarFallback className="text-lg">
                    <Building2 className="h-8 w-8" />
                  </AvatarFallback>
                </Avatar>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold">
                    {communityData.data.community.name}
                  </h3>
                  <p className="text-muted-foreground">
                    {communityData.data.community.description}
                  </p>
                  <div className="flex items-center space-x-2 mt-2">
                    <Badge
                      className={getVisibilityColor(
                        communityData.data.community.communityVisibility
                      )}
                    >
                      {communityData.data.community.communityVisibility}
                    </Badge>
                    <Badge
                      className={getStatusColor(
                        communityData.data.community.isBlocked,
                        communityData.data.community.isDeleted
                      )}
                    >
                      {communityData.data.community.isDeleted
                        ? "Deleted"
                        : communityData.data.community.isBlocked
                        ? "Blocked"
                        : "Active"}
                    </Badge>
                  </div>
                </div>
              </div>
            </div>

            <Separator />

            {/* Community Statistics */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center text-lg">
                  <Building2 className="h-5 w-5 mr-2" />
                  Community Statistics
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-4">
                  <div className="text-center">
                    <p className="text-2xl font-bold text-secondary">
                      {communityData.data.community.membersCount || 0}
                    </p>
                    <p className="text-sm text-muted-foreground">Members</p>
                  </div>
                  <div className="text-center">
                    <p className="text-2xl font-bold text-secondary">
                      {communityData.data.community.postsCount || 0}
                    </p>
                    <p className="text-sm text-muted-foreground">Posts</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Basic Information */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center text-lg">
                  <Building2 className="h-5 w-5 mr-2" />
                  Basic Information
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="flex items-center space-x-3">
                    <User className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">Created By</p>
                      <p className="text-sm text-muted-foreground">
                        {communityData.data.community.createdBy?.fullName ||
                          "N/A"}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-3">
                    <Calendar className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">Created</p>
                      <p className="text-sm text-muted-foreground">
                        {new Date(
                          communityData.data.community.createdAt
                        ).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-3">
                    <Eye className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">Visibility</p>
                      <p className="text-sm text-muted-foreground">
                        {communityData.data.community.communityVisibility}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-3">
                    <Shield className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">Status</p>
                      <p className="text-sm text-muted-foreground">
                        {communityData.data.community.isDeleted
                          ? "Deleted"
                          : communityData.data.community.isBlocked
                          ? "Blocked"
                          : "Active"}
                      </p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Community Rules */}
            {communityData.data.community.rules && (
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center text-lg">
                    <FileText className="h-5 w-5 mr-2" />
                    Community Rules
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                    {communityData.data.community.rules}
                  </p>
                </CardContent>
              </Card>
            )}

            {/* Community Tags */}
            {communityData.data.community.tags &&
              communityData.data.community.tags.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-lg">
                      <Tag className="h-5 w-5 mr-2" />
                      Tags
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-2">
                      {communityData.data.community.tags.map((tag, index) => (
                        <Badge
                          key={index}
                          variant="secondary"
                          className="text-xs capitalize"
                        >
                          {typeof tag === "string" ? tag : tag.tag}
                        </Badge>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}

            {/* Community Members */}
            {communityData.data.community.members &&
              communityData.data.community.members.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-lg">
                      <Users className="h-5 w-5 mr-2" />
                      Recent Members
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                      {communityData.data.community.members
                        .slice(0, 5)
                        .map((member, index) => (
                          <div
                            key={index}
                            className="flex items-center justify-between p-3 border rounded-lg"
                          >
                            <div className="flex items-center space-x-3">
                              <Avatar className="h-8 w-8">
                                <AvatarFallback className="text-xs">
                                  {member.fullName.charAt(0).toUpperCase()}
                                </AvatarFallback>
                              </Avatar>
                              <div>
                                <p className="text-sm font-medium">
                                  {member.fullName}
                                </p>
                              </div>
                            </div>
                            {/* <div className="text-right">
                              <p className="text-xs text-muted-foreground">
                                Joined{" "}
                                {new Date(member.joinedAt).toLocaleDateString()}
                              </p>
                            </div> */}
                          </div>
                        ))}
                      {communityData.data.community.members.length > 5 && (
                        <p className="text-sm text-muted-foreground text-center">
                          And {communityData.data.community.members.length - 5}{" "}
                          more members...
                        </p>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )}

            {/* Community Posts */}
            {communityData.data.community.posts &&
              communityData.data.community.posts.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-lg">
                      <MessageSquare className="h-5 w-5 mr-2" />
                      Recent Posts
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      {communityData.data.community.posts
                        .slice(0, 3)
                        .map((post, index) => (
                          <div
                            key={index}
                            className="flex items-center justify-between p-3 border rounded-lg"
                          >
                            <div className="flex items-center space-x-3">
                              <div className="h-8 w-8 bg-gray-100 rounded-full flex items-center justify-center">
                                <MessageSquare className="h-4 w-4 text-gray-600" />
                              </div>
                              <div>
                                <p className="text-sm font-medium">
                                  Post {index + 1}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  Duration: {post.duration}s
                                </p>
                              </div>
                            </div>
                            <div className="text-right">
                              {post.audioUrl && (
                                <audio controls className="w-32 h-8">
                                  <source
                                    src={post.audioUrl}
                                    type="audio/mpeg"
                                  />
                                  <source
                                    src={post.audioUrl}
                                    type="audio/mp4"
                                  />
                                  <source
                                    src={post.audioUrl}
                                    type="audio/wav"
                                  />
                                  <source
                                    src={post.audioUrl}
                                    type="audio/webm"
                                  />
                                  Your browser does not support the audio
                                  element.
                                </audio>
                              )}
                            </div>
                          </div>
                        ))}
                      {communityData.data.community.posts.length > 3 && (
                        <p className="text-sm text-muted-foreground text-center">
                          And {communityData.data.community.posts.length - 3}{" "}
                          more posts...
                        </p>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )}

            {/* Community Management Actions */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center text-lg">
                  <Shield className="h-5 w-5 mr-2" />
                  Community Management
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  {/* View Posts Button */}
                  <Button
                    variant="default"
                    size="sm"
                    onClick={() => {
                      if (communityData.data.community?.posts?.length == 0)
                        return;
                      router.push(
                        `/communities/${communityData.data.community._id}/posts`
                      );
                      onClose();
                    }}
                    disabled={communityData.data.community?.posts?.length == 0}
                    className="flex items-center space-x-2 gradient-button"
                  >
                    <MessageSquare className="h-4 w-4" />
                    <span>View Posts</span>
                    <ExternalLink className="h-3 w-3" />
                  </Button>

                  {/* Block/Unblock Community */}
                  {communityData.data.community.isBlocked ? (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        handleUnblockCommunity(communityData.data.community._id)
                      }
                      disabled={unblockCommunityMutation.isPending}
                      className="flex items-center space-x-2"
                    >
                      <Unlock className="h-4 w-4" />
                      <span>Unblock</span>
                    </Button>
                  ) : (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        handleBlockCommunity(communityData.data.community._id)
                      }
                      disabled={blockCommunityMutation.isPending}
                      className="flex items-center space-x-2"
                    >
                      <Lock className="h-4 w-4" />
                      <span>Block</span>
                    </Button>
                  )}

                  {/* Delete Community */}
                  <Button
                    variant="destructive"
                    size="sm"
                    onClick={() =>
                      handleDeleteCommunity(communityData.data.community._id)
                    }
                    disabled={deleteCommunityMutation.isPending}
                    className="flex items-center space-x-2"
                  >
                    <Trash2 className="h-4 w-4" />
                    <span>Delete</span>
                  </Button>

                  {/* Edit Community (placeholder for future implementation) */}
                  {/* <Button
                    variant="outline"
                    size="sm"
                    disabled
                    className="flex items-center space-x-2"
                  >
                    <Edit className="h-4 w-4" />
                    <span>Edit</span>
                  </Button> */}
                </div>
              </CardContent>
            </Card>

            {/* Actions */}
            <div className="flex justify-end space-x-2">
              <Button onClick={onClose}>Close</Button>
            </div>
          </div>
        ) : (
          <div className="text-center py-8">
            <p className="text-muted-foreground">Community not found</p>
            <Button variant="outline" onClick={onClose} className="mt-4">
              Close
            </Button>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
