"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { FIX_PACKAGES_ADMIN } from "@/lib/strings";
import type { FixPackage } from "@/features/packages/services/fix-packages.service";
import type { ApiFixPackageItinerary } from "@/core/api/services/fix-packages/fix-packages.types";
import { getFixPackageAction } from "@/features/packages/actions/fix-packages-actions";
import { mapApiFixPackageToFixPackage } from "@/features/packages/types/fix-package-api.types";
import { htmlToList } from "@/components/shared/package-detail/package-detail-utils";
import { Calendar, MapPin, IndianRupee, Info, Check, X } from "lucide-react";
import { useEffect, useState } from "react";
import { LoadingSpinner } from "@/components/shared/skeletons";

interface ViewPackageDetailsDialogProps {
  package: FixPackage | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ViewPackageDetailsDialog({
  package: pkg,
  open,
  onOpenChange,
}: ViewPackageDetailsDialogProps) {
  const [fullPackage, setFullPackage] = useState<FixPackage | null>(null);
  const [rawItineraries, setRawItineraries] = useState<
    ApiFixPackageItinerary[] | null
  >(null);
  const [loadingDetails, setLoadingDetails] = useState(false);

  // Fetch full package detail when dialog opens so we have itinerary, inclusions, exclusions
  useEffect(() => {
    if (!open || !pkg?.id) {
      setFullPackage(null);
      setRawItineraries(null);
      return;
    }
    let cancelled = false;
    setLoadingDetails(true);
    setFullPackage(null);
    setRawItineraries(null);
    getFixPackageAction(pkg.id)
      .then((result) => {
        if (cancelled) return;
        if (result.success && result.data) {
          const data = result.data as {
            itineraries?: ApiFixPackageItinerary[];
            [key: string]: unknown;
          };
          setFullPackage(mapApiFixPackageToFixPackage(result.data as any));
          setRawItineraries(
            data?.itineraries && data.itineraries.length > 0
              ? data.itineraries
              : null
          );
        } else {
          setFullPackage(pkg);
        }
      })
      .catch(() => {
        if (!cancelled) setFullPackage(pkg);
      })
      .finally(() => {
        if (!cancelled) setLoadingDetails(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open, pkg?.id]);

  if (!pkg) return null;

  // Prefer full detail when loaded; fallback to list item (pkg is non-null here)
  const display: FixPackage = fullPackage ?? pkg;

  const formatCurrency = (amount: number): string => {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const discountPercentage =
    pkg.originalPrice > pkg.discountedPrice
      ? Math.round(
          ((pkg.originalPrice - pkg.discountedPrice) / pkg.originalPrice) * 100
        )
      : 0;

  const inclusionList = htmlToList(display.inclusion?.trim() ?? "");
  const exclusionList = htmlToList(display.exclusion?.trim() ?? "");
  const hasItineraryList = rawItineraries && rawItineraries.length > 0;
  const hasItineraryHtml = !!display.itineraryDetails?.trim();
  const hasOtherDetails = !!display.otherDetails?.trim();

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-5xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-start justify-between gap-4">
            <div>
              <DialogTitle className="text-2xl">{pkg.name}</DialogTitle>
              <div className="flex items-center gap-2 mt-2">
                <Badge
                  variant={pkg.status === "active" ? "default" : "secondary"}
                >
                  {pkg.status === "active"
                    ? FIX_PACKAGES_ADMIN.ACTIVE
                    : FIX_PACKAGES_ADMIN.INACTIVE}
                </Badge>
                {discountPercentage > 0 && (
                  <Badge
                    variant="outline"
                    className="bg-green-50 text-green-700 border-green-200"
                  >
                    {discountPercentage}
                    {FIX_PACKAGES_ADMIN.PERCENT_OFF_VIEW}
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </DialogHeader>

        <div className="space-y-6 mt-4">
          {/* Pricing Section */}
          <div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
            <IndianRupee
              className="h-8 w-8 text-primary flex-shrink-0"
              aria-hidden="true"
            />
            <div className="flex-1">
              <p className="text-sm text-muted-foreground">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_PRICE}
              </p>
              <div className="flex items-baseline gap-3 mt-1">
                <span className="text-2xl font-bold text-green-600">
                  {formatCurrency(pkg.discountedPrice)}
                </span>
                {pkg.originalPrice > pkg.discountedPrice && (
                  <span className="text-lg text-muted-foreground line-through">
                    {formatCurrency(pkg.originalPrice)}
                  </span>
                )}
              </div>
            </div>
            <div className="text-right">
              <p className="text-sm text-muted-foreground">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_DURATION}
              </p>
              <p className="text-2xl font-bold">{pkg.totalDays}</p>
              <p className="text-sm text-muted-foreground">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_DAYS}
              </p>
            </div>
          </div>

          <Separator />

          {/* Location Details */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <MapPin className="h-5 w-5 text-primary" aria-hidden="true" />
              <h3 className="font-semibold text-lg">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_LOCATION_DETAILS}
              </h3>
            </div>
            <p className="text-muted-foreground leading-relaxed pl-7">
              {display.locationDetails || "—"}
            </p>
          </div>

          <Separator />

          {/* Itinerary Details */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Calendar className="h-5 w-5 text-primary" aria-hidden="true" />
              <h3 className="font-semibold text-lg">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_ITINERARY_DETAILS}
              </h3>
            </div>
            {loadingDetails ? (
              <div className="pl-7 flex items-center gap-2 text-muted-foreground">
                <LoadingSpinner size="sm" aria-hidden="true" />
                <span>{FIX_PACKAGES_ADMIN.VIEW_PACKAGE_LOADING_DETAILS}</span>
              </div>
            ) : hasItineraryList ? (
              <ul className="list-disc list-inside text-muted-foreground leading-relaxed pl-7 space-y-1">
                {(rawItineraries ?? []).map((it, idx) => (
                  <li key={idx}>
                    Day {it.day} : {it.title}
                  </li>
                ))}
              </ul>
            ) : hasItineraryHtml ? (
              <div
                className="prose prose-sm max-w-none text-muted-foreground leading-relaxed pl-7"
                dangerouslySetInnerHTML={{
                  __html: display.itineraryDetails || "",
                }}
              />
            ) : (
              <p className="text-muted-foreground pl-7">—</p>
            )}
          </div>

          <Separator />

          {/* Inclusions */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Check className="h-5 w-5 text-primary" aria-hidden="true" />
              <h3 className="font-semibold text-lg">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_INCLUSIONS}
              </h3>
            </div>
            {loadingDetails ? (
              <div className="pl-7 flex items-center gap-2 text-muted-foreground">
                <LoadingSpinner size="sm" aria-hidden="true" />
                <span>{FIX_PACKAGES_ADMIN.VIEW_PACKAGE_LOADING_DETAILS}</span>
              </div>
            ) : inclusionList.length > 0 ? (
              <ul className="list-disc list-inside text-muted-foreground leading-relaxed pl-7 space-y-1">
                {inclusionList.map((item, idx) => (
                  <li key={idx}>{item}</li>
                ))}
              </ul>
            ) : display.inclusion?.trim() ? (
              <div
                className="prose prose-sm max-w-none text-muted-foreground leading-relaxed pl-7"
                dangerouslySetInnerHTML={{ __html: display.inclusion }}
              />
            ) : (
              <p className="text-muted-foreground pl-7">—</p>
            )}
          </div>

          <Separator />

          {/* Exclusions */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <X className="h-5 w-5 text-primary" aria-hidden="true" />
              <h3 className="font-semibold text-lg">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_EXCLUSIONS}
              </h3>
            </div>
            {loadingDetails ? (
              <div className="pl-7 flex items-center gap-2 text-muted-foreground">
                <LoadingSpinner size="sm" aria-hidden="true" />
                <span>{FIX_PACKAGES_ADMIN.VIEW_PACKAGE_LOADING_DETAILS}</span>
              </div>
            ) : exclusionList.length > 0 ? (
              <ul className="list-disc list-inside text-muted-foreground leading-relaxed pl-7 space-y-1">
                {exclusionList.map((item, idx) => (
                  <li key={idx}>{item}</li>
                ))}
              </ul>
            ) : display.exclusion?.trim() ? (
              <div
                className="prose prose-sm max-w-none text-muted-foreground leading-relaxed pl-7"
                dangerouslySetInnerHTML={{ __html: display.exclusion }}
              />
            ) : (
              <p className="text-muted-foreground pl-7">—</p>
            )}
          </div>

          {hasOtherDetails && (
            <>
              <Separator />
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <Info className="h-5 w-5 text-primary" aria-hidden="true" />
                  <h3 className="font-semibold text-lg">
                    {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_OTHER_DETAILS}
                  </h3>
                </div>
                <div className="text-muted-foreground leading-relaxed pl-7 whitespace-pre-line">
                  {display.otherDetails}
                </div>
              </div>
            </>
          )}

          <Separator />

          {/* Metadata */}
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <p className="text-muted-foreground">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_CREATED}
              </p>
              <p className="font-medium">
                {new Date(pkg.createdAt).toLocaleDateString("en-IN")}
              </p>
            </div>
            <div>
              <p className="text-muted-foreground">
                {FIX_PACKAGES_ADMIN.VIEW_PACKAGE_LAST_UPDATED}
              </p>
              <p className="font-medium">
                {new Date(pkg.updatedAt).toLocaleDateString("en-IN")}
              </p>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
