"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import {
  ArrowLeft,
  BadgeCheck,
  Building2,
  CreditCard,
  IndianRupee,
  Loader2,
  Plus,
  Smartphone,
  Wallet,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { FIXED_BOOKING_REFUND_DETAILS } from "@/lib/strings/fixed-booking-refund-details";
import { cn } from "@/lib/utils";
import {
  createMyPaymentMethodAction,
  getMyPaymentMethodsAction,
} from "@/features/payment/actions/payment-methods-actions";
import { cancelFixPackageBookingAction } from "@/features/fixed-packages/actions/booking-actions";
import type { PaymentMethodItem } from "@/core/api/services/payment-methods";

const inflightPaymentMethodsRequest = new Map<
  string,
  ReturnType<typeof getMyPaymentMethodsAction>
>();

function dedupedGetMyPaymentMethodsAction() {
  const key = "my-payment-methods";
  const existing = inflightPaymentMethodsRequest.get(key);
  if (existing) return existing;

  const pending = getMyPaymentMethodsAction().finally(() => {
    inflightPaymentMethodsRequest.delete(key);
  });

  inflightPaymentMethodsRequest.set(key, pending);
  return pending;
}

type AddMethodForm = {
  type: "bank" | "upi";
  accountHolder: string;
  bankName: string;
  accountNumber: string;
  ifscCode: string;
  upiId: string;
};

const INITIAL_METHOD_FORM: AddMethodForm = {
  type: "bank",
  accountHolder: "",
  bankName: "",
  accountNumber: "",
  ifscCode: "",
  upiId: "",
};

function getMethodTitle(method: PaymentMethodItem): string {
  switch (method.method_type) {
    case "UPI":
      return FIXED_BOOKING_REFUND_DETAILS.DUMMY_UPI_TITLE;
    case "NET_BANKING":
      return (
        method.details.bank_name ||
        method.provider_name ||
        FIXED_BOOKING_REFUND_DETAILS.NEW_BANK_ACCOUNT
      );
    case "CARD":
      return method.provider_name || "Card";
    case "WALLET":
      return method.provider_name || "Wallet";
  }
}

function getMethodSubtitle(method: PaymentMethodItem): string {
  switch (method.method_type) {
    case "UPI":
      return (
        method.details.account_name ||
        method.provider_name ||
        FIXED_BOOKING_REFUND_DETAILS.NEW_UPI_FALLBACK
      );
    case "NET_BANKING":
      return (
        method.details.account_holder_name ||
        method.provider_name ||
        FIXED_BOOKING_REFUND_DETAILS.ACCOUNT_HOLDER_FALLBACK
      );
    case "CARD":
      return (
        method.details.card_holder_name || method.provider_name || "Card holder"
      );
    case "WALLET":
      return method.details.account_name || method.provider_name || "Wallet";
  }
}

function getMethodDetail(method: PaymentMethodItem): string {
  switch (method.method_type) {
    case "UPI":
      return method.details.upi_id || "";
    case "NET_BANKING":
      return `A/C ending ${String(method.details.account_number ?? "").slice(-4) || "****"} · IFSC ${method.details.ifsc_code || FIXED_BOOKING_REFUND_DETAILS.PENDING_IFSC}`;
    case "CARD":
      return `Card ending ${String(method.details.card_number ?? "").slice(-4) || "****"}`;
    case "WALLET":
      return `Mobile ending ${String(method.details.mobile_number ?? "").slice(-4) || "****"}`;
  }
}

function getMethodIcon(method: PaymentMethodItem) {
  switch (method.method_type) {
    case "UPI":
      return Wallet;
    case "NET_BANKING":
      return Building2;
    case "CARD":
      return CreditCard;
    case "WALLET":
      return Smartphone;
  }
}

function getMethodIconClass(method: PaymentMethodItem): string {
  switch (method.method_type) {
    case "UPI":
      return "bg-orange-50 text-orange-600";
    case "NET_BANKING":
      return "bg-blue-50 text-blue-600";
    case "CARD":
      return "bg-violet-50 text-violet-600";
    case "WALLET":
      return "bg-emerald-50 text-emerald-600";
  }
}

type FixedBookingRefundDetailsProps = {
  bookingId: string;
};

