"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Loader2, Search } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import type { SightseeingItem } from "@/features/packages/types/package-form.types";
import {
  getSightseeingsAction,
  type Sightseeing,
} from "@/features/sightseeings/api";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { FIX_PACKAGES_ADMIN } from "@/lib/strings";
import { cn, getStorageUrl } from "@/lib/utils";

const SIGHTSEEING_SELECTION_LIMIT = 5;

export interface SightseeingModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  draft: SightseeingItem[];
  onDraftChange: (draft: SightseeingItem[]) => void;
  onSave: (sightseeings: SightseeingItem[]) => void;
}

function mapSightseeingToItem(sightseeing: Sightseeing): SightseeingItem {
  return {
    id: sightseeing.id,
    location_detail:
      sightseeing.location_detail?.trim() || `Sightseeing ${sightseeing.id}`,
    image: sightseeing.image ?? null,
    status: sightseeing.status === "inactive" ? "inactive" : "active",
  };
}

function mergeSightseeings(
  selected: SightseeingItem[],
  incoming: SightseeingItem[]
): SightseeingItem[] {
  const merged = new Map<number, SightseeingItem>();

  selected.forEach((item) => {
    merged.set(item.id, item);
  });

  incoming.forEach((item) => {
    merged.set(item.id, item);
  });

  return Array.from(merged.values());
}

function appendSightseeingPage(
  draft: SightseeingItem[],
  previous: SightseeingItem[],
  pageItems: SightseeingItem[]
): SightseeingItem[] {
  return mergeSightseeings(draft, [...previous, ...pageItems]);
}

