"use client";

import { useEffect, useMemo, useState } from "react";

import { CreditCard, Lock } from "lucide-react";

import { ALL_PAYMENT_PLANS } from "@/lib/event-form-utils";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { formatCurrency } from "@/lib/utils";
import type { PaymentPlanType, Sailing } from "@/types/cruise";

export interface PaymentCloudResult {
  planType: PaymentPlanType;
  templateId?: string;
  depositAmount: number;
  autoPayEnabled: boolean;
  success: boolean;
}

interface PaymentCloudCheckoutProps {
  sailing: Sailing;
  total: number;
  depositAmount: number;
  planType: PaymentPlanType;
  templateId?: string;
  autoPayEnabled: boolean;
  onPlanChange: (plan: PaymentPlanType, templateId?: string) => void;
  onAutoPayChange: (enabled: boolean) => void;
  onPaymentComplete: (result: PaymentCloudResult) => void;
  /** Pay a single installment (guest portal) instead of full booking checkout */
  mode?: "booking" | "installment";
  installmentRemaining?: number;
  payAmount?: number;
  onPayAmountChange?: (amount: number) => void;
}

export function PaymentCloudCheckout({
  sailing,
  total,
  depositAmount,
  planType,
  templateId,
  autoPayEnabled,
  onPlanChange,
  onAutoPayChange,
  onPaymentComplete,
  mode = "booking",
  installmentRemaining = 0,
  payAmount,
  onPayAmountChange,
}: PaymentCloudCheckoutProps) {
  const [cardNumber, setCardNumber] = useState("");
  const [expiry, setExpiry] = useState("");
  const [cvc, setCvc] = useState("");
  const [nameOnCard, setNameOnCard] = useState("");
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState("");

  const allowedPlans = sailing.allowedPaymentPlans ?? ALL_PAYMENT_PLANS;
  const allowPartial = sailing.allowPartialPayments !== false;
  const minPartial = sailing.minPartialPayment ?? 50;

  const allowedCustomTemplates = useMemo(
    () => (allowedPlans.includes("custom") ? sailing.paymentScheduleTemplates : []),
    [allowedPlans, sailing.paymentScheduleTemplates],
  );

  useEffect(() => {
    if (mode !== "booking") return;
    if (allowedPlans.includes(planType)) {
      if (planType === "custom" && templateId && !allowedCustomTemplates.some((t) => t.id === templateId)) {
        onPlanChange("custom", allowedCustomTemplates[0]?.id);
      }
      return;
    }
    const fallback = allowedPlans[0] ?? "full";
    onPlanChange(fallback, fallback === "custom" ? allowedCustomTemplates[0]?.id : undefined);
  }, [allowedPlans, allowedCustomTemplates, mode, onPlanChange, planType, templateId]);

  const chargeNow = useMemo(() => {
    if (mode === "installment") {
      const remaining = installmentRemaining;
      const amount = payAmount ?? remaining;
      return Math.min(Math.max(amount, 0), remaining);
    }
    if (planType === "full") return total;
    if (planType === "custom" && templateId) {
      const template = sailing.paymentScheduleTemplates.find((t) => t.id === templateId);
      const firstPct = template?.installments[0]?.percent ?? 30;
      return Math.round(total * (firstPct / 100) * 100) / 100;
    }
    return depositAmount;
  }, [mode, installmentRemaining, payAmount, planType, templateId, sailing.paymentScheduleTemplates, total, depositAmount]);

  const handleSubmit = () => {
    setError("");
    if (!cardNumber || !expiry || !cvc || !nameOnCard) {
      setError("Please complete all card fields.");
      return;
    }
    if (mode === "installment" && chargeNow <= 0) {
      setError("Enter a valid payment amount.");
      return;
    }
    if (mode === "installment" && allowPartial && chargeNow < minPartial && chargeNow < installmentRemaining) {
      setError(`Minimum partial payment is ${formatCurrency(minPartial)}.`);
      return;
    }
    setProcessing(true);
    setTimeout(() => {
      setProcessing(false);
      onPaymentComplete({
        planType: mode === "installment" ? "full" : planType,
        templateId,
        depositAmount: chargeNow,
        autoPayEnabled,
        success: true,
      });
    }, 1200);
  };

  return (
    <div className="space-y-4">
      <Card className="border-primary/20 bg-primary/5">
        <CardHeader className="pb-2">
          <div className="flex items-center gap-2">
            <CreditCard className="size-5 text-primary" />
            <CardTitle className="text-base">Payment Cloud</CardTitle>
          </div>
          <CardDescription>Secure mock checkout — no real charges are processed.</CardDescription>
        </CardHeader>
      </Card>

      {mode === "booking" && (
        <div className="space-y-3">
          <Label>Payment plan</Label>
          <RadioGroup
            value={planType === "custom" && templateId ? `custom-${templateId}` : planType}
            onValueChange={(v) => {
              if (v.startsWith("custom-")) {
                onPlanChange("custom", v.replace("custom-", ""));
              } else {
                onPlanChange(v as PaymentPlanType);
              }
            }}
            className="grid gap-2"
          >
            {allowedPlans.includes("full") && (
              <label className="flex cursor-pointer items-center gap-3 rounded-lg border p-3 hover:bg-muted/40">
                <RadioGroupItem value="full" />
                <div className="flex-1">
                  <p className="font-medium text-sm">Pay in full</p>
                  <p className="text-muted-foreground text-xs">{formatCurrency(total)} today</p>
                </div>
              </label>
            )}
            {allowedPlans.includes("recurring_3") && (
              <label className="flex cursor-pointer items-center gap-3 rounded-lg border p-3 hover:bg-muted/40">
                <RadioGroupItem value="recurring_3" />
                <div className="flex-1">
                  <p className="font-medium text-sm">3 monthly installments</p>
                  <p className="text-muted-foreground text-xs">
                    {formatCurrency(depositAmount)} deposit + 3 payments
                  </p>
                </div>
              </label>
            )}
            {allowedPlans.includes("recurring_6") && (
              <label className="flex cursor-pointer items-center gap-3 rounded-lg border p-3 hover:bg-muted/40">
                <RadioGroupItem value="recurring_6" />
                <div className="flex-1">
                  <p className="font-medium text-sm">6 monthly installments</p>
                  <p className="text-muted-foreground text-xs">
                    {formatCurrency(depositAmount)} deposit + 6 payments
                  </p>
                </div>
              </label>
            )}
            {allowedCustomTemplates.map((template) => (
              <label
                key={template.id}
                className="flex cursor-pointer items-center gap-3 rounded-lg border p-3 hover:bg-muted/40"
              >
                <RadioGroupItem value={`custom-${template.id}`} />
                <div className="flex-1">
                  <p className="font-medium text-sm">{template.name}</p>
                  <p className="text-muted-foreground text-xs">
                    {template.installments.map((i) => `${i.percent}%`).join(" · ")}
                  </p>
                </div>
              </label>
            ))}
          </RadioGroup>
        </div>
      )}

      {mode === "booking" &&
        (planType === "recurring_3" || planType === "recurring_6" || planType === "custom") && (
          <div className="flex items-center justify-between rounded-lg border p-3">
            <div>
              <p className="font-medium text-sm">Enable auto-pay</p>
              <p className="text-muted-foreground text-xs">Automatically charge scheduled installments</p>
            </div>
            <Switch checked={autoPayEnabled} onCheckedChange={onAutoPayChange} />
          </div>
        )}

      {mode === "installment" && allowPartial && installmentRemaining > minPartial && (
        <div className="space-y-1.5">
          <Label htmlFor="partial-amount">Payment amount</Label>
          <Input
            id="partial-amount"
            type="number"
            min={minPartial}
            max={installmentRemaining}
            step="0.01"
            value={payAmount ?? installmentRemaining}
            onChange={(e) => onPayAmountChange?.(Number.parseFloat(e.target.value) || 0)}
          />
          <p className="text-muted-foreground text-xs">
            Remaining on this installment: {formatCurrency(installmentRemaining)} · min partial{" "}
            {formatCurrency(minPartial)}
          </p>
        </div>
      )}

      <div className="rounded-lg border bg-muted/30 p-3 text-sm">
        <p className="font-medium">Amount due today: {formatCurrency(chargeNow)}</p>
        {mode === "booking" && planType !== "full" && (
          <p className="text-muted-foreground text-xs">Total booking: {formatCurrency(total)}</p>
        )}
        {mode === "installment" && (
          <p className="text-muted-foreground text-xs">
            Installment balance: {formatCurrency(installmentRemaining)}
          </p>
        )}
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        <div className="space-y-1.5 sm:col-span-2">
          <Label htmlFor="pc-name">Name on card</Label>
          <Input id="pc-name" placeholder="Jane Doe" value={nameOnCard} onChange={(e) => setNameOnCard(e.target.value)} />
        </div>
        <div className="space-y-1.5 sm:col-span-2">
          <Label htmlFor="pc-number">Card number</Label>
          <Input
            id="pc-number"
            placeholder="4242 4242 4242 4242"
            value={cardNumber}
            onChange={(e) => setCardNumber(e.target.value)}
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="pc-expiry">Expiry</Label>
          <Input id="pc-expiry" placeholder="MM/YY" value={expiry} onChange={(e) => setExpiry(e.target.value)} />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="pc-cvc">CVC</Label>
          <Input id="pc-cvc" placeholder="123" value={cvc} onChange={(e) => setCvc(e.target.value)} />
        </div>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      <Button type="button" className="w-full" onClick={handleSubmit} disabled={processing}>
        <Lock className="mr-2 size-4" />
        {processing ? "Processing…" : `Pay ${formatCurrency(chargeNow)}`}
      </Button>
    </div>
  );
}
