"use client"

import type React from "react"

import { useEffect, useState } from "react"
import { Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

type Settings = {
  id?: number
  api_url_live?: string
  api_key_live?: string
  api_url_sandbox?: string
  api_key_sandbox?: string
  mode?: "live" | "sandbox"
  admin_address?: string
  admin_private_key?: string
  conversion_rate?: number | string
  contract_address?: string
  min_amount?: number | string
  max_amount?: number | string
  youtube_url?: string
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<Settings | null>(null)
  const [loading, setLoading] = useState(true)

  // General (form state)
  const [baseUrl, setBaseUrl] = useState("https://pay.neonecy.com")
  const [adminAddress, setAdminAddress] = useState("0xccC4EDed11160742F607599B55FEfA27DFE8fA15")
  const [adminPrivateKey, setAdminPrivateKey] = useState("")
  const [conversionRate, setConversionRate] = useState("0.03")
  const [contractAddress, setContractAddress] = useState("0xB4128af1bece30B0399c895EDF86E6Cae6565cDa")
  const [minAmount, setMinAmount] = useState<string>("")
  const [maxAmount, setMaxAmount] = useState<string>("")
  const [mode, setMode] = useState<"sandbox" | "live">("live")
  const [youtubeUrl, setYoutubeUrl] = useState<string>("")
  const [savingGeneral, setSavingGeneral] = useState(false)

  // Sandbox
  const [apiUrlSandbox, setApiUrlSandbox] = useState("https://sandbox.uddoktapay.com")
  const [apiKeySandbox, setApiKeySandbox] = useState("982d381360a69d419689740d9f2e26ce36fb7a50")
  const [savingSandbox, setSavingSandbox] = useState(false)

  // Live
  const [apiUrlLive, setApiUrlLive] = useState("https://pay.neonecy.com")
  const [apiKeyLive, setApiKeyLive] = useState("f1d5bd54b659a131aad3020f1bbcd15e5bd275d9")
  const [savingLive, setSavingLive] = useState(false)

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        const res = await fetch("/api/system-settings", { cache: "no-store" })
        const data = res.ok ? await res.json() : null
        if (!mounted) return

        const raw = Array.isArray(data?.data) ? data.data[0] : (data?.data ?? data ?? {})
        setSettings(raw)

        setBaseUrl(raw.api_url_live ?? "https://pay.neonecy.com")
        setAdminAddress(raw.admin_address ?? "0xccC4EDed11160742F607599B55FEfA27DFE8fA15")
        setAdminPrivateKey(raw.admin_private_key ?? "")
        setConversionRate(String(raw.conversion_rate ?? "0.03"))
        setContractAddress(raw.contract_address ?? "0xB4128af1bece30B0399c895EDF86E6Cae6565cDa")

        setMinAmount(raw.min_amount != null ? String(raw.min_amount) : "")
        setMaxAmount(raw.max_amount != null ? String(raw.max_amount) : "")
        setMode(raw.mode === "sandbox" || raw.mode === "live" ? raw.mode : "live")

        setApiUrlSandbox(raw.api_url_sandbox ?? "https://sandbox.uddoktapay.com")
        setApiKeySandbox(raw.api_key_sandbox ?? "982d381360a69d419689740d9f2e26ce36fb7a50")
        setApiUrlLive(raw.api_url_live ?? "https://pay.neonecy.com")
        setApiKeyLive(raw.api_key_live ?? "f1d5bd54b659a131aad3020f1bbcd15e5bd275d9")

        setYoutubeUrl(raw.youtube_url ?? "")
      } finally {
        if (mounted) setLoading(false)
      }
    })()
    return () => {
      mounted = false
    }
  }, [])

  async function saveGeneral(e: React.FormEvent) {
    e.preventDefault()
    setSavingGeneral(true)
    try {
      const id = (settings as any)?.id ?? 1
      const fd = new FormData()
      fd.append("id", String(id))
      fd.append("admin_address", adminAddress)
      fd.append("admin_private_key", adminPrivateKey)
      fd.append("contract_address", contractAddress)
      fd.append("conversion_rate", conversionRate)
      fd.append("api_url_live", baseUrl)

      if (minAmount !== "") fd.append("min_amount", minAmount)
      if (maxAmount !== "") fd.append("max_amount", maxAmount)
      fd.append("mode", mode)

      // New field: YouTube video URL
      // Backend parameter name: youtube_url
      if (youtubeUrl !== "") fd.append("youtube_url", youtubeUrl)

      const res = await fetch("/api/system-settings/update", { method: "POST", body: fd })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) {
        alert(`Failed to update: ${body?.message ?? res.statusText}`)
        return
      }
      alert("General settings updated.")
    } finally {
      setSavingGeneral(false)
    }
  }

  async function saveSandbox(e: React.FormEvent) {
    e.preventDefault()
    setSavingSandbox(true)
    try {
      const id = (settings as any)?.id ?? 1
      const fd = new FormData()
      fd.append("id", String(id))
      fd.append("mode", "sandbox")
      fd.append("api_url_sandbox", apiUrlSandbox)
      fd.append("api_key_sandbox", apiKeySandbox)
      const res = await fetch("/api/system-settings/update", { method: "POST", body: fd })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) {
        alert(`Failed to update: ${body?.message ?? res.statusText}`)
        return
      }
      alert("Sandbox settings updated.")
    } finally {
      setSavingSandbox(false)
    }
  }

  async function saveLive(e: React.FormEvent) {
    e.preventDefault()
    setSavingLive(true)
    try {
      const id = (settings as any)?.id ?? 1
      const fd = new FormData()
      fd.append("id", String(id))
      fd.append("mode", "live")
      fd.append("api_url_live", apiUrlLive)
      fd.append("api_key_live", apiKeyLive)
      const res = await fetch("/api/system-settings/update", { method: "POST", body: fd })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) {
        alert(`Failed to update: ${body?.message ?? res.statusText}`)
        return
      }
      alert("Live settings updated.")
    } finally {
      setSavingLive(false)
    }
  }

  const modeChipClass =
    mode === "live"
      ? "bg-emerald-100 text-emerald-700 border border-emerald-200"
      : "bg-amber-100 text-amber-700 border border-amber-200"

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
          <h1 className="text-xl sm:text-2xl font-semibold">Settings</h1>
          <p className="text-sm text-muted-foreground">Manage system configuration.</p>
        </div>

        {!loading && (
          <div className="flex flex-wrap items-center gap-2">
            <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${modeChipClass}`}>
              Active: {mode === "live" ? "Live" : "Sandbox"}
            </span>
            <span className="text-xs text-muted-foreground">
              Limits: {minAmount || "0"} - {maxAmount || "0"}
            </span>
          </div>
        )}
      </div>

      <Tabs defaultValue="general" className="w-full">
        <div className="overflow-x-auto">
          <TabsList className="flex min-w-[560px] sm:min-w-0 gap-1">
            <TabsTrigger value="general">General</TabsTrigger>
            <TabsTrigger value="sandbox">Sandbox</TabsTrigger>
            <TabsTrigger value="live">Live</TabsTrigger>
          </TabsList>
        </div>

        <TabsContent value="general">
          <Card>
            <CardHeader>
              <CardTitle className="text-base sm:text-lg">General Settings</CardTitle>
              <CardDescription>Update global configuration and active environment.</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" /> Loading...
                </div>
              ) : (
                <form onSubmit={saveGeneral} className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="baseUrl">Base API URL (Live)</Label>
                    <Input id="baseUrl" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="admin_address">Admin Address</Label>
                    <Input
                      id="admin_address"
                      value={adminAddress}
                      onChange={(e) => setAdminAddress(e.target.value)}
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="admin_private_key">Admin Private Key</Label>
                    <Input
                      id="admin_private_key"
                      type="password"
                      value={adminPrivateKey}
                      onChange={(e) => setAdminPrivateKey(e.target.value)}
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="conversion_rate">Conversion Rate</Label>
                    <Input
                      id="conversion_rate"
                      type="number"
                      step="0.00000001"
                      value={conversionRate}
                      onChange={(e) => setConversionRate(e.target.value)}
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="contract_address">Contract Address</Label>
                    <Input
                      id="contract_address"
                      value={contractAddress}
                      onChange={(e) => setContractAddress(e.target.value)}
                      required
                    />
                  </div>

                  {/* Mode selector */}
                  <div className="space-y-2">
                    <Label>Mode</Label>
                    <Select value={mode} onValueChange={(v: "sandbox" | "live") => setMode(v)}>
                      <SelectTrigger aria-label="Select mode">
                        <SelectValue placeholder="Select mode" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="sandbox">Sandbox</SelectItem>
                        <SelectItem value="live">Live</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Min / Max amount */}
                  <div className="space-y-2">
                    <Label htmlFor="min_amount">Minimum Amount</Label>
                    <Input
                      id="min_amount"
                      type="number"
                      min="0"
                      step="0.01"
                      value={minAmount}
                      onChange={(e) => setMinAmount(e.target.value)}
                      placeholder="e.g. 500"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="max_amount">Maximum Amount</Label>
                    <Input
                      id="max_amount"
                      type="number"
                      min="0"
                      step="0.01"
                      value={maxAmount}
                      onChange={(e) => setMaxAmount(e.target.value)}
                      placeholder="e.g. 1000"
                    />
                  </div>

                  {/* YouTube video URL */}
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="youtube_url">YouTube Video URL</Label>
                    <Input
                      id="youtube_url"
                      type="url"
                      placeholder="https://www.youtube.com/watch?v=XXXXXXXXXXX"
                      value={youtubeUrl}
                      onChange={(e) => setYoutubeUrl(e.target.value)}
                    />
                    <p className="text-xs text-muted-foreground">
                      Provide a full YouTube link (e.g., watch?v=..., youtu.be/..., or embed/...).
                    </p>
                  </div>

                  <div className="md:col-span-2">
                    <Button type="submit" disabled={savingGeneral}>
                      {savingGeneral ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Updating...
                        </>
                      ) : (
                        "Update"
                      )}
                    </Button>
                  </div>
                </form>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="sandbox">
          <Card>
            <CardHeader>
              <CardTitle className="text-base sm:text-lg">Sandbox Settings</CardTitle>
              <CardDescription>Configure sandbox API credentials.</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" /> Loading...
                </div>
              ) : (
                <form onSubmit={saveSandbox} className="grid gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="api_url_sandbox">Sandbox API URL</Label>
                    <Input
                      id="api_url_sandbox"
                      value={apiUrlSandbox}
                      onChange={(e) => setApiUrlSandbox(e.target.value)}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="api_key_sandbox">Sandbox API Key</Label>
                    <Input
                      id="api_key_sandbox"
                      value={apiKeySandbox}
                      onChange={(e) => setApiKeySandbox(e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <Button type="submit" disabled={savingSandbox}>
                      {savingSandbox ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Updating...
                        </>
                      ) : (
                        "Update"
                      )}
                    </Button>
                  </div>
                </form>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="live">
          <Card>
            <CardHeader>
              <CardTitle className="text-base sm:text-lg">Live Settings</CardTitle>
              <CardDescription>Configure live API credentials.</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" /> Loading...
                </div>
              ) : (
                <form onSubmit={saveLive} className="grid gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="api_url_live">Live API URL</Label>
                    <Input
                      id="api_url_live"
                      value={apiUrlLive}
                      onChange={(e) => setApiUrlLive(e.target.value)}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="api_key_live">Live API Key</Label>
                    <Input
                      id="api_key_live"
                      value={apiKeyLive}
                      onChange={(e) => setApiKeyLive(e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <Button type="submit" disabled={savingLive}>
                      {savingLive ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Updating...
                        </>
                      ) : (
                        "Update"
                      )}
                    </Button>
                  </div>
                </form>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
