import { useRoute, useLocation, Link } from "wouter";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Eye, MessageCircle, ThumbsUp, Pin, Search, Info, Settings, User, LogOut } from "lucide-react";
import type { MediaOutlet, CommunityPost } from "@shared/schema";
import { queryClient, apiRequest } from "@/lib/queryClient";
import SearchModal from "@/components/SearchModal";
import LoginModal from "@/components/LoginModal";

export default function Community() {
  const [, params] = useRoute("/media/:slug/community");
  const [, setLocation] = useLocation();
  const { user, isAuthenticated } = useAuth();
  const [isNewPostOpen, setIsNewPostOpen] = useState(false);
  const [sortBy, setSortBy] = useState("latest");
  const [searchTerm, setSearchTerm] = useState("");
  const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);
  const [isLoginModalOpen, setIsLoginModalOpen] = useState(false);
  const [enlargedImage, setEnlargedImage] = useState<string | null>(null);

  const slug = params?.slug || '';

  const { data: outlet, isLoading: outletLoading } = useQuery<MediaOutlet>({
    queryKey: ["/api/media-outlets", slug],
    enabled: !!slug
  });

  const { data: posts = [], isLoading: postsLoading } = useQuery<CommunityPost[]>({
    queryKey: [`/api/media-outlets/${slug}/community?sort=${sortBy}`],
    enabled: !!slug && !!outlet
  });

  const createPostMutation = useMutation({
    mutationFn: async (data: { title: string; content: string; imageUrl?: string }) => {
      return await apiRequest("POST", `/api/media-outlets/${slug}/community`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ 
        predicate: (query) => 
          query.queryKey[0]?.toString().startsWith(`/api/media-outlets/${slug}/community`) ?? false
      });
      setIsNewPostOpen(false);
    }
  });

  const handleLogout = async () => {
    try {
      const response = await fetch("/api/logout", {
        method: "POST",
        credentials: "include",
      });
      if (response.ok) {
        window.location.href = "/";
      }
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  const handleAdminPage = () => {
    if (user?.role === "admin" || user?.role === "superadmin") {
      setLocation("/admin");
    }
  };

  const formatTimeAgo = (createdAt: Date | string | null) => {
    if (!createdAt) return "";
    const now = new Date();
    const postDate = new Date(createdAt);
    const diffInMs = now.getTime() - postDate.getTime();
    const diffInMinutes = Math.floor(diffInMs / 60000);
    
    if (diffInMinutes < 1) return "방금";
    if (diffInMinutes < 60) return `${diffInMinutes}분 전`;
    
    const diffInHours = Math.floor(diffInMinutes / 60);
    if (diffInHours < 24) return `${diffInHours}시간 전`;
    
    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays < 30) return `${diffInDays}일 전`;
    
    return postDate.toLocaleDateString('ko-KR');
  };

  const filteredPosts = posts.filter(post => 
    searchTerm === "" || 
    post.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    post.content.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const pinnedPosts = filteredPosts.filter(post => post.isPinned || post.isNotice);
  const regularPosts = filteredPosts.filter(post => !post.isPinned && !post.isNotice);

  if (outletLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">로딩 중...</p>
        </div>
      </div>
    );
  }

  if (!outlet) {
    return <div>미디어 아울렛을 찾을 수 없습니다</div>;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              {outlet.imageUrl ? (
                <img 
                  src={outlet.imageUrl} 
                  alt={outlet.name}
                  className="w-10 h-10 rounded-full object-cover cursor-pointer hover:ring-2 hover:ring-blue-400 transition-all"
                  onClick={() => setEnlargedImage(outlet.imageUrl!)}
                  data-testid="image-outlet-header-profile"
                />
              ) : (
                <div className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center">
                  <span className="text-gray-600 font-bold text-sm">
                    {outlet.name.charAt(0)}
                  </span>
                </div>
              )}
              <div className="flex flex-col cursor-pointer hover:opacity-80 transition-opacity mt-1" onClick={() => setLocation(`/media/${slug}`)}>
                <img 
                  src="/attached_assets/logo_black_1759162717640.png" 
                  alt="SAPIENS" 
                  className="h-2.5 w-auto max-w-[70px] mb-0.5"
                  data-testid="logo-sapiens"
                />
                <div className="flex items-center space-x-1.5">
                  <span className="text-lg font-bold text-gray-900" data-testid="text-outlet-name-header">
                    {outlet.name}
                  </span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      setLocation(`/media/${outlet.slug}/report`);
                    }}
                    className="h-auto p-1"
                    aria-label="View profile"
                    data-testid="button-profile"
                  >
                    Profile
                  </Button>
                </div>
              </div>
            </div>
            
            <div className="flex items-center space-x-4">
              <div 
                className="relative cursor-pointer"
                onClick={() => setIsSearchModalOpen(true)}
                data-testid="search-container"
              >
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
                <Input 
                  type="text" 
                  placeholder="Search the website" 
                  className="w-80 pl-10 bg-gray-50 border-gray-200 cursor-pointer"
                  readOnly
                  data-testid="input-search"
                />
              </div>

              {isAuthenticated && user && (
                <div className="flex items-center space-x-2">
                  {(user.role === 'admin' || user.role === 'superadmin') && (
                    <Button 
                      variant="ghost" 
                      size="sm" 
                      onClick={handleAdminPage}
                      data-testid="button-admin"
                    >
                      <Settings className="h-4 w-4" />
                    </Button>
                  )}
                  <span className="text-sm text-gray-700" data-testid="text-user-name">{user.firstName || user.email}</span>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={handleLogout}
                    data-testid="button-logout"
                  >
                    <LogOut className="h-4 w-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      <SearchModal 
        isOpen={isSearchModalOpen}
        onClose={() => setIsSearchModalOpen(false)}
      />

      {enlargedImage && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4"
          onClick={() => setEnlargedImage(null)}
        >
          <img 
            src={enlargedImage} 
            alt="Enlarged view"
            className="max-w-full max-h-full object-contain"
          />
        </div>
      )}

      {/* Community Content */}
      <main className="max-w-7xl mx-auto px-6 py-8">
        {/* Community Header */}
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900" data-testid="text-community-title">
              {outlet.name} 커뮤니티
            </h1>
            <p className="text-sm text-gray-600 mt-1">자유롭게 의견을 나눠보세요</p>
          </div>
          
          <Dialog open={isNewPostOpen} onOpenChange={setIsNewPostOpen}>
            <DialogTrigger asChild>
              <Button 
                onClick={(e) => {
                  if (!isAuthenticated) {
                    e.preventDefault();
                    setIsLoginModalOpen(true);
                  }
                }}
                data-testid="button-new-post"
              >
                글쓰기
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl" data-testid="dialog-new-post">
              <DialogHeader>
                <DialogTitle>새 글 작성</DialogTitle>
              </DialogHeader>
              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                createPostMutation.mutate({
                  title: formData.get('title') as string,
                  content: formData.get('content') as string,
                  imageUrl: formData.get('imageUrl') as string || undefined
                });
              }}>
                <div className="space-y-4">
                  <div>
                    <Input 
                      name="title" 
                      placeholder="제목을 입력하세요" 
                      required 
                      data-testid="input-post-title"
                    />
                  </div>
                  <div>
                    <Textarea 
                      name="content" 
                      placeholder="내용을 입력하세요" 
                      rows={10}
                      required 
                      data-testid="textarea-post-content"
                    />
                  </div>
                  <div>
                    <Input 
                      name="imageUrl" 
                      placeholder="이미지 URL (선택사항)" 
                      data-testid="input-post-image-url"
                    />
                  </div>
                  <div className="flex justify-end space-x-2">
                    <Button type="button" variant="outline" onClick={() => setIsNewPostOpen(false)} data-testid="button-cancel-post">
                      취소
                    </Button>
                    <Button type="submit" disabled={createPostMutation.isPending} data-testid="button-submit-post">
                      {createPostMutation.isPending ? '작성 중...' : '작성하기'}
                    </Button>
                  </div>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Controls */}
        <div className="mb-4 flex items-center justify-between bg-white p-4 rounded-lg border border-gray-200">
          <div className="flex items-center space-x-4">
            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="w-32" data-testid="select-sort">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="latest">최신순</SelectItem>
                <SelectItem value="views">조회순</SelectItem>
                <SelectItem value="likes">추천순</SelectItem>
                <SelectItem value="replies">댓글순</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input 
              type="text" 
              placeholder="검색" 
              className="w-64 pl-10"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              data-testid="input-search-posts"
            />
          </div>
        </div>

        {/* Posts List */}
        {postsLoading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">로딩 중...</p>
          </div>
        ) : (
          <div className="space-y-1">
            {/* Pinned/Notice Posts */}
            {pinnedPosts.map((post) => (
              <Link key={post.id} href={`/media/${slug}/community/${post.id}`}>
                <Card 
                  className="p-4 hover:bg-gray-50 transition-colors cursor-pointer border-l-4 border-l-red-500" 
                  data-testid={`card-post-${post.id}`}
                >
                  <div className="flex items-center space-x-4">
                    {post.imageUrl && (
                      <img 
                        src={post.imageUrl} 
                        alt={post.title}
                        className="w-16 h-16 object-cover rounded flex-shrink-0"
                        data-testid={`image-post-${post.id}`}
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2 mb-1">
                        {post.isNotice && (
                          <Badge variant="destructive" className="text-xs" data-testid={`badge-notice-${post.id}`}>
                            공지
                          </Badge>
                        )}
                        {post.isPinned && !post.isNotice && (
                          <Badge variant="secondary" className="text-xs" data-testid={`badge-pin-${post.id}`}>
                            <Pin className="h-3 w-3 mr-1" />
                            고정
                          </Badge>
                        )}
                      </div>
                      <h3 className="font-medium text-gray-900 truncate" data-testid={`text-post-title-${post.id}`}>
                        {post.title}
                      </h3>
                      <div className="flex items-center space-x-4 mt-2 text-xs text-gray-500">
                        <span data-testid={`text-post-time-${post.id}`}>{formatTimeAgo(post.createdAt)}</span>
                        <div className="flex items-center space-x-1" data-testid={`stat-views-${post.id}`}>
                          <Eye className="h-3 w-3" />
                          <span>{post.viewCount}</span>
                        </div>
                        <div className="flex items-center space-x-1" data-testid={`stat-replies-${post.id}`}>
                          <MessageCircle className="h-3 w-3" />
                          <span>{post.replyCount}</span>
                        </div>
                        <div className="flex items-center space-x-1" data-testid={`stat-likes-${post.id}`}>
                          <ThumbsUp className="h-3 w-3" />
                          <span>{post.likeCount}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </Card>
              </Link>
            ))}

            {/* Regular Posts */}
            {regularPosts.map((post) => (
              <Link key={post.id} href={`/media/${slug}/community/${post.id}`}>
                <Card 
                  className="p-4 hover:bg-gray-50 transition-colors cursor-pointer" 
                  data-testid={`card-post-${post.id}`}
                >
                  <div className="flex items-center space-x-4">
                    {post.imageUrl && (
                      <img 
                        src={post.imageUrl} 
                        alt={post.title}
                        className="w-16 h-16 object-cover rounded flex-shrink-0"
                        data-testid={`image-post-${post.id}`}
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium text-gray-900 truncate" data-testid={`text-post-title-${post.id}`}>
                        {post.title}
                      </h3>
                      <div className="flex items-center space-x-4 mt-2 text-xs text-gray-500">
                        <span data-testid={`text-post-time-${post.id}`}>{formatTimeAgo(post.createdAt)}</span>
                        <div className="flex items-center space-x-1" data-testid={`stat-views-${post.id}`}>
                          <Eye className="h-3 w-3" />
                          <span>{post.viewCount}</span>
                        </div>
                        <div className="flex items-center space-x-1" data-testid={`stat-replies-${post.id}`}>
                          <MessageCircle className="h-3 w-3" />
                          <span>{post.replyCount}</span>
                        </div>
                        <div className="flex items-center space-x-1" data-testid={`stat-likes-${post.id}`}>
                          <ThumbsUp className="h-3 w-3" />
                          <span>{post.likeCount}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </Card>
              </Link>
            ))}

            {filteredPosts.length === 0 && (
              <div className="text-center py-12">
                <p className="text-gray-500">아직 작성된 글이 없습니다.</p>
              </div>
            )}
          </div>
        )}
      </main>

      <LoginModal 
        isOpen={isLoginModalOpen} 
        onClose={() => setIsLoginModalOpen(false)} 
      />
    </div>
  );
}
