"use client"

import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { AmountStep } from "./steps/amount-step"
import { ScheduleStep } from "./steps/schedule-step"
import { PaymentStep } from "./steps/payment-step"
import { IdentityStep } from "./steps/identity-step"
import { ConfirmationStep } from "./steps/confirmation-step"
import { BankInstructionsStep } from "./steps/bank-instructions-step"
import { CardPaymentStep } from "./steps/card-payment-step"
import { DirectDebitStep } from "./steps/direct-debit-step"

export type Rail = "bank" | "gocardless" | "card"

export interface PledgeData {
  amountPence: number
  rail: Rail
  donorName: string
  donorEmail: string
  donorPhone: string
  giftAid: boolean
  // Scheduling
  scheduleMode: "now" | "date" | "installments"
  dueDate?: string
  installmentCount?: number
  installmentDates?: string[]
}

interface EventInfo {
  id: string
  name: string
  organizationName: string
  qrSourceId: string | null
  qrSourceLabel: string | null
}

/*
  Flow:
  0 = Amount
  1 = Schedule (When to pay?)  ← NEW
  2 = Payment method (if "now") or Identity (if deferred)
  3 = Identity (for bank transfer "now")
  4 = Bank instructions (now)
  5 = Confirmation (generic — card, DD, or deferred pledge)
  6 = Card payment
  8 = Direct Debit
*/

