"use client";

import { useState, useEffect } from "react";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { formatDate } from "@/lib/utils";
import {
  Calendar,
  Clock,
  MapPin,
  Plus,
  Edit,
  Trash2,
  Search,
  Eye,
} from "lucide-react";
import { usePathname } from "next/navigation";
import { HistoryContent } from "@/models/HistoryContent";
import { useAuth } from "@/hooks/use-auth";

function HistoryManagement() {
  const { user } = useAuth();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const pathname = usePathname();

  const [searchQuery, setSearchQuery] = useState("");
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [selectedHistory, setSelectedHistory] = useState<HistoryContent | null>(
    null
  );
  const [location, setLocation] = useState("");

  // Check if we should auto-open the create dialog based on the URL
  useEffect(() => {
    if (pathname === "/dashboard/history/new") {
      setIsCreateDialogOpen(true);
      // Navigate back to /admin/events to clean up the URL
      setLocation("/dashboard/history");
    }
  }, [location, setLocation]);

  // Fetch events for the museum
  const { data: histories, isLoading } = useQuery({
    queryKey: ["/histories"],
  });

  // Create event mutation
  const createHistoryMutation = useMutation({
    mutationFn: (historyData: any) =>
      apiRequest("POST", "/histories", historyData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/histories"] });
      setIsCreateDialogOpen(false);
      toast({
        title: "History created",
        description: "The history has been created successfully.",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create history. Please try again.",
        variant: "destructive",
      });
    },
  });

  // Update history mutation
  const updateHistoryMutation = useMutation({
    mutationFn: (data: { id: string; updates: Partial<HistoryContent> }) =>
      apiRequest("PATCH", `/histories/${data.id}`, data.updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/histories"] });
      setIsEditDialogOpen(false);
      setSelectedHistory(null);
      toast({
        title: "History updated",
        description: "The history has been updated successfully.",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update event. Please try again.",
        variant: "destructive",
      });
    },
  });

  // Delete history mutation
  const deleteHistoryMutation = useMutation({
    mutationFn: (historyId: string) =>
      apiRequest("DELETE", `/histories/${historyId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/histories"] });
      toast({
        title: "History deleted",
        description: "The history has been deleted successfully.",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete history. Please try again.",
        variant: "destructive",
      });
    },
  });

  const handleCreateHistory = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);

    const historyData = {
      title: formData.get("title") as string,
      slug: (formData.get("slug") as string) || undefined,
      content: formData.get("content") as string,
      metaDescription: formData.get("metaDescription") as string,
      keywords: formData.get("keywords") as string,
      imageUrl: (formData.get("imageUrl") as string) || null,
      authorId: user?.id ?? null,
    };

    createHistoryMutation.mutate(historyData);
  };

  const handleUpdateHistory = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedHistory) return;

    const formData = new FormData(e.target as HTMLFormElement);

    const updates: Partial<HistoryContent> = {
      title: formData.get("title") as string,
      slug: (formData.get("slug") as string) || undefined,
      content: formData.get("content") as string,
      metaDescription: formData.get("metaDescription") as string,
      keywords: formData.get("keywords") as string,
      imageUrl: (formData.get("imageUrl") as string) || null,
      authorId: user?.id ?? null,
    };

    updateHistoryMutation.mutate({ id: selectedHistory.id, updates });
  };

  const handleDeleteEvent = (historyId: string) => {
    if (confirm("Are you sure you want to delete this event?")) {
      deleteHistoryMutation.mutate(historyId);
    }
  };

  const filteredHistories = Array.isArray(histories)
    ? histories.filter(
        (history: HistoryContent) =>
          history.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          history.metaDescription
            .toLowerCase()
            .includes(searchQuery.toLowerCase())
      )
    : [];

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-3xl font-playfair font-bold text-primary">
            History Management
          </h1>
          <p className="text-muted-foreground mt-1">
            Manage your museum's History
          </p>
        </div>

        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button className="bg-primary hover:bg-primary/90">
              <Plus className="w-4 h-4 mr-2" />
              Create History
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Create New History</DialogTitle>
              <DialogDescription>
                Add a new History for your museum
              </DialogDescription>
            </DialogHeader>

            <form onSubmit={handleCreateHistory} className="space-y-4">
              <div>
                <Label htmlFor="title">Title</Label>
                <Input id="title" name="title" required />
              </div>

              <div>
                <Label htmlFor="content">Content</Label>
                <Textarea id="content" name="content" rows={6} required />
              </div>

              <div>
                <Label htmlFor="metaDescription">Meta Description</Label>
                <Textarea
                  id="metaDescription"
                  name="metaDescription"
                  rows={3}
                />
              </div>

              <div>
                <Label htmlFor="keywords">Keywords (comma separated)</Label>
                <Input id="keywords" name="keywords" />
              </div>

              <div>
                <Label htmlFor="imageUrl">Image URL</Label>
                <Input id="imageUrl" name="imageUrl" type="url" />
              </div>

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsCreateDialogOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  disabled={createHistoryMutation.isPending}
                >
                  {createHistoryMutation.isPending
                    ? "Creating..."
                    : "Create History"}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center">
              <Calendar className="h-8 w-8 text-primary" />
              <div className="ml-4">
                <p className="text-sm font-medium text-muted-foreground">
                  Total Histories
                </p>
                <p className="text-2xl font-bold">{filteredHistories.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Search and Filter */}
      <Card className="mb-6">
        <CardContent className="p-6">
          <div className="flex items-center space-x-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
              <Input
                placeholder="Search histories..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Edit History Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Edit History</DialogTitle>
            <DialogDescription>Update history information</DialogDescription>
          </DialogHeader>

          {selectedHistory && (
            <form onSubmit={handleUpdateHistory} className="space-y-4">
              <div>
                <Label htmlFor="edit-title">Title</Label>
                <Input
                  id="edit-title"
                  name="title"
                  defaultValue={selectedHistory.title}
                  required
                />
              </div>

              <div>
                <Label htmlFor="edit-content">Content</Label>
                <Textarea
                  id="edit-content"
                  name="content"
                  rows={6}
                  defaultValue={selectedHistory.content}
                  required
                />
              </div>

              <div>
                <Label htmlFor="edit-metaDescription">Meta Description</Label>
                <Textarea
                  id="edit-metaDescription"
                  name="metaDescription"
                  rows={3}
                  defaultValue={selectedHistory.metaDescription}
                />
              </div>

              <div>
                <Label htmlFor="edit-keywords">
                  Keywords (comma separated)
                </Label>
                <Input
                  id="edit-keywords"
                  name="keywords"
                  defaultValue={selectedHistory.keywords}
                />
              </div>

              <div>
                <Label htmlFor="edit-imageUrl">Image URL</Label>
                <Input
                  id="edit-imageUrl"
                  name="imageUrl"
                  type="url"
                  defaultValue={selectedHistory.imageUrl ?? ""}
                />
              </div>

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsEditDialogOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  disabled={updateHistoryMutation.isPending}
                >
                  {updateHistoryMutation.isPending
                    ? "Updating..."
                    : "Update History"}
                </Button>
              </DialogFooter>
            </form>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default HistoryManagement;
