"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Dialog, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { formatPence } from "@/lib/utils"
import { Plus, QrCode, Calendar, MapPin, Target, ExternalLink } from "lucide-react"
import Link from "next/link"

interface EventSummary {
  id: string
  name: string
  slug: string
  eventDate: string | null
  location: string | null
  goalAmount: number | null
  status: string
  pledgeCount: number
  qrSourceCount: number
  totalPledged: number
  totalCollected: number
  paymentMode?: string
  externalPlatform?: string
}

const platformNames: Record<string, string> = {
  launchgood: "🌙 LaunchGood",
  enthuse: "💜 Enthuse",
  justgiving: "💛 JustGiving",
  gofundme: "💚 GoFundMe",
  other: "🔗 External",
}

export default function EventsPage() {
  const [events, setEvents] = useState<EventSummary[]>([])
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)

  useEffect(() => {
    fetch("/api/events")
      .then((r) => r.json())
      .then((data) => {
        if (Array.isArray(data)) setEvents(data)
      })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])
  const [creating, setCreating] = useState(false)
  const [orgType, setOrgType] = useState<string | null>(null)
  const [form, setForm] = useState({ name: "", description: "", location: "", eventDate: "", goalAmount: "", paymentMode: "self" as "self" | "external", externalUrl: "", externalPlatform: "", zakatEligible: false })

  // Fetch org type to customize the form
  useEffect(() => {
    fetch("/api/onboarding").then(r => r.json()).then(d => {
      if (d.orgType) setOrgType(d.orgType)
      // Auto-set external mode for fundraisers
      if (d.orgType === "fundraiser") setForm(f => ({ ...f, paymentMode: "external" }))
    }).catch(() => {})
  }, [])

  const handleCreate = async () => {
    setCreating(true)
    try {
      const res = await fetch("/api/events", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          description: form.description || undefined,
          location: form.location || undefined,
          goalAmount: form.goalAmount ? Math.round(parseFloat(form.goalAmount) * 100) : undefined,
          eventDate: form.eventDate ? new Date(form.eventDate).toISOString() : undefined,
          paymentMode: form.paymentMode,
          externalUrl: form.externalUrl || undefined,
          externalPlatform: form.paymentMode === "external" ? (form.externalPlatform || "other") : undefined,
          zakatEligible: form.zakatEligible,
        }),
      })
      if (res.ok) {
        const event = await res.json()
        setEvents((prev) => [{ ...event, pledgeCount: 0, qrSourceCount: 0, totalPledged: 0, totalCollected: 0 }, ...prev])
        setShowCreate(false)
        setForm({ name: "", description: "", location: "", eventDate: "", goalAmount: "", paymentMode: orgType === "fundraiser" ? "external" : "self", externalUrl: "", externalPlatform: "", zakatEligible: false })
      }
    } catch {
      // handle error
    }
    setCreating(false)
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-900">Campaigns</h1>
          <p className="text-muted-foreground mt-1">Create campaigns, share pledge links, and track donations</p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="h-4 w-4 mr-2" /> New Campaign
        </Button>
      </div>

      {/* Event cards */}
      <div className="grid md:grid-cols-2 gap-4">
        {events.map((event) => {
          const progress = event.goalAmount ? Math.round((event.totalPledged / event.goalAmount) * 100) : 0

          return (
            <Card key={event.id} className="hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-lg">{event.name}</CardTitle>
                    <CardDescription className="flex items-center gap-3 mt-1">
                      {event.eventDate && (
                        <span className="flex items-center gap-1">
                          <Calendar className="h-3 w-3" />
                          {new Date(event.eventDate).toLocaleDateString("en-GB")}
                        </span>
                      )}
                      {event.location && (
                        <span className="flex items-center gap-1">
                          <MapPin className="h-3 w-3" />
                          {event.location}
                        </span>
                      )}
                    </CardDescription>
                  </div>
                  <div className="flex gap-1.5">
                    {event.paymentMode === "external" && event.externalPlatform && (
                      <Badge variant="outline" className="text-[10px]">{platformNames[event.externalPlatform] || "External"}</Badge>
                    )}
                    <Badge variant={event.status === "active" ? "success" : "secondary"}>
                      {event.status}
                    </Badge>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-3 gap-4 text-center">
                  <div>
                    <p className="text-xl font-bold">{event.pledgeCount}</p>
                    <p className="text-xs text-muted-foreground">Pledges</p>
                  </div>
                  <div>
                    <p className="text-xl font-bold">{formatPence(event.totalPledged)}</p>
                    <p className="text-xs text-muted-foreground">Pledged</p>
                  </div>
                  <div>
                    <p className="text-xl font-bold text-success-green">{formatPence(event.totalCollected)}</p>
                    <p className="text-xs text-muted-foreground">Collected</p>
                  </div>
                </div>

                {event.goalAmount && (
                  <div>
                    <div className="flex justify-between text-xs text-muted-foreground mb-1">
                      <span>{progress}% of goal</span>
                      <span className="flex items-center gap-1">
                        <Target className="h-3 w-3" /> {formatPence(event.goalAmount)}
                      </span>
                    </div>
                    <div className="h-2 rounded-full bg-gray-100 overflow-hidden">
                      <div
                        className="h-full rounded-full bg-trust-blue transition-all"
                        style={{ width: `${Math.min(progress, 100)}%` }}
                      />
                    </div>
                  </div>
                )}

                <div className="flex gap-2">
                  <Link href={`/dashboard/events/${event.id}`} className="flex-1">
                    <Button variant="outline" size="sm" className="w-full">
                      <QrCode className="h-4 w-4 mr-1" /> Pledge Links ({event.qrSourceCount})
                    </Button>
                  </Link>
                  <Link href={`/dashboard/pledges?event=${event.id}`} className="flex-1">
                    <Button variant="outline" size="sm" className="w-full">
                      View Pledges
                    </Button>
                  </Link>
                </div>
              </CardContent>
            </Card>
          )
        })}
      </div>

      {/* Create dialog */}
      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogHeader>
          <DialogTitle>New Campaign</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label>Campaign Name *</Label>
            <Input
              placeholder="e.g. Ramadan Appeal 2026, Mosque Building Fund"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            />
          </div>
          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea
              placeholder="Brief description..."
              value={form.description}
              onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Date</Label>
              <Input
                type="datetime-local"
                value={form.eventDate}
                onChange={(e) => setForm((f) => ({ ...f, eventDate: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Goal (£)</Label>
              <Input
                type="number"
                placeholder="50000"
                value={form.goalAmount}
                onChange={(e) => setForm((f) => ({ ...f, goalAmount: e.target.value }))}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Location</Label>
            <Input
              placeholder="Venue name and address"
              value={form.location}
              onChange={(e) => setForm((f) => ({ ...f, location: e.target.value }))}
            />
          </div>

          {/* Payment mode toggle */}
          <div className="space-y-2">
            <Label>How do donors pay?</Label>
            <div className="grid grid-cols-2 gap-2">
              <button
                type="button"
                onClick={() => setForm(f => ({ ...f, paymentMode: "self" }))}
                className={`rounded-xl border p-3 text-left text-xs transition-all ${form.paymentMode === "self" ? "border-trust-blue bg-trust-blue/5" : "border-gray-200"}`}
              >
                <span className="font-bold block">🏦 Bank transfer</span>
                <span className="text-muted-foreground">We show our bank details</span>
              </button>
              <button
                type="button"
                onClick={() => setForm(f => ({ ...f, paymentMode: "external" }))}
                className={`rounded-xl border p-3 text-left text-xs transition-all ${form.paymentMode === "external" ? "border-warm-amber bg-warm-amber/5" : "border-gray-200"}`}
              >
                <span className="font-bold block">🔗 External page</span>
                <span className="text-muted-foreground">LaunchGood, Enthuse, etc.</span>
              </button>
            </div>
          </div>

          {form.paymentMode === "external" && (
            <div className="space-y-3 rounded-xl border border-warm-amber/20 bg-warm-amber/5 p-3">
              <div className="space-y-2">
                <Label>Fundraising page URL *</Label>
                <div className="relative">
                  <ExternalLink className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="https://launchgood.com/my-campaign"
                    value={form.externalUrl}
                    onChange={(e) => setForm((f) => ({ ...f, externalUrl: e.target.value }))}
                    className="pl-9"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Platform</Label>
                <select
                  value={form.externalPlatform}
                  onChange={(e) => setForm(f => ({ ...f, externalPlatform: e.target.value }))}
                  className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm"
                >
                  <option value="">Select platform...</option>
                  <option value="launchgood">🌙 LaunchGood</option>
                  <option value="enthuse">💜 Enthuse</option>
                  <option value="justgiving">💛 JustGiving</option>
                  <option value="gofundme">💚 GoFundMe</option>
                  <option value="other">🔗 Other / Custom</option>
                </select>
              </div>
            </div>
          )}

          {/* Zakat eligible toggle */}
          <button
            type="button"
            onClick={() => setForm(f => ({ ...f, zakatEligible: !f.zakatEligible }))}
            className={`w-full flex items-center justify-between rounded-xl border-2 p-3 text-left transition-all ${
              form.zakatEligible ? "border-trust-blue bg-trust-blue/5" : "border-gray-200"
            }`}
          >
            <div>
              <p className="text-sm font-bold">🌙 Zakat eligible</p>
              <p className="text-xs text-muted-foreground">Let donors mark their pledge as Zakat</p>
            </div>
            <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${form.zakatEligible ? "bg-trust-blue border-trust-blue" : "border-gray-300"}`}>
              {form.zakatEligible && <span className="text-white text-xs font-bold">✓</span>}
            </div>
          </button>

          {/* External URL for self-payment campaigns (for reference/allocation) */}
          {form.paymentMode === "self" && (
            <div className="space-y-2">
              <Label>External fundraising page <span className="text-muted-foreground font-normal">(optional)</span></Label>
              <div className="relative">
                <ExternalLink className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="https://launchgood.com/my-campaign"
                  value={form.externalUrl}
                  onChange={(e) => setForm(f => ({ ...f, externalUrl: e.target.value }))}
                  className="pl-9"
                />
              </div>
              <p className="text-[10px] text-muted-foreground">Link an external page for reference. Payments still go via your bank.</p>
            </div>
          )}

          <div className="flex gap-3 pt-2">
            <Button variant="outline" onClick={() => setShowCreate(false)} className="flex-1">
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={!form.name || creating || (form.paymentMode === "external" && !form.externalUrl)} className="flex-1">
              {creating ? "Creating..." : "Create Campaign"}
            </Button>
          </div>
        </div>
      </Dialog>
    </div>
  )
}
