"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
// Badge available but not used yet
import { useToast } from "@/components/ui/toast"
import {
  Building2, Banknote, Calendar, QrCode, ArrowRight, CheckCircle2, Loader2, Sparkles
} from "lucide-react"

export default function SetupPage() {
  const [step, setStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const { toast } = useToast()

  // Org
  const [orgName, setOrgName] = useState("")
  const [charityNumber, setCharityNumber] = useState("")

  // Bank
  const [bankName, setBankName] = useState("")
  const [sortCode, setSortCode] = useState("")
  const [accountNo, setAccountNo] = useState("")
  const [accountName, setAccountName] = useState("")

  // Event
  const [eventName, setEventName] = useState("")
  const [eventDate, setEventDate] = useState("")
  const [targetPence, setTargetPence] = useState("")

  // Result
  const [setupResult, setSetupResult] = useState<{ orgId?: string; eventId?: string; qrToken?: string } | null>(null)

  const saveOrg = async () => {
    if (!orgName) { toast("Charity name is required", "error"); return }
    setLoading(true)
    try {
      const res = await fetch("/api/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: orgName,
          charityNumber,
          bankName,
          bankSortCode: sortCode,
          bankAccountNo: accountNo,
          bankAccountName: accountName || orgName,
        }),
      })
      const data = await res.json()
      if (data.id) setSetupResult(prev => ({ ...prev, orgId: data.id }))
      setStep(2)
    } catch {
      toast("Failed to save", "error")
    }
    setLoading(false)
  }

  const saveBankAndContinue = async () => {
    if (!sortCode || !accountNo) { toast("Bank details are required for donors to pay you", "error"); return }
    setLoading(true)
    try {
      await fetch("/api/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          bankName,
          bankSortCode: sortCode.replace(/\s/g, "").replace(/(\d{2})(\d{2})(\d{2})/, "$1-$2-$3"),
          bankAccountNo: accountNo.replace(/\s/g, ""),
          bankAccountName: accountName || orgName,
        }),
      })
      setStep(3)
    } catch {
      toast("Failed to save bank details", "error")
    }
    setLoading(false)
  }

  const createFirstEvent = async () => {
    if (!eventName) { toast("Event name is required", "error"); return }
    setLoading(true)
    try {
      const res = await fetch("/api/events", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: eventName,
          date: eventDate || undefined,
          targetPence: targetPence ? parseInt(targetPence) * 100 : undefined,
        }),
      })
      const data = await res.json()
      if (data.id) {
        setSetupResult(prev => ({ ...prev, eventId: data.id }))
        // Auto-generate a QR code
        const qrRes = await fetch(`/api/events/${data.id}/qr`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ label: "Main QR Code", volunteerName: "" }),
        })
        const qrData = await qrRes.json()
        if (qrData.token) setSetupResult(prev => ({ ...prev, qrToken: qrData.token }))
        setStep(4)
      }
    } catch {
      toast("Failed to create event", "error")
    }
    setLoading(false)
  }

  const steps = [
    { num: 1, label: "Charity", icon: Building2 },
    { num: 2, label: "Bank", icon: Banknote },
    { num: 3, label: "Event", icon: Calendar },
    { num: 4, label: "Ready!", icon: Sparkles },
  ]

  return (
    <div className="max-w-lg mx-auto space-y-6">
      {/* Progress */}
      <div className="flex items-center justify-between">
        {steps.map((s, i) => (
          <div key={s.num} className="flex items-center">
            <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold transition-all ${
              step >= s.num ? "bg-trust-blue text-white" : "bg-gray-100 text-gray-400"
            }`}>
              {step > s.num ? <CheckCircle2 className="h-5 w-5" /> : <s.icon className="h-5 w-5" />}
            </div>
            {i < steps.length - 1 && (
              <div className={`w-12 sm:w-20 h-0.5 mx-1 transition-all ${step > s.num ? "bg-trust-blue" : "bg-gray-200"}`} />
            )}
          </div>
        ))}
      </div>

      {/* Step 1: Org */}
      {step === 1 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="h-5 w-5 text-trust-blue" /> Your Charity
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>Charity Name *</Label>
              <Input value={orgName} onChange={e => setOrgName(e.target.value)} placeholder="e.g. Islamic Relief UK" />
            </div>
            <div>
              <Label>Charity Number <span className="text-muted-foreground">(optional)</span></Label>
              <Input value={charityNumber} onChange={e => setCharityNumber(e.target.value)} placeholder="e.g. 328158" />
            </div>
            <Button onClick={saveOrg} disabled={loading} className="w-full">
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <>Next: Bank Details <ArrowRight className="h-4 w-4 ml-1" /></>}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Step 2: Bank */}
      {step === 2 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Banknote className="h-5 w-5 text-trust-blue" /> Bank Details
            </CardTitle>
            <p className="text-sm text-muted-foreground">These will be shown to donors so they can make bank transfers to your charity.</p>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>Bank Name</Label>
              <Input value={bankName} onChange={e => setBankName(e.target.value)} placeholder="e.g. Barclays" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Sort Code *</Label>
                <Input value={sortCode} onChange={e => setSortCode(e.target.value)} placeholder="20-30-80" />
              </div>
              <div>
                <Label>Account Number *</Label>
                <Input value={accountNo} onChange={e => setAccountNo(e.target.value)} placeholder="12345678" />
              </div>
            </div>
            <div>
              <Label>Account Name</Label>
              <Input value={accountName} onChange={e => setAccountName(e.target.value)} placeholder={orgName || "Account holder name"} />
            </div>
            <Button onClick={saveBankAndContinue} disabled={loading} className="w-full">
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <>Next: Create Event <ArrowRight className="h-4 w-4 ml-1" /></>}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Step 3: Event */}
      {step === 3 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5 text-trust-blue" /> First Event
            </CardTitle>
            <p className="text-sm text-muted-foreground">Create an event to start collecting pledges. You can add more later.</p>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>Event Name *</Label>
              <Input value={eventName} onChange={e => setEventName(e.target.value)} placeholder="e.g. Annual Charity Gala 2026" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Event Date <span className="text-muted-foreground">(optional)</span></Label>
                <Input type="date" value={eventDate} onChange={e => setEventDate(e.target.value)} />
              </div>
              <div>
                <Label>Target (£) <span className="text-muted-foreground">(optional)</span></Label>
                <Input type="number" value={targetPence} onChange={e => setTargetPence(e.target.value)} placeholder="10000" />
              </div>
            </div>
            <Button onClick={createFirstEvent} disabled={loading} className="w-full">
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <>Create Event & Generate QR <QrCode className="h-4 w-4 ml-1" /></>}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Step 4: Done */}
      {step === 4 && (
        <Card className="border-success-green/30">
          <CardHeader className="text-center pb-2">
            <div className="mx-auto w-16 h-16 rounded-full bg-success-green/10 flex items-center justify-center mb-3">
              <Sparkles className="h-8 w-8 text-success-green" />
            </div>
            <CardTitle>You&apos;re All Set! 🎉</CardTitle>
            <p className="text-sm text-muted-foreground">Your charity is ready to collect pledges.</p>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="bg-gray-50 rounded-xl p-4 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Charity</span>
                <span className="text-sm font-medium">{orgName}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Bank</span>
                <span className="text-sm font-medium">{sortCode} / {accountNo}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Event</span>
                <span className="text-sm font-medium">{eventName}</span>
              </div>
            </div>

            {setupResult?.qrToken && (
              <div className="bg-trust-blue/5 rounded-xl p-4 text-center space-y-2">
                <QrCode className="h-8 w-8 text-trust-blue mx-auto" />
                <p className="text-sm font-medium">Your pledge link is ready</p>
                <code className="text-xs bg-white px-3 py-1.5 rounded-lg border block overflow-x-auto">
                  {typeof window !== "undefined" ? window.location.origin : ""}/p/{setupResult.qrToken}
                </code>
                <p className="text-xs text-muted-foreground">Share this link or print the QR code from your Events dashboard</p>
              </div>
            )}

            <div className="grid grid-cols-2 gap-2">
              <a href="/dashboard">
                <Button variant="outline" className="w-full">Go to Dashboard</Button>
              </a>
              <a href={`/dashboard/events${setupResult?.eventId ? `/${setupResult.eventId}/qr` : ""}`}>
                <Button className="w-full">Print QR Codes</Button>
              </a>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Tips */}
      {step < 4 && (
        <div className="bg-warm-amber/5 rounded-xl border border-warm-amber/20 p-4">
          <p className="text-xs font-semibold text-warm-amber mb-1">💡 Tip</p>
          {step === 1 && <p className="text-xs text-muted-foreground">Your charity name appears on the donor pledge page and WhatsApp receipts.</p>}
          {step === 2 && <p className="text-xs text-muted-foreground">Bank details are shown to donors who choose &quot;Bank Transfer&quot;. Each pledge gets a unique reference number for easy reconciliation.</p>}
          {step === 3 && <p className="text-xs text-muted-foreground">Give each volunteer their own QR code to track who brings in the most pledges. You can create more QR codes after setup.</p>}
        </div>
      )}
    </div>
  )
}