export default function PledgePage() {
  const params = useParams()
  const token = params.token as string
  const [step, setStep] = useState(0)
  const [eventInfo, setEventInfo] = useState<EventInfo | null>(null)
  const [pledgeData, setPledgeData] = useState<PledgeData>({
    amountPence: 0,
    rail: "bank",
    donorName: "",
    donorEmail: "",
    donorPhone: "",
    giftAid: false,
    scheduleMode: "now",
  })
  const [pledgeResult, setPledgeResult] = useState<{
    id: string
    reference: string
    bankDetails?: { bankName: string; sortCode: string; accountNo: string; accountName: string }
  } | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")

  useEffect(() => {
    fetch(`/api/qr/${token}`)
      .then((r) => r.json())
      .then((data) => {
        if (data.error) setError(data.error)
        else setEventInfo(data)
        setLoading(false)
      })
      .catch(() => { setError("Unable to load pledge page"); setLoading(false) })
    fetch("/api/analytics", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventType: "pledge_start", metadata: { token } }),
    }).catch(() => {})
  }, [token])

  // Step 0: Amount selected
  const handleAmountSelected = (amountPence: number) => {
    setPledgeData((d) => ({ ...d, amountPence }))
    setStep(1) // → Schedule step
  }

  // Step 1: Schedule selected
  const handleScheduleSelected = (schedule: {
    mode: "now" | "date" | "installments"
    dueDate?: string
    installmentCount?: number
    installmentDates?: string[]
  }) => {
    setPledgeData((d) => ({
      ...d,
      scheduleMode: schedule.mode,
      dueDate: schedule.dueDate,
      installmentCount: schedule.installmentCount,
      installmentDates: schedule.installmentDates,
    }))

    if (schedule.mode === "now") {
      setStep(2) // → Payment method selection
    } else {
      // Deferred or installments: skip payment method, go to identity
      // Payment method will be chosen when the due date arrives
      setPledgeData((d) => ({ ...d, rail: "bank" })) // default to bank for deferred
      setStep(3) // → Identity
    }
  }

  // Step 2: Payment method selected (only for "now" mode)
  const handleRailSelected = (rail: Rail) => {
    setPledgeData((d) => ({ ...d, rail }))
    setStep(rail === "bank" ? 3 : rail === "card" ? 6 : 8) // identity or card/DD
  }

  // Submit pledge (from identity step, or card/DD steps)
  const submitPledge = async (identity: { donorName: string; donorEmail: string; donorPhone: string; giftAid: boolean }) => {
    const finalData = { ...pledgeData, ...identity }
    setPledgeData(finalData)

    try {
      const res = await fetch("/api/pledges", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...finalData,
          eventId: eventInfo?.id,
          qrSourceId: eventInfo?.qrSourceId,
        }),
      })
      const result = await res.json()
      if (result.error) { setError(result.error); return }
      setPledgeResult(result)

      // Where to go after pledge is created:
      if (finalData.scheduleMode === "now" && finalData.rail === "bank") {
        setStep(4) // Bank instructions
      } else {
        setStep(5) // Confirmation
      }
    } catch {
      setError("Something went wrong. Please try again.")
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 gap-4">
        <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 flex items-center justify-center animate-pulse">
          <span className="text-white text-xl">🤲</span>
        </div>
        <p className="text-trust-blue font-medium animate-pulse">Loading...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 p-4">
        <div className="text-center space-y-4 animate-fade-up">
          <div className="text-5xl">😔</div>
          <h1 className="text-xl font-bold text-gray-900">Something went wrong</h1>
          <p className="text-muted-foreground">{error}</p>
          <button onClick={() => window.location.reload()} className="text-trust-blue font-medium hover:underline">
            Try again →
          </button>
        </div>
      </div>
    )
  }

  const shareUrl = `${typeof window !== "undefined" ? window.location.origin : ""}/p/${token}`
  const isDeferred = pledgeData.scheduleMode !== "now"

  // Format due date for display
  const dueDateLabel = pledgeData.dueDate
    ? new Date(pledgeData.dueDate).toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" })
    : pledgeData.installmentCount
      ? `${pledgeData.installmentCount} monthly payments`
      : undefined

  const steps: Record<number, React.ReactNode> = {
    0: <AmountStep onSelect={handleAmountSelected} eventName={eventInfo?.name || ""} eventId={eventInfo?.id} />,
    1: <ScheduleStep amount={pledgeData.amountPence} onSelect={handleScheduleSelected} />,
    2: <PaymentStep onSelect={handleRailSelected} amount={pledgeData.amountPence} />,
    3: <IdentityStep onSubmit={submitPledge} amount={pledgeData.amountPence} />,
    4: pledgeResult && <BankInstructionsStep pledge={pledgeResult} amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} donorPhone={pledgeData.donorPhone} />,
    5: pledgeResult && (
      <ConfirmationStep
        pledge={pledgeResult}
        amount={isDeferred && pledgeData.installmentCount ? Math.ceil(pledgeData.amountPence / pledgeData.installmentCount) * pledgeData.installmentCount : pledgeData.amountPence}
        rail={pledgeData.rail}
        eventName={eventInfo?.name || ""}
        shareUrl={shareUrl}
        donorPhone={pledgeData.donorPhone}
        isDeferred={isDeferred}
        dueDateLabel={dueDateLabel}
        installmentCount={pledgeData.installmentCount}
        installmentAmount={pledgeData.installmentCount ? Math.ceil(pledgeData.amountPence / pledgeData.installmentCount) : undefined}
      />
    ),
    6: <CardPaymentStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />,
    8: <DirectDebitStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} organizationName={eventInfo?.organizationName || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />,
  }

  const backableSteps = new Set([1, 2, 3, 6, 8])
  const getBackStep = (s: number): number => {
    if (s === 6 || s === 8) return 2  // card/DD → payment method
    if (s === 3 && pledgeData.scheduleMode !== "now") return 1 // deferred identity → schedule
    if (s === 3) return 2 // bank identity → payment method
    return s - 1
  }

  const progressMap: Record<number, number> = { 0: 8, 1: 25, 2: 40, 3: 60, 4: 100, 5: 100, 6: 60, 8: 60 }
  const progressPercent = progressMap[step] || 10

  return (
    <div className="min-h-screen bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5">
      {/* Progress bar */}
      <div className="fixed top-0 left-0 right-0 h-1 bg-gray-100 z-50">
        <div
          className="h-full bg-gradient-to-r from-trust-blue to-success-green transition-all duration-700 ease-out"
          style={{ width: `${progressPercent}%` }}
        />
      </div>

      {/* Header */}
      <div className="pt-6 pb-1 px-4 text-center">
        <p className="text-xs font-medium text-muted-foreground">{eventInfo?.organizationName}</p>
        {eventInfo?.qrSourceLabel && (
          <p className="text-[10px] text-muted-foreground/60">{eventInfo.qrSourceLabel}</p>
        )}
      </div>

      {/* Content */}
      <div className="px-4 pb-20">{steps[step]}</div>

      {/* Back button */}
      {backableSteps.has(step) && (
        <div className="fixed bottom-0 left-0 right-0 pb-6 pt-4 px-4 bg-gradient-to-t from-white via-white/80 to-transparent">
          <button
            onClick={() => setStep(getBackStep(step))}
            className="text-sm text-muted-foreground hover:text-foreground transition-colors tap-target flex items-center gap-1"
          >
            ← Back
          </button>
        </div>
      )}
    </div>
  )
}
