"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 { Building2, CreditCard, Palette, Check, Loader2, AlertCircle } from "lucide-react"

interface OrgSettings {
  name: string
  bankName: string
  bankSortCode: string
  bankAccountNo: string
  bankAccountName: string
  refPrefix: string
  primaryColor: string
  gcAccessToken: string
  gcEnvironment: string
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<OrgSettings | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState<string | null>(null)
  const [saved, setSaved] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch("/api/settings", { headers: { "x-org-id": "demo" } })
      .then((r) => r.json())
      .then((data) => {
        if (data.name) setSettings(data)
      })
      .catch(() => setError("Failed to load settings"))
      .finally(() => setLoading(false))
  }, [])

  const save = async (section: string, data: Record<string, string>) => {
    setSaving(section)
    setError(null)
    try {
      const res = await fetch("/api/settings", {
        method: "PATCH",
        headers: { "Content-Type": "application/json", "x-org-id": "demo" },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        setSaved(section)
        setTimeout(() => setSaved(null), 2000)
      } else {
        setError("Failed to save")
      }
    } catch {
      setError("Failed to save")
    }
    setSaving(null)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-8 w-8 text-trust-blue animate-spin" />
      </div>
    )
  }

  if (!settings) {
    return (
      <div className="text-center py-20">
        <AlertCircle className="h-8 w-8 text-danger-red mx-auto mb-2" />
        <p className="text-muted-foreground">Failed to load settings</p>
      </div>
    )
  }

  const update = (key: keyof OrgSettings, value: string) => {
    setSettings((s) => s ? { ...s, [key]: value } : s)
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h1 className="text-3xl font-extrabold text-gray-900">Settings</h1>
        <p className="text-muted-foreground mt-1">Configure your organisation&apos;s payment details</p>
      </div>

      {error && (
        <div className="rounded-xl bg-danger-red/10 border border-danger-red/20 p-3 text-sm text-danger-red">
          {error}
        </div>
      )}

      {/* Bank Details */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Building2 className="h-5 w-5" /> Bank Account Details
          </CardTitle>
          <CardDescription>
            These details are shown to donors when they choose bank transfer.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Bank Name</Label>
              <Input value={settings.bankName} onChange={(e) => update("bankName", e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Account Name</Label>
              <Input value={settings.bankAccountName} onChange={(e) => update("bankAccountName", e.target.value)} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Sort Code</Label>
              <Input value={settings.bankSortCode} onChange={(e) => update("bankSortCode", e.target.value)} placeholder="XX-XX-XX" />
            </div>
            <div className="space-y-2">
              <Label>Account Number</Label>
              <Input value={settings.bankAccountNo} onChange={(e) => update("bankAccountNo", e.target.value)} placeholder="XXXXXXXX" />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Reference Prefix</Label>
            <Input value={settings.refPrefix} onChange={(e) => update("refPrefix", e.target.value)} maxLength={4} />
            <p className="text-xs text-muted-foreground">Max 4 chars. Used in payment references, e.g. {settings.refPrefix}-XXXX-50</p>
          </div>
          <Button
            onClick={() => save("bank", {
              bankName: settings.bankName,
              bankSortCode: settings.bankSortCode,
              bankAccountNo: settings.bankAccountNo,
              bankAccountName: settings.bankAccountName,
              refPrefix: settings.refPrefix,
            })}
            disabled={saving === "bank"}
          >
            {saving === "bank" ? (
              <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving...</>
            ) : saved === "bank" ? (
              <><Check className="h-4 w-4 mr-2" /> Saved!</>
            ) : (
              "Save Bank Details"
            )}
          </Button>
        </CardContent>
      </Card>

      {/* GoCardless */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <CreditCard className="h-5 w-5" /> GoCardless (Direct Debit)
          </CardTitle>
          <CardDescription>
            Connect GoCardless to enable Direct Debit collection.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Access Token</Label>
            <Input
              type="password"
              value={settings.gcAccessToken}
              onChange={(e) => update("gcAccessToken", e.target.value)}
              placeholder="sandbox_xxxxx or live_xxxxx"
            />
          </div>
          <div className="space-y-2">
            <Label>Environment</Label>
            <div className="flex gap-3">
              {["sandbox", "live"].map((env) => (
                <button
                  key={env}
                  onClick={() => update("gcEnvironment", env)}
                  className={`px-4 py-2 rounded-xl text-sm font-medium border-2 transition-colors ${
                    settings.gcEnvironment === env
                      ? env === "live"
                        ? "border-danger-red bg-danger-red/5 text-danger-red"
                        : "border-trust-blue bg-trust-blue/5 text-trust-blue"
                      : "border-gray-200 text-muted-foreground hover:border-gray-300"
                  }`}
                >
                  {env.charAt(0).toUpperCase() + env.slice(1)}
                  {env === "live" && settings.gcEnvironment === "live" && " ⚠️"}
                </button>
              ))}
            </div>
            {settings.gcEnvironment === "live" && (
              <p className="text-xs text-danger-red font-medium">⚠️ Live mode will create real Direct Debit mandates</p>
            )}
          </div>
          <Button
            onClick={() => save("gc", {
              gcAccessToken: settings.gcAccessToken,
              gcEnvironment: settings.gcEnvironment,
            })}
            disabled={saving === "gc"}
          >
            {saving === "gc" ? (
              <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving...</>
            ) : saved === "gc" ? (
              <><Check className="h-4 w-4 mr-2" /> Connected!</>
            ) : (
              "Save GoCardless Settings"
            )}
          </Button>
        </CardContent>
      </Card>

      {/* Branding */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Palette className="h-5 w-5" /> Branding
          </CardTitle>
          <CardDescription>
            Customise the look of your pledge pages.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Organisation Name</Label>
            <Input
              value={settings.name}
              onChange={(e) => update("name", e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>Primary Colour</Label>
            <div className="flex gap-2">
              <Input
                type="color"
                value={settings.primaryColor}
                onChange={(e) => update("primaryColor", e.target.value)}
                className="w-14 h-11 p-1"
              />
              <Input
                value={settings.primaryColor}
                onChange={(e) => update("primaryColor", e.target.value)}
                className="flex-1"
              />
            </div>
          </div>
          <Button
            onClick={() => save("brand", {
              name: settings.name,
              primaryColor: settings.primaryColor,
            })}
            disabled={saving === "brand"}
          >
            {saving === "brand" ? (
              <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving...</>
            ) : saved === "brand" ? (
              <><Check className="h-4 w-4 mr-2" /> Saved!</>
            ) : (
              "Save Branding"
            )}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
