import { useState, useEffect } from "react";
import { loadStripe, type Stripe } from "@stripe/stripe-js";
import {
  Elements, PaymentElement, useStripe, useElements,
} from "@stripe/react-stripe-js";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import {
  CreditCard, Landmark, ArrowRight, Shield, Lock,
  Clock, CheckCircle2, Info, Banknote, Loader2, AlertCircle,
  RotateCcw, XCircle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { formatShortDateEST } from "@/lib/timezoneUtils";

function fmt(cents: number) { return (cents / 100).toFixed(2); }

// ─── Fee logic ───
function useFee(netCents: number, isAch: boolean, mapping: any) {
  const passProcessingFee = mapping?.pass_processing_fee ?? false;
  const feePercent = Number(mapping?.processing_fee_percent) || 0.029;
  const feeFixed = Number(mapping?.processing_fee_fixed_cents) || 30;
  let feeCents = 0;
  if (passProcessingFee && netCents > 0) {
    if (isAch) { feeCents = Math.min(Math.ceil(netCents * 0.008), 500); }
    else { feeCents = Math.ceil((netCents + feeFixed) / (1 - feePercent)) - netCents; }
  }
  return { feeCents, totalCents: netCents + feeCents, passProcessingFee };
}

function FeeDisclaimer({ netCents, isAch, mapping }: { netCents: number; isAch: boolean; mapping: any }) {
  const { feeCents, totalCents, passProcessingFee } = useFee(netCents, isAch, mapping);
  if (!netCents || netCents <= 0) return null;
  if (!passProcessingFee) {
    return (
      <div className="rounded-lg border border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-800 p-3 flex items-center gap-2">
        <CheckCircle2 className="h-4 w-4 text-green-600 shrink-0" />
        <p className="text-sm text-green-800 dark:text-green-300">
          <span className="font-semibold">No processing fee.</span>{" "}
          You will be charged exactly <span className="font-bold">${fmt(netCents)}</span>.
        </p>
      </div>
    );
  }
  return (
    <div className="rounded-lg border-2 border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-950/20 p-4 space-y-3">
      <div className="flex items-start gap-2">
        <AlertCircle className="h-4 w-4 text-amber-600 mt-0.5 shrink-0" />
        <p className="text-sm text-amber-900 dark:text-amber-200">
          <span className="font-bold">Processing fee applies.</span>{" "}
          {isAch ? "0.8% ACH fee (max $5.00)" : "2.9% + $0.30 card fee"} added per policy.
        </p>
      </div>
      <div className="grid grid-cols-3 gap-2">
        <div className="rounded-lg bg-background border p-2.5 text-center">
          <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide mb-1">Assessment</p>
          <p className="text-base font-bold text-foreground">${fmt(netCents)}</p>
        </div>
        <div className="rounded-lg bg-background border p-2.5 text-center">
          <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide mb-1">Fee</p>
          <p className="text-base font-bold text-foreground">+${fmt(feeCents)}</p>
        </div>
        <div className="rounded-lg bg-primary p-2.5 text-center">
          <p className="text-xs text-primary-foreground/80 font-semibold uppercase tracking-wide mb-1">You Pay</p>
          <p className="text-base font-bold text-primary-foreground">${fmt(totalCents)}</p>
        </div>
      </div>
    </div>
  );
}

// ─── Stripe Checkout form ───
function CheckoutForm({
  netCents, isAch, mapping, clientSecret, paymentIntentId, onSuccess, onCancel,
}: {
  netCents: number; isAch: boolean; mapping: any; clientSecret: string;
  paymentIntentId: string | null; onSuccess: () => void; onCancel: () => void;
}) {
  const stripe = useStripe();
  const elements = useElements();
  const { toast } = useToast();
  const [isProcessing, setIsProcessing] = useState(false);
  const { totalCents } = useFee(netCents, isAch, mapping);

  const handleSubmit = async () => {
    if (!stripe || !elements) return;
    setIsProcessing(true);
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: { return_url: window.location.href },
      redirect: "if_required",
    });
    if (error) {
      toast({ title: "Payment Failed", description: error.message, variant: "destructive" });
      setIsProcessing(false);
    } else {
      // Record the payment on the owner's ledger
      if (paymentIntentId) {
        const { error: recErr } = await supabase.functions.invoke("record-stripe-payment", {
          body: { payment_intent_id: paymentIntentId },
        });
        if (recErr) {
          console.error("Ledger recording failed:", recErr);
          toast({
            title: "Payment received — ledger sync pending",
            description: "Your payment was charged but the ledger update is still processing.",
          });
        } else {
          toast({ title: "Payment Successful!", description: `$${fmt(totalCents)} has been charged and posted to your ledger.` });
        }
      } else {
        toast({ title: "Payment Successful!", description: `$${fmt(totalCents)} has been charged.` });
      }
      onSuccess();
    }
  };

  return (
    <div className="space-y-4">
      <FeeDisclaimer netCents={netCents} isAch={isAch} mapping={mapping} />
      <PaymentElement options={{ layout: "tabs" }} />
      <div className="flex gap-3 pt-2">
        <Button variant="outline" onClick={onCancel} disabled={isProcessing} className="flex-1">Cancel</Button>
        <Button onClick={handleSubmit} disabled={isProcessing || !stripe} className="flex-1 gap-2">
          {isProcessing ? <><Loader2 className="h-4 w-4 animate-spin" /> Processing...</> : <>Pay ${fmt(totalCents)}</>}
        </Button>
      </div>
    </div>
  );
}