export default function FixedBookingRefundDetails({
  bookingId,
}: FixedBookingRefundDetailsProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const toast = useToastEnhanced();
  const bookingNumber = searchParams.get("bookingNumber") ?? bookingId;
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethodItem[]>([]);
  const [isLoadingMethods, setIsLoadingMethods] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedMethodId, setSelectedMethodId] = useState<string | number>("");
  const [isAddMethodOpen, setIsAddMethodOpen] = useState(false);
  const [methodForm, setMethodForm] =
    useState<AddMethodForm>(INITIAL_METHOD_FORM);

  useEffect(() => {
    let cancelled = false;
    setIsLoadingMethods(true);

    (async () => {
      const result = await dedupedGetMyPaymentMethodsAction();
      if (cancelled) return;
      setIsLoadingMethods(false);
      if (result.success) {
        setPaymentMethods(result.data ?? []);
      } else {
        toast.error({
          title: FIXED_BOOKING_REFUND_DETAILS.LOAD_FAILED_TITLE,
          description: result.error,
        });
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [toast]);

  const refundAmount = useMemo(() => {
    const numericId = Number.parseInt(bookingId, 10);
    if (Number.isNaN(numericId)) return 18500;
    return 15000 + (numericId % 5) * 1750;
  }, [bookingId]);

  const selectedMethod = paymentMethods.find(
    (method) => String(method.id) === String(selectedMethodId)
  );

  const updateMethodForm = <K extends keyof AddMethodForm>(
    key: K,
    value: AddMethodForm[K]
  ) => {
    setMethodForm((prev) => ({ ...prev, [key]: value }));
  };

  const resetMethodForm = () => {
    setMethodForm(INITIAL_METHOD_FORM);
  };

  const handleAddMethod = async () => {
    try {
      setIsSubmitting(true);

      const payload =
        methodForm.type === "bank"
          ? {
            provider_name:
              methodForm.bankName ||
              FIXED_BOOKING_REFUND_DETAILS.NEW_BANK_ACCOUNT,
            method_type: "NET_BANKING" as const,
            details: {
              bank_name: methodForm.bankName,
              account_number: methodForm.accountNumber,
              ifsc_code: methodForm.ifscCode,
              account_holder_name: methodForm.accountHolder,
            },
            status: "inactive" as const,
          }
          : {
            provider_name:
              methodForm.upiId ||
              FIXED_BOOKING_REFUND_DETAILS.NEW_UPI_FALLBACK,
            method_type: "UPI" as const,
            details: {
              upi_id: methodForm.upiId,
            },
            status: "inactive" as const,
          };

      const result = await createMyPaymentMethodAction(payload);

      if (!result.success) {
        toast.error({
          title: FIXED_BOOKING_REFUND_DETAILS.TOAST_METHOD_ADDED_TITLE,
          description: result.error,
        });
        return;
      }

      if (result.data) {
        setPaymentMethods((prev) => [result.data!, ...prev]);
        setSelectedMethodId(String(result.data.id));
      } else {
        const refreshed = await getMyPaymentMethodsAction();
        if (refreshed.success) {
          setPaymentMethods(refreshed.data ?? []);
        }
      }

      setIsAddMethodOpen(false);
      resetMethodForm();
      toast.success({
        title: FIXED_BOOKING_REFUND_DETAILS.TOAST_METHOD_ADDED_TITLE,
        description:
          FIXED_BOOKING_REFUND_DETAILS.TOAST_METHOD_ADDED_DESCRIPTION,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleProcessRefund = async () => {
    if (!selectedMethod) return;

    try {
      setIsSubmitting(true);
      const result = await cancelFixPackageBookingAction(
        bookingId,
        "User requested cancellation",
        selectedMethod.id
      );

      if (!result.success) {
        toast.error({
          title: "Refund request failed",
          description: result.error || "Please try again.",
        });
        return;
      }

      toast.success({
        title: FIXED_BOOKING_REFUND_DETAILS.TOAST_REFUND_INITIATED_TITLE,
        description: `${FIXED_BOOKING_REFUND_DETAILS.TOAST_REFUND_INITIATED_PREFIX}${bookingNumber}${FIXED_BOOKING_REFUND_DETAILS.TOAST_REFUND_INITIATED_MIDDLE}${getMethodSubtitle(selectedMethod)}.`,
      });
      router.push("/user/fixed-bookings");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div className="space-y-2">
          <Button
            variant="ghost"
            className="w-fit px-0 text-muted-foreground hover:text-foreground"
            onClick={() => router.back()}
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            {FIXED_BOOKING_REFUND_DETAILS.BACK}
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900 md:text-3xl">
              {FIXED_BOOKING_REFUND_DETAILS.PAGE_TITLE}
            </h1>
            <p className="text-sm text-muted-foreground md:text-base">
              {FIXED_BOOKING_REFUND_DETAILS.PAGE_SUBTITLE_PREFIX}
              {bookingNumber}.
            </p>
          </div>
        </div>

        <Button asChild variant="outline" className="bg-transparent">
          <Link href="/user/fixed-bookings">
            {FIXED_BOOKING_REFUND_DETAILS.VIEW_ALL_BOOKINGS}
          </Link>
        </Button>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.15fr_0.85fr]">
        <div className="space-y-6">
          <Card className="border-border/60 shadow-sm">
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <CreditCard className="h-5 w-5 text-emerald-600" />
                {FIXED_BOOKING_REFUND_DETAILS.PAYMENT_METHODS_TITLE}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <Button
                  onClick={() => setIsAddMethodOpen(true)}
                  className="w-full sm:w-auto"
                >
                  <Plus className="mr-2 h-4 w-4" />
                  {FIXED_BOOKING_REFUND_DETAILS.ADD_NEW_PAYMENT_METHOD}
                </Button>
              </div>

              {isLoadingMethods ? (
                <div className="flex items-center justify-center py-10">
                  <Loader2 className="h-6 w-6 animate-spin text-emerald-600" />
                </div>
              ) : paymentMethods.length === 0 ? (
                <div className="rounded-2xl border border-dashed p-8 text-center">
                  <p className="font-medium text-foreground">
                    {FIXED_BOOKING_REFUND_DETAILS.EMPTY_TITLE}
                  </p>
                  <p className="mt-1 text-sm text-muted-foreground">
                    {FIXED_BOOKING_REFUND_DETAILS.EMPTY_DESCRIPTION}
                  </p>
                </div>
              ) : (
                <RadioGroup
                  value={String(selectedMethodId)}
                  onValueChange={(val) => setSelectedMethodId(val)}
                  className="space-y-3"
                >
                  {paymentMethods.map((method) => {
                    const Icon = getMethodIcon(method);
                    const methodIdStr = String(method.id);
                    return (
                      <label
                        key={method.id}
                        htmlFor={methodIdStr}
                        className={cn(
                          "flex cursor-pointer items-start gap-4 rounded-2xl border p-4 transition-all",
                          String(selectedMethodId) === methodIdStr
                            ? "border-emerald-500 bg-emerald-50/70 shadow-sm"
                            : "border-border/70 hover:border-emerald-300 hover:bg-muted/40"
                        )}
                      >
                        <RadioGroupItem
                          value={methodIdStr}
                          id={methodIdStr}
                          className="mt-1"
                        />
                        <div
                          className={cn(
                            "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl",
                            getMethodIconClass(method)
                          )}
                        >
                          <Icon className="h-5 w-5" />
                        </div>
                        <div className="min-w-0 flex-1 space-y-1">
                          <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                            <div>
                              <p className="font-semibold text-foreground">
                                {getMethodTitle(method)}
                              </p>
                              <p className="text-sm text-muted-foreground">
                                {getMethodSubtitle(method)}
                              </p>
                            </div>
                            <Badge
                              variant="secondary"
                              className="w-fit bg-slate-100 text-slate-700"
                            >
                              {method.method_type}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {getMethodDetail(method)}
                          </p>
                        </div>
                      </label>
                    );
                  })}
                </RadioGroup>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="space-y-6">
          <Card className="border-border/60 shadow-sm">
            <CardHeader className="pb-3">
              <CardTitle className="text-lg">
                {FIXED_BOOKING_REFUND_DETAILS.REFUND_SUMMARY_TITLE}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-2xl border border-emerald-100 bg-emerald-50/80 p-4">
                <p className="text-sm text-emerald-700">
                  {FIXED_BOOKING_REFUND_DETAILS.ESTIMATED_REFUND_AMOUNT}
                </p>
                <div className="mt-2 flex items-center gap-2 text-2xl font-bold text-emerald-900">
                  <IndianRupee className="h-6 w-6" />
                  {refundAmount.toLocaleString("en-IN")}
                </div>
              </div>

              <div className="space-y-3 rounded-2xl border p-4">
                <div>
                  <p className="text-sm text-muted-foreground">
                    {FIXED_BOOKING_REFUND_DETAILS.BOOKING_REFERENCE}
                  </p>
                  <p className="font-semibold text-foreground">
                    #{bookingNumber}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">
                    {FIXED_BOOKING_REFUND_DETAILS.REFUND_DESTINATION}
                  </p>
                  <p className="font-semibold text-foreground">
                    {selectedMethod
                      ? getMethodSubtitle(selectedMethod)
                      : FIXED_BOOKING_REFUND_DETAILS.SELECT_PAYMENT_METHOD_FALLBACK}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">
                    {FIXED_BOOKING_REFUND_DETAILS.REFUND_STATUS}
                  </p>
                  <div className="mt-1 flex items-center gap-2 text-sm text-muted-foreground">
                    <BadgeCheck className="h-4 w-4 text-emerald-600" />
                    {FIXED_BOOKING_REFUND_DETAILS.WAITING_FOR_SELECTION}
                  </div>
                </div>
              </div>

              <Button
                className="w-full"
                disabled={!selectedMethodId || isSubmitting}
                onClick={handleProcessRefund}
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Processing
                  </>
                ) : (
                  FIXED_BOOKING_REFUND_DETAILS.PROCESS_REFUND
                )}
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>

      <Dialog
        open={isAddMethodOpen}
        onOpenChange={(open) => {
          setIsAddMethodOpen(open);
          if (!open) resetMethodForm();
        }}
      >
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {FIXED_BOOKING_REFUND_DETAILS.DIALOG_TITLE}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-5 py-2">
            <div className="space-y-2">
              <Label>{FIXED_BOOKING_REFUND_DETAILS.PAYMENT_METHOD_TYPE}</Label>
              <div className="grid grid-cols-2 gap-3">
                <Button
                  type="button"
                  variant={methodForm.type === "bank" ? "default" : "outline"}
                  className="justify-start"
                  onClick={() => updateMethodForm("type", "bank")}
                >
                  <Building2 className="mr-2 h-4 w-4" />
                  {FIXED_BOOKING_REFUND_DETAILS.BANK_ACCOUNT}
                </Button>
                <Button
                  type="button"
                  variant={methodForm.type === "upi" ? "default" : "outline"}
                  className="justify-start"
                  onClick={() => updateMethodForm("type", "upi")}
                >
                  <Wallet className="mr-2 h-4 w-4" />
                  {FIXED_BOOKING_REFUND_DETAILS.UPI_ID}
                </Button>
              </div>
            </div>

            {methodForm.type === "bank" ? (
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2 sm:col-span-2">
                  <Label htmlFor="accountHolder">
                    {FIXED_BOOKING_REFUND_DETAILS.ACCOUNT_HOLDER_NAME}
                  </Label>
                  <Input
                    id="accountHolder"
                    placeholder={
                      FIXED_BOOKING_REFUND_DETAILS.ACCOUNT_HOLDER_PLACEHOLDER
                    }
                    value={methodForm.accountHolder}
                    onChange={(event) =>
                      updateMethodForm("accountHolder", event.target.value)
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="bankName">
                    {FIXED_BOOKING_REFUND_DETAILS.BANK_NAME}
                  </Label>
                  <Input
                    id="bankName"
                    placeholder={
                      FIXED_BOOKING_REFUND_DETAILS.BANK_NAME_PLACEHOLDER
                    }
                    value={methodForm.bankName}
                    onChange={(event) =>
                      updateMethodForm("bankName", event.target.value)
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ifscCode">
                    {FIXED_BOOKING_REFUND_DETAILS.IFSC_CODE}
                  </Label>
                  <Input
                    id="ifscCode"
                    placeholder={
                      FIXED_BOOKING_REFUND_DETAILS.IFSC_CODE_PLACEHOLDER
                    }
                    value={methodForm.ifscCode}
                    onChange={(event) =>
                      updateMethodForm("ifscCode", event.target.value)
                    }
                  />
                </div>
                <div className="space-y-2 sm:col-span-2">
                  <Label htmlFor="accountNumber">
                    {FIXED_BOOKING_REFUND_DETAILS.ACCOUNT_NUMBER}
                  </Label>
                  <Input
                    id="accountNumber"
                    placeholder={
                      FIXED_BOOKING_REFUND_DETAILS.ACCOUNT_NUMBER_PLACEHOLDER
                    }
                    value={methodForm.accountNumber}
                    onChange={(event) =>
                      updateMethodForm("accountNumber", event.target.value)
                    }
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-2">
                <Label htmlFor="upiId">
                  {FIXED_BOOKING_REFUND_DETAILS.UPI_ID}
                </Label>
                <Input
                  id="upiId"
                  placeholder={FIXED_BOOKING_REFUND_DETAILS.UPI_ID_PLACEHOLDER}
                  value={methodForm.upiId}
                  onChange={(event) =>
                    updateMethodForm("upiId", event.target.value)
                  }
                />
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsAddMethodOpen(false);
                resetMethodForm();
              }}
              disabled={isSubmitting}
            >
              {FIXED_BOOKING_REFUND_DETAILS.CANCEL}
            </Button>
            <Button onClick={handleAddMethod} disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {FIXED_BOOKING_REFUND_DETAILS.ADDING}
                </>
              ) : (
                FIXED_BOOKING_REFUND_DETAILS.ADD_PAYMENT_METHOD
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