export function SightseeingModal({
  open,
  onOpenChange,
  draft,
  onDraftChange,
  onSave,
}: SightseeingModalProps) {
  const toast = useToastEnhanced();
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [availableSightseeings, setAvailableSightseeings] = useState<
    SightseeingItem[]
  >([]);
  const [lastPage, setLastPage] = useState(1);
  const [loadedPage, setLoadedPage] = useState(0);
  const [totalSightseeings, setTotalSightseeings] = useState<number | null>(
    null
  );

  const scrollRef = useRef<HTMLDivElement>(null);
  const loadMoreSentinelRef = useRef<HTMLDivElement>(null);
  const listFetchGenRef = useRef(0);
  const loadMoreInFlightRef = useRef(false);
  const draftRef = useRef(draft);
  draftRef.current = draft;

  const listPagingRef = useRef({
    open,
    isLoading,
    isLoadingMore,
    loadedPage,
    lastPage,
    searchTerm,
  });
  listPagingRef.current = {
    open,
    isLoading,
    isLoadingMore,
    loadedPage,
    lastPage,
    searchTerm,
  };

  const loadNextPage = useCallback(async () => {
    const p = listPagingRef.current;
    const genAtStart = listFetchGenRef.current;
    if (
      !p.open ||
      p.isLoading ||
      p.isLoadingMore ||
      p.loadedPage >= p.lastPage ||
      loadMoreInFlightRef.current
    ) {
      return;
    }

    loadMoreInFlightRef.current = true;
    setIsLoadingMore(true);
    try {
      const result = await getSightseeingsAction(
        p.searchTerm.trim() || undefined,
        p.loadedPage + 1
      );
      if (genAtStart !== listFetchGenRef.current) return;

      if (result.success && result.data) {
        const fetched = result.data.data
          .map(mapSightseeingToItem)
          .filter((item) => item.status !== "inactive");
        setAvailableSightseeings((prev) =>
          appendSightseeingPage(draftRef.current, prev, fetched)
        );
        setLastPage(Math.max(1, result.data.last_page));
        setLoadedPage((prev) => prev + 1);
        setTotalSightseeings(result.data.total);
        return;
      }

      setLastPage(listPagingRef.current.loadedPage);
      toast.error({
        title: FIX_PACKAGES_ADMIN.ERROR,
        description: result.error || "Failed to load sightseeings",
      });
    } catch {
      if (genAtStart !== listFetchGenRef.current) return;
      setLastPage(listPagingRef.current.loadedPage);
      toast.error({
        title: FIX_PACKAGES_ADMIN.ERROR,
        description: "An unexpected error occurred while loading sightseeings",
      });
    } finally {
      loadMoreInFlightRef.current = false;
      if (genAtStart === listFetchGenRef.current) {
        setIsLoadingMore(false);
      }
    }
  }, [toast]);

  useEffect(() => {
    if (!open) {
      setSearchTerm("");
      setAvailableSightseeings([]);
      setLastPage(1);
      setLoadedPage(0);
      setTotalSightseeings(null);
      setIsLoading(false);
      setIsLoadingMore(false);
      loadMoreInFlightRef.current = false;
      return;
    }

    let cancelled = false;
    const timeoutId = window.setTimeout(async () => {
      const gen = ++listFetchGenRef.current;
      setIsLoading(true);
      setLoadedPage(0);
      setTotalSightseeings(null);
      try {
        const result = await getSightseeingsAction(
          searchTerm.trim() || undefined,
          1
        );
        if (cancelled || gen !== listFetchGenRef.current) return;

        if (result.success && result.data) {
          const fetched = result.data.data
            .map(mapSightseeingToItem)
            .filter((item) => item.status !== "inactive");
          setAvailableSightseeings(
            mergeSightseeings(draftRef.current, fetched)
          );
          setLastPage(Math.max(1, result.data.last_page));
          setLoadedPage(1);
          setTotalSightseeings(result.data.total);
          return;
        }

        setLastPage(1);
        setLoadedPage(1);
        setTotalSightseeings(null);
        toast.error({
          title: FIX_PACKAGES_ADMIN.ERROR,
          description: result.error || "Failed to load sightseeings",
        });
      } catch {
        if (cancelled || gen !== listFetchGenRef.current) return;
        setLastPage(1);
        setLoadedPage(1);
        setTotalSightseeings(null);
        toast.error({
          title: FIX_PACKAGES_ADMIN.ERROR,
          description:
            "An unexpected error occurred while loading sightseeings",
        });
      } finally {
        if (!cancelled && gen === listFetchGenRef.current) {
          setIsLoading(false);
        }
      }
    }, 300);

    return () => {
      cancelled = true;
      window.clearTimeout(timeoutId);
    };
  }, [open, searchTerm, toast]);

  const sightseeingCountLabel = useMemo(() => {
    if (isLoading && availableSightseeings.length === 0) {
      return null;
    }
    const visibleCount = availableSightseeings.length;
    const stillPaging =
      lastPage > 1 && loadedPage < lastPage && totalSightseeings !== null;

    if (stillPaging) {
      return FIX_PACKAGES_ADMIN.SIGHTSEEING_MODAL_TOTAL_PARTIAL.replace(
        "{loaded}",
        String(visibleCount)
      ).replace("{total}", String(totalSightseeings));
    }

    if (visibleCount === 0 && !isLoading) {
      return null;
    }

    return FIX_PACKAGES_ADMIN.SIGHTSEEING_MODAL_TOTAL.replace(
      "{count}",
      String(visibleCount)
    );
  }, [
    availableSightseeings.length,
    isLoading,
    lastPage,
    loadedPage,
    totalSightseeings,
  ]);

  const selectedIds = useMemo(
    () => new Set(draft.map((item) => item.id)),
    [draft]
  );

  useEffect(() => {
    const root = scrollRef.current;
    const sentinel = loadMoreSentinelRef.current;
    if (!open || !root || !sentinel) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const hit = entries.some((e) => e.isIntersecting);
        if (!hit) return;
        const p = listPagingRef.current;
        if (p.isLoading || p.isLoadingMore || p.loadedPage >= p.lastPage) {
          return;
        }
        void loadNextPage();
      },
      { root, rootMargin: "120px", threshold: 0 }
    );

    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [availableSightseeings.length, loadNextPage, open]);

  const handleToggle = (item: SightseeingItem, checked: boolean) => {
    if (checked) {
      if (draft.length >= SIGHTSEEING_SELECTION_LIMIT) {
        toast.error({
          title: FIX_PACKAGES_ADMIN.LIMIT_REACHED,
          description: "You can select up to 5 sightseeing locations.",
        });
        return;
      }

      onDraftChange([...draft, item]);
      return;
    }

    onDraftChange(draft.filter((selected) => selected.id !== item.id));
  };

  const handleSave = () => {
    onSave(draft);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="flex max-h-[90vh] w-[min(96vw,1200px)] max-w-6xl flex-col gap-4 overflow-hidden p-6 sm:max-w-6xl">
        <DialogHeader className="shrink-0 space-y-2 text-left">
          <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
            <DialogTitle className="text-left">
              {FIX_PACKAGES_ADMIN.SIGHTSEEING_MODAL_TITLE}
            </DialogTitle>
            {sightseeingCountLabel ? (
              <span className="shrink-0 text-sm font-normal tabular-nums text-muted-foreground sm:ml-auto">
                {sightseeingCountLabel}
              </span>
            ) : null}
          </div>
          <DialogDescription>
            {FIX_PACKAGES_ADMIN.SIGHTSEEING_MODAL_DESCRIPTION}
          </DialogDescription>
        </DialogHeader>

        <div className="flex min-h-0 flex-1 flex-col space-y-4 overflow-hidden py-2">
          <div className="flex items-center gap-3">
            <div className="relative flex-1">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder={FIX_PACKAGES_ADMIN.SIGHTSEEING_SEARCH_PLACEHOLDER}
                className="pl-9"
              />
            </div>
            <p className="text-sm text-muted-foreground">
              {FIX_PACKAGES_ADMIN.SIGHTSEEING_SELECTED_COUNT.replace(
                "{count}",
                String(draft.length)
              )}
            </p>
          </div>

          {draft.length > 0 ? (
            <div className="rounded-lg border bg-muted/20 p-3">
              <p className="mb-2 text-sm font-medium">
                {FIX_PACKAGES_ADMIN.SELECTED_SIGHTSEEINGS}
              </p>
              <div className="flex flex-wrap gap-2">
                {draft.map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => handleToggle(item, false)}
                    className="rounded-full border bg-background px-3 py-1 text-sm transition hover:border-destructive hover:text-destructive"
                  >
                    {item.location_detail}
                  </button>
                ))}
              </div>
            </div>
          ) : null}

          <div
            ref={scrollRef}
            className="max-h-[min(640px,62vh)] min-h-0 w-full flex-1 overflow-y-auto rounded-xl border bg-background"
          >
            {isLoading ? (
              <div className="flex h-56 items-center justify-center text-sm text-muted-foreground">
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                {FIX_PACKAGES_ADMIN.LOADING_SIGHTSEEINGS}
              </div>
            ) : availableSightseeings.length > 0 ? (
              <div className="p-2 sm:p-3">
                <div className="grid grid-cols-5 gap-3">
                  {availableSightseeings.map((item) => {
                    const checked = selectedIds.has(item.id);
                    const imageUrl = item.image
                      ? getStorageUrl(item.image)
                      : null;

                    return (
                      <div
                        key={item.id}
                        onClick={() => handleToggle(item, !checked)}
                        className={cn(
                          "relative flex min-w-0 cursor-pointer flex-col overflow-hidden rounded-2xl border bg-background shadow-sm transition-colors hover:bg-muted/20",
                          checked && "border-primary/50 ring-1 ring-primary/25"
                        )}
                      >
                        <div className="relative aspect-[4/5] w-full shrink-0 bg-muted">
                          {imageUrl ? (
                            <img
                              src={imageUrl}
                              alt=""
                              className="h-full w-full object-cover"
                              aria-hidden
                            />
                          ) : null}
                          <div
                            className="absolute right-1.5 top-1.5 z-10 flex items-center justify-center"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <Checkbox
                              checked={checked}
                              onCheckedChange={(value) =>
                                handleToggle(item, value === true)
                              }
                              aria-label={item.location_detail}
                            />
                          </div>
                        </div>
                        <div
                          className={cn(
                            "border-t border-border/60 bg-muted/40 px-2 py-2",
                            checked && "bg-muted/60"
                          )}
                        >
                          <p className="line-clamp-2 text-left text-xs font-medium leading-snug text-foreground">
                            {item.location_detail}
                          </p>
                        </div>
                      </div>
                    );
                  })}
                </div>
                {loadedPage < lastPage ? (
                  <div
                    ref={loadMoreSentinelRef}
                    className="flex min-h-10 items-center justify-center py-3 text-xs text-muted-foreground"
                    aria-hidden
                  >
                    {isLoadingMore ? (
                      <>
                        <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
                        {FIX_PACKAGES_ADMIN.LOADING_MORE_SIGHTSEEINGS}
                      </>
                    ) : null}
                  </div>
                ) : null}
              </div>
            ) : (
              <div className="flex h-56 items-center justify-center px-4 text-center text-sm text-muted-foreground">
                {FIX_PACKAGES_ADMIN.NO_SIGHTSEEING_RESULTS}
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="shrink-0">
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            {FIX_PACKAGES_ADMIN.DIALOG_CANCEL}
          </Button>
          <Button type="button" onClick={handleSave}>
            {FIX_PACKAGES_ADMIN.DIALOG_SAVE}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