// Forte removed


// ─── Main Page ───
export default function HomeownerPaymentsPage() {
  const { toast } = useToast();
  const [paymentMethod, setPaymentMethod] = useState<"card" | "ach">("card");
  const [frequency, setFrequency] = useState<"one-time" | "auto-pay">("one-time");
  const [amount, setAmount] = useState("");

  const [ownerData, setOwnerData] = useState<any>(null);
  const [stripeMapping, setStripeMapping] = useState<any>(null);
  const [activeGateway, setActiveGateway] = useState<"stripe" | null>(null);
  const [stripePromise, setStripePromise] = useState<Promise<Stripe | null> | null>(null);
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [paymentIntentId, setPaymentIntentId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [debugError, setDebugError] = useState<string | null>(null);
  const [paymentHistory, setPaymentHistory] = useState<any[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);

  const isAch = paymentMethod === "ach";
  const netCents = Math.round(parseFloat(amount || "0") * 100);
  const currentMapping = stripeMapping;

  useEffect(() => {
    const init = async () => {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      const { data: owner } = await supabase
        .from("owners")
        .select("id, first_name, last_name, association_id, unit_id, property_address, units(unit_number, account_number)")
        .eq("user_id", user.id)
        .neq("status", "archived")
        .maybeSingle();

      if (!owner) return;
      setOwnerData(owner);

      const { data: gateways } = await supabase.rpc("get_association_payment_gateways", {
        p_association_id: owner.association_id,
      });

      const stripeData = (gateways as any)?.stripe || null;

      if (stripeData) {
        setStripeMapping(stripeData);
        setStripePromise(loadStripe(stripeData.stripe_public_key, { stripeAccount: stripeData.stripe_account_id }));
        setActiveGateway("stripe");
      } else {
        setDebugError("Online payments are not yet configured for your association.");
      }

      fetchHistory(owner.id, owner.association_id);
    };
    init();
  }, []);

  const fetchHistory = async (ownerId: string, associationId: string) => {
    setHistoryLoading(true);
    const { data } = await supabase
      .from("stripe_payments").select("*")
      .eq("owner_id", ownerId).eq("association_id", associationId)
      .order("created_at", { ascending: false }).limit(15);
    setPaymentHistory(data || []);
    setHistoryLoading(false);
  };

  const handleProceedToPayment = async () => {
    setDebugError(null);
    if (!amount || isNaN(parseFloat(amount)) || parseFloat(amount) <= 0) {
      toast({ title: "Invalid Amount", description: "Enter a valid amount greater than $0.", variant: "destructive" });
      return;
    }

    if (!stripeMapping) { setDebugError("Stripe not configured."); return; }
    setIsLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("create-payment-intent", {
        body: {
          amount_cents: netCents, association_id: ownerData.association_id,
          owner_id: ownerData.id, unit_id: ownerData.unit_id,
          payment_method_type: isAch ? "us_bank_account" : "card",
          description: `Assessment Payment — ${ownerData.property_address || ownerData.units?.account_number || "Unit"}`,
        },
      });
      if (error) throw new Error(error.message);
      if (data?.error) throw new Error(data.error);
      if (!data?.clientSecret) throw new Error("Missing client secret.");
      setClientSecret(data.clientSecret);
      setPaymentIntentId(data.paymentIntentId || null);
    } catch (err: any) {
      setDebugError(err.message);
      toast({ title: "Payment Request Failed", description: err.message, variant: "destructive" });
    } finally { setIsLoading(false); }
  };

  const resetForm = () => {
    setClientSecret(null);
    setPaymentIntentId(null);
    setAmount("");
    setDebugError(null);
    if (ownerData) fetchHistory(ownerData.id, ownerData.association_id);
  };

  const stripeOptions = clientSecret ? {
    clientSecret,
    appearance: { theme: "stripe" as const, variables: { colorPrimary: "#2563eb" } },
  } : undefined;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
          <CreditCard className="h-6 w-6 text-primary" /> Payments
        </h1>
        <p className="text-muted-foreground mt-1 text-sm">
          Manage dues, set up recurring payments, and view your transaction history.
        </p>
      </div>

      {debugError && !clientSecret && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{debugError}</AlertDescription>
          <Button variant="outline" size="sm" className="mt-2" onClick={resetForm}>
            <RotateCcw className="mr-1.5 h-3 w-3" /> Try Again
          </Button>
        </Alert>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
        <Card className="lg:col-span-3">
          <CardHeader>
            <CardTitle>Make a Payment</CardTitle>
            <CardDescription>Processed securely via Stripe</CardDescription>
          </CardHeader>
          <CardContent>
            {!clientSecret ? (
              <div className="space-y-5">
                {ownerData && (
                  <div className="flex items-center gap-2 rounded-md bg-muted px-4 py-2.5 text-sm">
                    <Info className="h-4 w-4 text-primary" />
                    <span className="text-muted-foreground">
                      Paying for:{" "}
                      <span className="font-medium text-foreground">
                        {ownerData.property_address || ownerData.units?.account_number || `${ownerData.first_name} ${ownerData.last_name}`}
                      </span>
                    </span>
                  </div>
                )}

                {/* Amount */}
                <div className="space-y-2">
                  <Label>Amount</Label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm font-medium">$</span>
                    <Input type="number" step="0.01" min="0.01" placeholder="0.00"
                      value={amount} onChange={e => setAmount(e.target.value)}
                      className="pl-7 text-lg font-semibold h-11" disabled={!activeGateway} />
                  </div>
                </div>

                {/* Payment Method */}
                {activeGateway && (
                  <div className="space-y-2">
                    <Label>Payment Method</Label>
                    <div className="grid grid-cols-2 gap-3">
                      <button type="button" onClick={() => setPaymentMethod("card")}
                        className={cn(
                          "flex flex-col items-center gap-1.5 rounded-lg border-2 p-4 transition-colors",
                          paymentMethod === "card" ? "border-primary bg-primary/5" : "border-border hover:border-muted-foreground/30"
                        )}>
                        <CreditCard className={cn("h-5 w-5", paymentMethod === "card" ? "text-primary" : "text-muted-foreground")} />
                        <span className="text-sm font-medium">Credit / Debit Card</span>
                      </button>
                      <button type="button" onClick={() => setPaymentMethod("ach")}
                        className={cn(
                          "flex flex-col items-center gap-1.5 rounded-lg border-2 p-4 transition-colors",
                          paymentMethod === "ach" ? "border-primary bg-primary/5" : "border-border hover:border-muted-foreground/30"
                        )}>
                        <Landmark className={cn("h-5 w-5", paymentMethod === "ach" ? "text-primary" : "text-muted-foreground")} />
                        <span className="text-sm font-medium">Bank Account (ACH)</span>
                      </button>
                    </div>
                  </div>
                )}

                {netCents > 0 && currentMapping && (
                  <FeeDisclaimer netCents={netCents} isAch={isAch} mapping={currentMapping} />
                )}

                {/* Frequency */}
                {activeGateway && (
                  <div className="space-y-2">
                    <Label>Frequency</Label>
                    <div className="grid grid-cols-2 gap-3">
                      <button type="button" onClick={() => setFrequency("one-time")}
                        className={cn(
                          "flex items-center gap-2 rounded-lg border-2 px-4 py-3 transition-colors",
                          frequency === "one-time" ? "border-primary bg-primary/5" : "border-border hover:border-muted-foreground/30"
                        )}>
                        <Banknote className={cn("h-4 w-4", frequency === "one-time" ? "text-primary" : "text-muted-foreground")} />
                        <span className="text-sm font-medium">One-Time</span>
                        {frequency === "one-time" && <CheckCircle2 className="h-4 w-4 text-primary ml-auto" />}
                      </button>
                      <button type="button" onClick={() => setFrequency("auto-pay")}
                        className={cn(
                          "flex items-center gap-2 rounded-lg border-2 px-4 py-3 transition-colors",
                          frequency === "auto-pay" ? "border-primary bg-primary/5" : "border-border hover:border-muted-foreground/30"
                        )}>
                        <Clock className={cn("h-4 w-4", frequency === "auto-pay" ? "text-primary" : "text-muted-foreground")} />
                        <span className="text-sm font-medium">Auto-Pay</span>
                        {frequency === "auto-pay" && <CheckCircle2 className="h-4 w-4 text-primary ml-auto" />}
                      </button>
                    </div>
                  </div>
                )}

                <Button className="w-full gap-2" size="lg" onClick={handleProceedToPayment}
                  disabled={isLoading || !amount || parseFloat(amount) <= 0 || !activeGateway}>
                  {isLoading
                    ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Preparing...</>
                    : <>Continue to Payment <ArrowRight className="h-4 w-4" /></>}
                </Button>

                <div className="flex items-center justify-center gap-4 text-xs text-muted-foreground pt-2">
                  <span className="flex items-center gap-1"><Shield className="h-3.5 w-3.5" /> 256-bit SSL</span>
                  <span>·</span>
                  <span className="flex items-center gap-1">
                    <CreditCard className="h-3.5 w-3.5" /> Powered by Stripe
                  </span>
                  <span>·</span>
                  <span className="flex items-center gap-1"><Lock className="h-3.5 w-3.5" /> PCI Compliant</span>
                </div>
              </div>
            ) : stripePromise && stripeOptions ? (
              <div className="animate-in fade-in slide-in-from-bottom-2 duration-300">
                <Elements options={stripeOptions} stripe={stripePromise}>
                  <CheckoutForm
                    netCents={netCents} isAch={isAch} mapping={stripeMapping}
                    clientSecret={clientSecret!} paymentIntentId={paymentIntentId}
                    onSuccess={resetForm} onCancel={resetForm}
                  />
                </Elements>
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">Payment gateway not initialized.</div>
            )}
          </CardContent>
        </Card>

        {/* Payment History */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Payment History</CardTitle>
            <CardDescription>Recent transactions for this unit</CardDescription>
          </CardHeader>
          <CardContent className="p-0">
            {historyLoading ? (
              <div className="p-10 flex justify-center"><Loader2 className="h-7 w-7 animate-spin text-primary" /></div>
            ) : paymentHistory.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-center px-4">
                <Banknote className="h-8 w-8 text-muted-foreground/40 mb-3" />
                <p className="text-sm text-muted-foreground">No recent payments found.</p>
              </div>
            ) : (
              <div className="divide-y max-h-[560px] overflow-y-auto">
                {paymentHistory.map(tx => {
                  const isSuccess = tx.status === "succeeded";
                  const isPending = tx.status === "pending" || tx.status === "processing";
                  return (
                    <div key={tx.id} className="px-5 py-3.5 hover:bg-muted/50 transition-colors flex items-center gap-3">
                      <div className={cn(
                        "p-2 rounded-full shrink-0",
                        isSuccess ? "bg-green-100 dark:bg-green-900/30 text-green-600"
                          : isPending ? "bg-amber-100 dark:bg-amber-900/30 text-amber-600"
                          : "bg-red-100 dark:bg-red-900/30 text-red-600"
                      )}>
                        {isSuccess ? <CheckCircle2 className="h-4 w-4" /> : isPending ? <Clock className="h-4 w-4" /> : <XCircle className="h-4 w-4" />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-foreground truncate">{tx.description || "Payment"}</p>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <p className="text-xs text-muted-foreground">{formatShortDateEST(tx.created_at)}</p>
                          {(tx.payment_method_type === "us_bank_account" || tx.payment_method_type === "echeck") && (
                            <Badge variant="outline" className="text-xs py-0 h-4">ACH</Badge>
                          )}
                          {tx.description?.includes("Forte") && (
                            <Badge variant="outline" className="text-xs py-0 h-4">Forte</Badge>
                          )}
                        </div>
                      </div>
                      <div className="text-right shrink-0">
                        <p className="text-sm font-semibold text-foreground">${fmt(tx.amount_cents)}</p>
                        <p className="text-xs text-muted-foreground capitalize">{tx.status}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
