import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Plus, Edit, Trash2, Eye, Globe, Calendar, Star } from "lucide-react";
import { queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { format } from "date-fns";

interface ClubNews {
  id: number;
  title: string;
  content: string;
  excerpt?: string;
  category: string;
  priority: string;
  status: string;
  featuredImageUrl?: string;
  authorId: string;
  publishedAt?: string;
  expiresAt?: string;
  viewCount: number;
  tags?: string[];
  isSticky: boolean;
  allowComments: boolean;
  notifyMembers: boolean;
  createdAt: string;
  updatedAt: string;
}

export default function NewsPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [selectedNews, setSelectedNews] = useState<ClubNews | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    title: "",
    content: "",
    excerpt: "",
    category: "general",
    priority: "normal",
    isSticky: false,
    allowComments: true,
    notifyMembers: false,
  });

  const { data: allNews = [], isLoading: isLoadingAll } = useQuery({
    queryKey: ["/api/club-news"],
  });

  const { data: publishedNews = [], isLoading: isLoadingPublished } = useQuery({
    queryKey: ["/api/club-news", "published"],
    queryFn: () => fetch("/api/club-news?published=true").then(res => res.json()),
  });

  const createNewsMutation = useMutation({
    mutationFn: async (newsData: any) => {
      const response = await fetch("/api/club-news", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newsData),
      });
      if (!response.ok) throw new Error("Failed to create news");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-news"] });
      setIsCreateDialogOpen(false);
      setFormData({
        title: "",
        content: "",
        excerpt: "",
        category: "general",
        priority: "normal",
        isSticky: false,
        allowComments: true,
        notifyMembers: false,
      });
      toast({
        title: "Success",
        description: "News article created successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create news article",
        variant: "destructive",
      });
    },
  });

  const updateNewsMutation = useMutation({
    mutationFn: async ({ id, ...newsData }: any) => {
      const response = await fetch(`/api/club-news/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newsData),
      });
      if (!response.ok) throw new Error("Failed to update news");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-news"] });
      setIsEditDialogOpen(false);
      setSelectedNews(null);
      toast({
        title: "Success",
        description: "News article updated successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update news article",
        variant: "destructive",
      });
    },
  });

  const publishNewsMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await fetch(`/api/club-news/${id}/publish`, {
        method: "POST",
      });
      if (!response.ok) throw new Error("Failed to publish news");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-news"] });
      toast({
        title: "Success",
        description: "News article published successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to publish news article",
        variant: "destructive",
      });
    },
  });

  const deleteNewsMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await fetch(`/api/club-news/${id}`, {
        method: "DELETE",
      });
      if (!response.ok) throw new Error("Failed to delete news");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-news"] });
      toast({
        title: "Success",
        description: "News article deleted successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete news article",
        variant: "destructive",
      });
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedNews) {
      updateNewsMutation.mutate({ id: selectedNews.id, ...formData });
    } else {
      createNewsMutation.mutate(formData);
    }
  };

  const openEditDialog = (news: ClubNews) => {
    setSelectedNews(news);
    setFormData({
      title: news.title,
      content: news.content,
      excerpt: news.excerpt || "",
      category: news.category,
      priority: news.priority,
      isSticky: news.isSticky,
      allowComments: news.allowComments,
      notifyMembers: news.notifyMembers,
    });
    setIsEditDialogOpen(true);
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "urgent": return "destructive";
      case "high": return "orange";
      case "normal": return "default";
      case "low": return "secondary";
      default: return "default";
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "published": return "default";
      case "draft": return "secondary";
      case "archived": return "outline";
      default: return "default";
    }
  };

  const NewsCard = ({ news }: { news: ClubNews }) => (
    <Card className="mb-4">
      <CardHeader>
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <CardTitle className="text-lg">{news.title}</CardTitle>
              {news.isSticky && <Star className="w-4 h-4 text-yellow-500" />}
            </div>
            <div className="flex gap-2">
              <Badge variant={getStatusColor(news.status)}>{news.status}</Badge>
              <Badge variant={getPriorityColor(news.priority)}>{news.priority}</Badge>
              <Badge variant="outline">{news.category}</Badge>
            </div>
          </div>
          <div className="flex gap-2">
            {news.status === "draft" && (
              <Button
                size="sm"
                onClick={() => publishNewsMutation.mutate(news.id)}
                disabled={publishNewsMutation.isPending}
              >
                <Globe className="w-4 h-4 mr-1" />
                Publish
              </Button>
            )}
            <Button
              size="sm"
              variant="outline"
              onClick={() => openEditDialog(news)}
            >
              <Edit className="w-4 h-4" />
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => deleteNewsMutation.mutate(news.id)}
              disabled={deleteNewsMutation.isPending}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        </div>
        {news.excerpt && (
          <CardDescription>{news.excerpt}</CardDescription>
        )}
      </CardHeader>
      <CardContent>
        <div className="text-sm text-muted-foreground space-y-1">
          <div className="flex items-center gap-4">
            <span className="flex items-center gap-1">
              <Eye className="w-3 h-3" />
              {news.viewCount} views
            </span>
            <span className="flex items-center gap-1">
              <Calendar className="w-3 h-3" />
              {format(new Date(news.createdAt), "MMM d, yyyy")}
            </span>
          </div>
          {news.publishedAt && (
            <div>Published: {format(new Date(news.publishedAt), "MMM d, yyyy 'at' h:mm a")}</div>
          )}
        </div>
      </CardContent>
    </Card>
  );

  const NewsForm = () => (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label htmlFor="title">Title</Label>
        <Input
          id="title"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          required
        />
      </div>
      
      <div>
        <Label htmlFor="excerpt">Excerpt (Optional)</Label>
        <Input
          id="excerpt"
          value={formData.excerpt}
          onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
          placeholder="Brief summary of the article"
        />
      </div>

      <div>
        <Label htmlFor="content">Content</Label>
        <Textarea
          id="content"
          value={formData.content}
          onChange={(e) => setFormData({ ...formData, content: e.target.value })}
          rows={8}
          required
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="category">Category</Label>
          <Select
            value={formData.category}
            onValueChange={(value) => setFormData({ ...formData, category: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="general">General</SelectItem>
              <SelectItem value="match">Match</SelectItem>
              <SelectItem value="training">Training</SelectItem>
              <SelectItem value="social">Social</SelectItem>
              <SelectItem value="announcement">Announcement</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label htmlFor="priority">Priority</Label>
          <Select
            value={formData.priority}
            onValueChange={(value) => setFormData({ ...formData, priority: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="low">Low</SelectItem>
              <SelectItem value="normal">Normal</SelectItem>
              <SelectItem value="high">High</SelectItem>
              <SelectItem value="urgent">Urgent</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <div className="space-y-3">
        <div className="flex items-center space-x-2">
          <Switch
            id="isSticky"
            checked={formData.isSticky}
            onCheckedChange={(checked) => setFormData({ ...formData, isSticky: checked })}
          />
          <Label htmlFor="isSticky">Pin to top</Label>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="allowComments"
            checked={formData.allowComments}
            onCheckedChange={(checked) => setFormData({ ...formData, allowComments: checked })}
          />
          <Label htmlFor="allowComments">Allow comments</Label>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="notifyMembers"
            checked={formData.notifyMembers}
            onCheckedChange={(checked) => setFormData({ ...formData, notifyMembers: checked })}
          />
          <Label htmlFor="notifyMembers">Notify all members</Label>
        </div>
      </div>

      <div className="flex gap-2 pt-4">
        <Button type="submit" disabled={createNewsMutation.isPending || updateNewsMutation.isPending}>
          {selectedNews ? "Update Article" : "Create Article"}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            setIsCreateDialogOpen(false);
            setIsEditDialogOpen(false);
            setSelectedNews(null);
            setFormData({
              title: "",
              content: "",
              excerpt: "",
              category: "general",
              priority: "normal",
              isSticky: false,
              allowComments: true,
              notifyMembers: false,
            });
          }}
        >
          Cancel
        </Button>
      </div>
    </form>
  );

  if (!user) {
    return (
      <div className="container mx-auto p-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Access Denied</h1>
          <p>Please log in to manage club news.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">Club News</h1>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="w-4 h-4 mr-2" />
              Create Article
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create News Article</DialogTitle>
              <DialogDescription>
                Create a new article to share with club members
              </DialogDescription>
            </DialogHeader>
            <NewsForm />
          </DialogContent>
        </Dialog>
      </div>

      <Tabs defaultValue="all" className="w-full">
        <TabsList>
          <TabsTrigger value="all">All Articles</TabsTrigger>
          <TabsTrigger value="published">Published</TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="mt-6">
          {isLoadingAll ? (
            <div className="text-center py-8">Loading articles...</div>
          ) : allNews.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No articles found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {allNews.map((news: ClubNews) => (
                <NewsCard key={news.id} news={news} />
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="published" className="mt-6">
          {isLoadingPublished ? (
            <div className="text-center py-8">Loading published articles...</div>
          ) : publishedNews.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No published articles found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {publishedNews.map((news: ClubNews) => (
                <NewsCard key={news.id} news={news} />
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit News Article</DialogTitle>
            <DialogDescription>
              Update the article details
            </DialogDescription>
          </DialogHeader>
          <NewsForm />
        </DialogContent>
      </Dialog>
    </div>
  );
}