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, MousePointer, Calendar, Image } 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 ClubBanner {
  id: number;
  title: string;
  description?: string;
  imageUrl: string;
  linkUrl?: string;
  position: string;
  displayOrder: number;
  startDate?: string;
  endDate?: string;
  isActive: boolean;
  targetAudience: string;
  clickCount: number;
  viewCount: number;
  backgroundColor?: string;
  textColor?: string;
  borderStyle?: string;
  animationType?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

export default function BannersPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [selectedBanner, setSelectedBanner] = useState<ClubBanner | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    imageUrl: "",
    linkUrl: "",
    position: "header",
    displayOrder: 0,
    startDate: "",
    endDate: "",
    isActive: true,
    targetAudience: "all",
    backgroundColor: "",
    textColor: "",
    borderStyle: "",
    animationType: "none",
  });

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

  const { data: activeBanners = [], isLoading: isLoadingActive } = useQuery({
    queryKey: ["/api/club-banners", "active"],
    queryFn: () => fetch("/api/club-banners?active=true").then(res => res.json()),
  });

  const createBannerMutation = useMutation({
    mutationFn: async (bannerData: any) => {
      const response = await fetch("/api/club-banners", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...bannerData,
          displayOrder: parseInt(bannerData.displayOrder),
        }),
      });
      if (!response.ok) throw new Error("Failed to create banner");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-banners"] });
      setIsCreateDialogOpen(false);
      resetForm();
      toast({
        title: "Success",
        description: "Banner created successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create banner",
        variant: "destructive",
      });
    },
  });

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

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

  const resetForm = () => {
    setFormData({
      title: "",
      description: "",
      imageUrl: "",
      linkUrl: "",
      position: "header",
      displayOrder: 0,
      startDate: "",
      endDate: "",
      isActive: true,
      targetAudience: "all",
      backgroundColor: "",
      textColor: "",
      borderStyle: "",
      animationType: "none",
    });
  };

  const openEditDialog = (banner: ClubBanner) => {
    setSelectedBanner(banner);
    setFormData({
      title: banner.title,
      description: banner.description || "",
      imageUrl: banner.imageUrl,
      linkUrl: banner.linkUrl || "",
      position: banner.position,
      displayOrder: banner.displayOrder,
      startDate: banner.startDate ? banner.startDate.split('T')[0] : "",
      endDate: banner.endDate ? banner.endDate.split('T')[0] : "",
      isActive: banner.isActive,
      targetAudience: banner.targetAudience,
      backgroundColor: banner.backgroundColor || "",
      textColor: banner.textColor || "",
      borderStyle: banner.borderStyle || "",
      animationType: banner.animationType || "none",
    });
    setIsEditDialogOpen(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedBanner) {
      updateBannerMutation.mutate({ id: selectedBanner.id, ...formData });
    } else {
      createBannerMutation.mutate(formData);
    }
  };

  const getPositionColor = (position: string) => {
    switch (position) {
      case "header": return "default";
      case "sidebar": return "secondary";
      case "footer": return "outline";
      case "popup": return "destructive";
      default: return "default";
    }
  };

  const BannerCard = ({ banner }: { banner: ClubBanner }) => (
    <Card className="mb-4">
      <CardHeader>
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <CardTitle className="text-lg flex items-center gap-2">
              <Image className="w-5 h-5" />
              {banner.title}
            </CardTitle>
            <div className="flex gap-2">
              <Badge variant={banner.isActive ? "default" : "secondary"}>
                {banner.isActive ? "Active" : "Inactive"}
              </Badge>
              <Badge variant={getPositionColor(banner.position)}>{banner.position}</Badge>
              <Badge variant="outline">{banner.targetAudience}</Badge>
              <Badge variant="outline">Order: {banner.displayOrder}</Badge>
            </div>
          </div>
          <div className="flex gap-2">
            <Button
              size="sm"
              variant="outline"
              onClick={() => openEditDialog(banner)}
            >
              <Edit className="w-4 h-4" />
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => deleteBannerMutation.mutate(banner.id)}
              disabled={deleteBannerMutation.isPending}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        </div>
        {banner.description && (
          <CardDescription>{banner.description}</CardDescription>
        )}
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {banner.imageUrl && (
            <div className="border rounded-lg overflow-hidden">
              <img
                src={banner.imageUrl}
                alt={banner.title}
                className="w-full h-32 object-cover"
                onError={(e) => {
                  e.currentTarget.style.display = 'none';
                }}
              />
            </div>
          )}
          
          <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" />
                {banner.viewCount} views
              </span>
              <span className="flex items-center gap-1">
                <MousePointer className="w-3 h-3" />
                {banner.clickCount} clicks
              </span>
              <span className="flex items-center gap-1">
                <Calendar className="w-3 h-3" />
                {format(new Date(banner.createdAt), "MMM d, yyyy")}
              </span>
            </div>
            
            {banner.startDate && (
              <div>Starts: {format(new Date(banner.startDate), "MMM d, yyyy")}</div>
            )}
            
            {banner.endDate && (
              <div>Ends: {format(new Date(banner.endDate), "MMM d, yyyy")}</div>
            )}
            
            {banner.linkUrl && (
              <div className="truncate">
                Link: <a href={banner.linkUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                  {banner.linkUrl}
                </a>
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );

  const BannerForm = () => (
    <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="description">Description (Optional)</Label>
        <Textarea
          id="description"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          rows={2}
        />
      </div>

      <div>
        <Label htmlFor="imageUrl">Image URL</Label>
        <Input
          id="imageUrl"
          value={formData.imageUrl}
          onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
          placeholder="https://example.com/banner.jpg"
          required
        />
      </div>

      <div>
        <Label htmlFor="linkUrl">Link URL (Optional)</Label>
        <Input
          id="linkUrl"
          value={formData.linkUrl}
          onChange={(e) => setFormData({ ...formData, linkUrl: e.target.value })}
          placeholder="https://example.com/page"
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="position">Position</Label>
          <Select
            value={formData.position}
            onValueChange={(value) => setFormData({ ...formData, position: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="header">Header</SelectItem>
              <SelectItem value="sidebar">Sidebar</SelectItem>
              <SelectItem value="footer">Footer</SelectItem>
              <SelectItem value="popup">Popup</SelectItem>
              <SelectItem value="homepage">Homepage</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label htmlFor="displayOrder">Display Order</Label>
          <Input
            id="displayOrder"
            type="number"
            value={formData.displayOrder}
            onChange={(e) => setFormData({ ...formData, displayOrder: parseInt(e.target.value) || 0 })}
            min="0"
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="startDate">Start Date (Optional)</Label>
          <Input
            id="startDate"
            type="date"
            value={formData.startDate}
            onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
          />
        </div>

        <div>
          <Label htmlFor="endDate">End Date (Optional)</Label>
          <Input
            id="endDate"
            type="date"
            value={formData.endDate}
            onChange={(e) => setFormData({ ...formData, endDate: e.target.value })}
          />
        </div>
      </div>

      <div>
        <Label htmlFor="targetAudience">Target Audience</Label>
        <Select
          value={formData.targetAudience}
          onValueChange={(value) => setFormData({ ...formData, targetAudience: value })}
        >
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Users</SelectItem>
            <SelectItem value="members">Members Only</SelectItem>
            <SelectItem value="visitors">Visitors Only</SelectItem>
            <SelectItem value="specific_role">Specific Role</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="backgroundColor">Background Color (Optional)</Label>
          <Input
            id="backgroundColor"
            value={formData.backgroundColor}
            onChange={(e) => setFormData({ ...formData, backgroundColor: e.target.value })}
            placeholder="#ffffff"
          />
        </div>

        <div>
          <Label htmlFor="textColor">Text Color (Optional)</Label>
          <Input
            id="textColor"
            value={formData.textColor}
            onChange={(e) => setFormData({ ...formData, textColor: e.target.value })}
            placeholder="#000000"
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="borderStyle">Border Style (Optional)</Label>
          <Input
            id="borderStyle"
            value={formData.borderStyle}
            onChange={(e) => setFormData({ ...formData, borderStyle: e.target.value })}
            placeholder="1px solid #ccc"
          />
        </div>

        <div>
          <Label htmlFor="animationType">Animation</Label>
          <Select
            value={formData.animationType}
            onValueChange={(value) => setFormData({ ...formData, animationType: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="none">None</SelectItem>
              <SelectItem value="fade">Fade</SelectItem>
              <SelectItem value="slide">Slide</SelectItem>
              <SelectItem value="bounce">Bounce</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

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

      <div className="flex gap-2 pt-4">
        <Button type="submit" disabled={createBannerMutation.isPending || updateBannerMutation.isPending}>
          {selectedBanner ? "Update Banner" : "Create Banner"}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            setIsCreateDialogOpen(false);
            setIsEditDialogOpen(false);
            setSelectedBanner(null);
            resetForm();
          }}
        >
          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 banners.</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 Banners</h1>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="w-4 h-4 mr-2" />
              Create Banner
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create Banner</DialogTitle>
              <DialogDescription>
                Create a new banner for club promotion
              </DialogDescription>
            </DialogHeader>
            <BannerForm />
          </DialogContent>
        </Dialog>
      </div>

      <Tabs defaultValue="all" className="w-full">
        <TabsList>
          <TabsTrigger value="all">All Banners</TabsTrigger>
          <TabsTrigger value="active">Active Banners</TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="mt-6">
          {isLoadingAll ? (
            <div className="text-center py-8">Loading banners...</div>
          ) : allBanners.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No banners found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {allBanners.map((banner: ClubBanner) => (
                <BannerCard key={banner.id} banner={banner} />
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="active" className="mt-6">
          {isLoadingActive ? (
            <div className="text-center py-8">Loading active banners...</div>
          ) : activeBanners.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No active banners found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {activeBanners.map((banner: ClubBanner) => (
                <BannerCard key={banner.id} banner={banner} />
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

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