// Updated page.tsx with gift categories and summary sections

"use client";

import React, { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import {
  AlertTriangle,
  ChevronRight,
  Edit,
  ExternalLink,
  Loader2,
  MoreHorizontal,
  Plus,
  Search,
  Trash,
} from "lucide-react";
import { useEvents } from "@/context/event-context";
import { useGifts } from "@/context/gift-context";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { GiftPriority, GiftStatus } from "@/client/types.gen";
import { CategoryModal } from "@/components/gifts/category-modal";
import { GiftModal } from "@/components/gifts/gift-modal";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

export default function GiftRegistryPage() {
  const { slug } = useParams<{ slug: string }>();
  const { event, fetchEventBySlug, isLoadingEvent, eventError } = useEvents();
  const {
    categories,
    items,
    isLoadingCategories,
    isLoadingItems,
    purchases,
    error,
    refetchCategories,
    refetchItems,
    currentEventId,
    setCurrentEventId,
    deleteItem,
  } = useGifts();

  // State for modals
  const [isAddGiftModalOpen, setIsAddGiftModalOpen] = useState(false);
  const [isEditGiftModalOpen, setIsEditGiftModalOpen] = useState(false);
  const [isAddCategoryModalOpen, setIsAddCategoryModalOpen] = useState(false);
  const [isEditCategoryModalOpen, setIsEditCategoryModalOpen] = useState(false);
  const [selectedGiftId, setSelectedGiftId] = useState<string | null>(null);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(
    null,
  );

  // State for filtering and searching
  const [searchQuery, setSearchQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<string>("all");

  // Filter items based on search query and filters
  const filteredItems = items
    ? items.filter((item) => {
        // Filter by search query
        const matchesSearch =
          searchQuery === "" ||
          item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          item.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
          item.store_name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
          item.brand?.toLowerCase().includes(searchQuery.toLowerCase());

        // Filter by category
        const matchesCategory =
          categoryFilter === "all" || item.category_id === categoryFilter;

        // Filter by status
        const matchesStatus =
          statusFilter === "all" || item.status === statusFilter;

        return matchesSearch && matchesCategory && matchesStatus;
      })
    : [];

  // Helper to get status badge with color
  const getStatusBadge = (status: GiftStatus | null | undefined) => {
    if (!status) return null;

    const statusStyles: Record<GiftStatus, string> = {
      available:
        "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300",
      reserved:
        "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300",
      purchased:
        "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300",
      received:
        "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300",
      removed: "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300",
    };

    return (
      <div className="flex items-center gap-2">
        <div className="h-2 w-2 rounded-full bg-current"></div>
        <Badge variant="outline" className={statusStyles[status]}>
          {status.toUpperCase()}
        </Badge>
      </div>
    );
  };

  // Helper to get priority badge with color
  const getPriorityBadge = (priority: GiftPriority | null | undefined) => {
    if (!priority) return null;

    const priorityStyles: Record<GiftPriority, string> = {
      low: "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300",
      medium: "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300",
      high: "bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300",
      must_have: "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300",
    };

    const priorityLabels: Record<GiftPriority, string> = {
      low: "LOW",
      medium: "MEDIUM",
      high: "HIGH",
      must_have: "MUST-HAVE",
    };

    return (
      <Badge variant="outline" className={priorityStyles[priority]}>
        {priorityLabels[priority]}
      </Badge>
    );
  };

  // Calculate summary statistics
  const summaryStats = {
    totalItems: items?.length || 0,
    totalCategories: categories?.length || 0,
    availableItems:
      items?.filter((item) => item.status === GiftStatus.AVAILABLE).length || 0,
    availableQuantity:
      items
        ?.filter((item) => item.status === GiftStatus.AVAILABLE)
        .reduce((acc, item) => acc + (item.quantity_requested || 1), 0) || 0,
    reservedItems:
      items?.filter((item) => item.status === GiftStatus.RESERVED).length || 0,
    reservedQuantity:
      items
        ?.filter((item) => item.status === GiftStatus.RESERVED)
        .reduce((acc, item) => acc + (item.quantity_requested || 1), 0) || 0,
    purchasedItems:
      items?.filter((item) => item.status === GiftStatus.PURCHASED).length || 0,
    purchasedQuantity:
      items
        ?.filter((item) => item.status === GiftStatus.PURCHASED)
        .reduce((acc, item) => acc + (item.quantity_requested || 1), 0) || 0,
    receivedItems:
      items?.filter((item) => item.status === GiftStatus.RECEIVED).length || 0,
    receivedQuantity:
      items
        ?.filter((item) => item.status === GiftStatus.RECEIVED)
        .reduce((acc, item) => acc + (item.quantity_requested || 1), 0) || 0,
  };

  // Functions to handle modal actions
  const handleAddGift = () => {
    setIsAddGiftModalOpen(true);
  };

  const handleDeleteGift = async (id: string) => {
    await deleteItem(id);
    await refetchItems(undefined, event?.id);
  };

  const handleEditGift = (giftId: string) => {
    setSelectedGiftId(giftId);
    setIsEditGiftModalOpen(true);
  };

  const handleAddCategory = () => {
    setIsAddCategoryModalOpen(true);
  };

  const handleEditCategory = (categoryId: string) => {
    setSelectedCategoryId(categoryId);
    setIsEditCategoryModalOpen(true);
  };

  // Load event and gift data
  useEffect(() => {
    fetchEventBySlug(slug);
  }, [slug, fetchEventBySlug]);

  useEffect(() => {
    if (event?.id) {
      setCurrentEventId(event.id);
      refetchCategories(event.id);
      refetchItems(undefined, event.id);
    }
  }, [event, setCurrentEventId, refetchCategories, refetchItems]);

  // Loading state
  if (isLoadingEvent || isLoadingCategories || isLoadingItems) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <Loader2 className="h-8 w-8 animate-spin text-blue-500" />
        <span className="ml-2">Loading gift registry...</span>
      </div>
    );
  }

  // Error state
  if (eventError || error) {
    return (
      <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative flex items-center">
        <AlertTriangle className="h-5 w-5 mr-2" />
        <span>
          Error loading gift registry: {(eventError || error)?.message}
        </span>
      </div>
    );
  }

  // Not found state
  if (!event) {
    return (
      <Card className="max-w-3xl mx-auto">
        <CardHeader>
          <CardTitle>Event Not Found</CardTitle>
        </CardHeader>
        <CardContent>
          <p>
            The event you're looking for doesn't exist or may have been removed.
          </p>
          <Button asChild className="mt-4">
            <Link href="/dashboard">Return to Dashboard</Link>
          </Button>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <header className="mb-8 flex justify-between items-start">
        <div>
          {/*<h1 className="text-4xl font-bold tracking-tight">EVENTSPACE</h1>*/}
          <div className="mt-2 text-gray-500 dark:text-gray-400">
            Admin • {event.title}
          </div>
        </div>
      </header>

      {/* Breadcrumb Navigation */}
      <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
        <Link
          href="/dashboard"
          className="hover:text-gray-700 dark:hover:text-gray-300"
        >
          Dashboard
        </Link>
        <ChevronRight className="mx-1 h-4 w-4" />
        <Link
          href="/dashboard/events"
          className="hover:text-gray-700 dark:hover:text-gray-300"
        >
          Events
        </Link>
        <ChevronRight className="mx-1 h-4 w-4" />
        <Link
          href={`/dashboard/events/${slug}`}
          className="hover:text-gray-700 dark:hover:text-gray-300"
        >
          {event.title}
        </Link>
        <ChevronRight className="mx-1 h-4 w-4" />
        <span className="text-gray-900 dark:text-gray-100">Gift Registry</span>
      </div>

      {/* Gift Registry Content */}
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold">GIFT REGISTRY MANAGEMENT</h2>
          <Button
            className="bg-blue-600 hover:bg-blue-700"
            onClick={handleAddGift}
          >
            <Plus className="mr-2 h-4 w-4" /> Add Gift
          </Button>
        </div>

        {/* Filters and Search */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div className="flex flex-wrap gap-2">
            <div className="flex items-center gap-2">
              <span className="text-sm">Filter by:</span>
              <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                <SelectTrigger className="w-[150px]">
                  <SelectValue placeholder="Category" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Categories</SelectItem>
                  {categories?.map((category) => (
                    <SelectItem key={category.id} value={category.id}>
                      {category.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center gap-2">
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-[150px]">
                  <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Statuses</SelectItem>
                  <SelectItem value={GiftStatus.AVAILABLE}>
                    Available
                  </SelectItem>
                  <SelectItem value={GiftStatus.RESERVED}>Reserved</SelectItem>
                  <SelectItem value={GiftStatus.PURCHASED}>
                    Purchased
                  </SelectItem>
                  <SelectItem value={GiftStatus.RECEIVED}>Received</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
            <Input
              placeholder="Search gifts..."
              className="pl-8"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>

        {/* Gift Items Table */}
        <div className="rounded-md border overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Category</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>Qty</TableHead>
                <TableHead>Price</TableHead>
                <TableHead>Priority</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredItems.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    No gifts found. Add your first gift!
                  </TableCell>
                </TableRow>
              ) : (
                filteredItems.map((item) => {
                  const category = categories?.find(
                    (c) => c.id === item.category_id,
                  );
                  const canShowReservations = item.status
                    ? (
                        [
                          GiftStatus.RESERVED,
                          GiftStatus.RECEIVED,
                        ] as GiftStatus[]
                      ).includes(item.status)
                    : false;

                  return (
                    <React.Fragment key={item.id}>
                      <TableRow>
                        <TableCell>
                          {category?.name || "Uncategorized"}
                        </TableCell>

                        <TableCell className="flex items-center gap-2 font-medium">
                          {/* Purchase URL clickable icon */}
                          {item.purchase_url ? (
                            <Link
                              href={item.purchase_url}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              <ExternalLink className="w-4 h-4 text-blue-500 hover:text-blue-600" />
                            </Link>
                          ) : (
                            <ExternalLink className="w-4 h-4 text-gray-300 cursor-not-allowed" />
                          )}
                          {item.name}
                        </TableCell>

                        <TableCell>{item.quantity_requested || 1}</TableCell>
                        <TableCell>{item.formatted_price || "-"}</TableCell>
                        <TableCell>{getPriorityBadge(item.priority)}</TableCell>

                        <TableCell>
                          {canShowReservations ? (
                            <Popover>
                              <PopoverTrigger asChild>
                                <div className="cursor-pointer">
                                  {getStatusBadge(item.status)}
                                </div>
                              </PopoverTrigger>
                              {/*<PopoverContent className="text-sm">*/}
                              {/*  {item.reservations &&*/}
                              {/*  item.reservations.length > 0 ? (*/}
                              {/*    <ul className="list-disc">*/}
                              {/*      {item.reservations.map((res) => (*/}
                              {/*        <li key={res.guest_id}>*/}
                              {/*          {res.guest_name}: {res.quantity}*/}
                              {/*        </li>*/}
                              {/*      ))}*/}
                              {/*    </ul>*/}
                              {/*  ) : (*/}
                              {/*    <p>No reservations available.</p>*/}
                              {/*  )}*/}
                              {/*</PopoverContent>*/}
                            </Popover>
                          ) : (
                            getStatusBadge(item.status)
                          )}
                        </TableCell>

                        <TableCell className="text-right">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-8 w-8"
                              >
                                <MoreHorizontal className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem
                                onClick={() => handleEditGift(item.id)}
                              >
                                <Edit className="h-4 w-4 mr-2" /> Edit
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                className="text-red-600"
                                onClick={() => handleDeleteGift(item.id)}
                              >
                                <Trash className="h-4 w-4 mr-2" /> Delete
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>

                      {/* Separate row for description */}
                      {/*{item.description && (*/}
                      <TableRow>
                        <TableCell
                          colSpan={7}
                          className="py-1 px-4 bg-gray-50 dark:bg-gray-800/50 text-sm text-gray-500 dark:text-gray-400 h-8"
                        >
                          {item.description}
                        </TableCell>
                      </TableRow>
                      {/*)}*/}
                    </React.Fragment>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>

        {/* Categories Section */}
        <div className="mt-8">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-xl font-bold">CATEGORIES</h3>
            <Button
              variant="outline"
              className="text-blue-600 border-blue-600"
              onClick={handleAddCategory}
            >
              <Plus className="mr-2 h-4 w-4" /> Add Category
            </Button>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {categories && categories.length > 0 ? (
              categories.map((category) => {
                const categoryItems =
                  items?.filter((item) => item.category_id === category.id) ||
                  [];

                return (
                  <Card
                    key={category.id}
                    className="border border-gray-200 dark:border-gray-700"
                  >
                    <CardHeader className="pb-2">
                      <div className="flex justify-between items-start">
                        <CardTitle className="text-base font-medium">
                          {category.name}
                        </CardTitle>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-7 w-7"
                            >
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => handleEditCategory(category.id)}
                            >
                              <Edit className="h-4 w-4 mr-2" /> Edit
                            </DropdownMenuItem>
                            <DropdownMenuItem className="text-red-600">
                              <Trash className="h-4 w-4 mr-2" /> Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="text-sm text-gray-500">
                        {categoryItems.length} item
                        {categoryItems.length !== 1 && "s"}
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="mt-2 text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-0"
                        onClick={() => handleEditCategory(category.id)}
                      >
                        Manage
                      </Button>
                    </CardContent>
                  </Card>
                );
              })
            ) : (
              <Card className="border border-dashed border-gray-300 dark:border-gray-700 col-span-full">
                <CardContent className="flex flex-col items-center justify-center py-6">
                  <p className="text-center text-gray-500 mb-4">
                    No categories found. Create your first category!
                  </p>
                  <Button
                    variant="outline"
                    onClick={handleAddCategory}
                    className="border-blue-600 text-blue-600"
                  >
                    <Plus className="mr-2 h-4 w-4" /> Add Category
                  </Button>
                </CardContent>
              </Card>
            )}
          </div>
        </div>

        {/* Summary Section */}
        <div className="mt-8 bg-gray-50 dark:bg-gray-800 rounded-lg p-6">
          <h3 className="text-xl font-bold mb-4">SUMMARY</h3>
          <ul className="space-y-2">
            <li className="text-gray-700 dark:text-gray-300">
              • {summaryStats.totalItems} total gift item
              {summaryStats.totalItems !== 1 ? "s" : ""} across{" "}
              {summaryStats.totalCategories} categor
              {summaryStats.totalCategories !== 1 ? "ies" : "y"}
            </li>
            <li className="text-gray-700 dark:text-gray-300">
              • {summaryStats.availableItems} gift
              {summaryStats.availableItems !== 1 ? "s are" : " is"} available (
              {summaryStats.availableQuantity} item
              {summaryStats.availableQuantity !== 1 ? "s" : ""})
            </li>
            <li className="text-gray-700 dark:text-gray-300">
              • {summaryStats.reservedItems} gift
              {summaryStats.reservedItems !== 1 ? "s are" : " is"} reserved (
              {summaryStats.reservedQuantity} item
              {summaryStats.reservedQuantity !== 1 ? "s" : ""})
            </li>
            <li className="text-gray-700 dark:text-gray-300">
              • {summaryStats.purchasedItems} gift
              {summaryStats.purchasedItems !== 1 ? "s have" : " has"} been
              purchased ({summaryStats.purchasedQuantity} item
              {summaryStats.purchasedQuantity !== 1 ? "s" : ""})
            </li>
            <li className="text-gray-700 dark:text-gray-300">
              • {summaryStats.receivedItems} gift
              {summaryStats.receivedItems !== 1 ? "s have" : " has"} been fully
              received ({summaryStats.receivedQuantity} item
              {summaryStats.receivedQuantity !== 1 ? "s" : ""})
            </li>
          </ul>
        </div>
      </div>

      {/* Category Modals */}
      {isAddCategoryModalOpen && (
        <CategoryModal
          isOpen={isAddCategoryModalOpen}
          onClose={() => setIsAddCategoryModalOpen(false)}
          eventId={event.id}
        />
      )}

      {/* Category Modals */}
      {isAddCategoryModalOpen && (
        <CategoryModal
          isOpen={isAddCategoryModalOpen}
          onClose={() => setIsAddCategoryModalOpen(false)}
          eventId={event.id}
        />
      )}

      {isEditCategoryModalOpen && selectedCategoryId && (
        <CategoryModal
          isOpen={isEditCategoryModalOpen}
          onClose={() => {
            setIsEditCategoryModalOpen(false);
            setSelectedCategoryId(null);
          }}
          categoryId={selectedCategoryId}
          eventId={event.id}
        />
      )}

      {/* Gift Modals */}
      {isAddGiftModalOpen && (
        <GiftModal
          isOpen={isAddGiftModalOpen}
          onClose={() => setIsAddGiftModalOpen(false)}
          eventId={event.id}
        />
      )}

      {isEditGiftModalOpen && selectedGiftId && (
        <GiftModal
          isOpen={isEditGiftModalOpen}
          onClose={() => {
            setIsEditGiftModalOpen(false);
            setSelectedGiftId(null);
          }}
          giftId={selectedGiftId}
          eventId={event.id}
        />
      )}
    </div>
  );
}
