"use client"

import { useState, useEffect } from "react"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Save } from "lucide-react"
import { useToast } from "@/hooks/use-toast"

interface Settings {
  [key: string]: string
}

export function SettingsManager() {
  const [settings, setSettings] = useState<Settings>({})
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const { toast } = useToast()

  useEffect(() => {
    loadSettings()
  }, [])

  const loadSettings = async () => {
    const supabase = createClient()
    const { data, error } = await supabase.from("site_settings").select("*")

    if (error) {
      toast({ title: "Erro ao carregar configurações", description: error.message, variant: "destructive" })
    } else {
      const settingsObj: Settings = {}
      data?.forEach((item) => {
        settingsObj[item.key] = item.value
      })
      setSettings(settingsObj)
    }
    setIsLoading(false)
  }

  const handleSave = async (key: string, value: string) => {
    setIsSaving(true)
    const supabase = createClient()

    const { error } = await supabase
      .from("site_settings")
      .upsert({ key, value, updated_at: new Date().toISOString() }, { onConflict: "key" })

    if (error) {
      toast({ title: "Erro ao salvar configuração", description: error.message, variant: "destructive" })
    } else {
      toast({ title: "Configuração salva com sucesso!" })
      loadSettings()
    }
    setIsSaving(false)
  }

  const handleChange = (key: string, value: string) => {
    setSettings((prev) => ({ ...prev, [key]: value }))
  }

  if (isLoading) {
    return <div className="text-center py-8">Carregando configurações...</div>
  }

  return (
    <div className="space-y-6">
      {/* Contact Information */}
      <Card>
        <CardHeader>
          <CardTitle>Informações de Contato</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="phone">Telefone</Label>
            <div className="flex gap-2">
              <Input
                id="phone"
                value={settings.phone || ""}
                onChange={(e) => handleChange("phone", e.target.value)}
                placeholder="(64) 3674-1234"
              />
              <Button onClick={() => handleSave("phone", settings.phone)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">E-mail</Label>
            <div className="flex gap-2">
              <Input
                id="email"
                type="email"
                value={settings.email || ""}
                onChange={(e) => handleChange("email", e.target.value)}
                placeholder="contato@unipora.edu.br"
              />
              <Button onClick={() => handleSave("email", settings.email)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="address">Endereço</Label>
            <div className="flex gap-2">
              <Textarea
                id="address"
                value={settings.address || ""}
                onChange={(e) => handleChange("address", e.target.value)}
                placeholder="Av. Principal, 1000 - Centro, Iporá - GO"
                rows={2}
              />
              <Button onClick={() => handleSave("address", settings.address)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Social Media Links */}
      <Card>
        <CardHeader>
          <CardTitle>Redes Sociais</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="instagram_url">Instagram</Label>
            <div className="flex gap-2">
              <Input
                id="instagram_url"
                value={settings.instagram_url || ""}
                onChange={(e) => handleChange("instagram_url", e.target.value)}
                placeholder="https://instagram.com/unipora"
              />
              <Button onClick={() => handleSave("instagram_url", settings.instagram_url)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="facebook_url">Facebook</Label>
            <div className="flex gap-2">
              <Input
                id="facebook_url"
                value={settings.facebook_url || ""}
                onChange={(e) => handleChange("facebook_url", e.target.value)}
                placeholder="https://facebook.com/unipora"
              />
              <Button onClick={() => handleSave("facebook_url", settings.facebook_url)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="youtube_url">YouTube</Label>
            <div className="flex gap-2">
              <Input
                id="youtube_url"
                value={settings.youtube_url || ""}
                onChange={(e) => handleChange("youtube_url", e.target.value)}
                placeholder="https://youtube.com/@unipora"
              />
              <Button onClick={() => handleSave("youtube_url", settings.youtube_url)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Maps */}
      <Card>
        <CardHeader>
          <CardTitle>Mapa do Google</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="maps_embed_url">URL de Embed do Google Maps</Label>
            <div className="flex gap-2">
              <Textarea
                id="maps_embed_url"
                value={settings.maps_embed_url || ""}
                onChange={(e) => handleChange("maps_embed_url", e.target.value)}
                placeholder="https://www.google.com/maps/embed?pb=..."
                rows={3}
              />
              <Button onClick={() => handleSave("maps_embed_url", settings.maps_embed_url)} disabled={isSaving}>
                <Save className="h-4 w-4" />
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">
              Acesse Google Maps, clique em "Compartilhar" → "Incorporar mapa" e cole o URL aqui
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
