"use client"

import { useState, useEffect } from "react"
import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { createBrowserClient } from "@/lib/supabase/client"
import { Plus, Copy, QrCode, Trash2, RefreshCw, Link2, Check } from "lucide-react"
import QRCode from "qrcode"

interface ReferralCode {
  id: string
  code: string
  name: string
  description: string | null
  is_active: boolean
  uses_count: number
  created_at: string
}

export function ReferralCodesManager() {
  const [referralCodes, setReferralCodes] = useState<ReferralCode[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showQRDialog, setShowQRDialog] = useState(false)
  const [selectedCode, setSelectedCode] = useState<ReferralCode | null>(null)
  const [qrCodeDataUrl, setQrCodeDataUrl] = useState("")
  const [copiedCode, setCopiedCode] = useState<string | null>(null)

  const [newCode, setNewCode] = useState({
    code: "",
    name: "",
    description: "",
  })

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

  async function loadReferralCodes() {
    setLoading(true)
    const supabase = createBrowserClient()

    const { data, error } = await supabase.from("referral_codes").select("*").order("created_at", { ascending: false })

    if (error) {
      console.error("[v0] Error loading referral codes:", error)
    } else {
      setReferralCodes(data || [])
    }

    setLoading(false)
  }

  function generateRandomCode() {
    const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
    let code = ""
    for (let i = 0; i < 8; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    setNewCode((prev) => ({ ...prev, code }))
  }

  async function createReferralCode() {
    if (!newCode.code || !newCode.name) {
      alert("Preencha o código e o nome")
      return
    }

    const supabase = createBrowserClient()

    const { error } = await supabase.from("referral_codes").insert({
      code: newCode.code.toUpperCase(),
      name: newCode.name,
      description: newCode.description || null,
      is_active: true,
      uses_count: 0,
    })

    if (error) {
      console.error("[v0] Error creating referral code:", error)
      alert("Erro ao criar código. Verifique se o código já existe.")
    } else {
      setShowCreateDialog(false)
      setNewCode({ code: "", name: "", description: "" })
      loadReferralCodes()
    }
  }

  async function toggleActive(id: string, currentStatus: boolean) {
    const supabase = createBrowserClient()

    const { error } = await supabase
      .from("referral_codes")
      .update({ is_active: !currentStatus, updated_at: new Date().toISOString() })
      .eq("id", id)

    if (error) {
      console.error("[v0] Error updating status:", error)
      alert("Erro ao atualizar status")
    } else {
      loadReferralCodes()
    }
  }

  async function deleteCode(id: string) {
    if (!confirm("Tem certeza que deseja excluir este código?")) {
      return
    }

    const supabase = createBrowserClient()

    const { error } = await supabase.from("referral_codes").delete().eq("id", id)

    if (error) {
      console.error("[v0] Error deleting code:", error)
      alert("Erro ao excluir código")
    } else {
      loadReferralCodes()
    }
  }

  function getReferralUrl(code: string) {
    if (typeof window !== "undefined") {
      return `${window.location.origin}/matricula?ref=${code}`
    }
    return ""
  }

  async function copyToClipboard(text: string, code: string) {
    try {
      await navigator.clipboard.writeText(text)
      setCopiedCode(code)
      setTimeout(() => setCopiedCode(null), 2000)
    } catch (err) {
      console.error("[v0] Failed to copy:", err)
    }
  }

  async function generateQRCode(code: ReferralCode) {
    const url = getReferralUrl(code.code)
    try {
      const qrDataUrl = await QRCode.toDataURL(url, {
        width: 400,
        margin: 2,
        color: {
          dark: "#000000",
          light: "#FFFFFF",
        },
      })
      setQrCodeDataUrl(qrDataUrl)
      setSelectedCode(code)
      setShowQRDialog(true)
    } catch (err) {
      console.error("[v0] Error generating QR code:", err)
    }
  }

  function downloadQRCode() {
    if (!qrCodeDataUrl || !selectedCode) return

    const link = document.createElement("a")
    link.href = qrCodeDataUrl
    link.download = `qrcode-${selectedCode.code}.png`
    link.click()
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">Códigos de Indicação</h2>
          <p className="text-muted-foreground">Gerencie códigos de referral para rastreamento de matrículas</p>
        </div>
        <div className="flex gap-2">
          <Button onClick={loadReferralCodes} variant="outline" size="icon">
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          </Button>
          <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Novo Código
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Criar Código de Indicação</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="code">Código *</Label>
                  <div className="flex gap-2">
                    <Input
                      id="code"
                      value={newCode.code}
                      onChange={(e) => setNewCode({ ...newCode, code: e.target.value.toUpperCase() })}
                      placeholder="Ex: AMIGO2024"
                      maxLength={20}
                    />
                    <Button type="button" variant="outline" onClick={generateRandomCode}>
                      Gerar
                    </Button>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="name">Nome *</Label>
                  <Input
                    id="name"
                    value={newCode.name}
                    onChange={(e) => setNewCode({ ...newCode, name: e.target.value })}
                    placeholder="Ex: Campanha Amigos 2024"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="description">Descrição (opcional)</Label>
                  <Textarea
                    id="description"
                    value={newCode.description}
                    onChange={(e) => setNewCode({ ...newCode, description: e.target.value })}
                    placeholder="Descrição do código..."
                    rows={3}
                  />
                </div>
                <Button onClick={createReferralCode} className="w-full">
                  Criar Código
                </Button>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Total de Códigos</div>
          <div className="text-2xl font-bold">{referralCodes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Códigos Ativos</div>
          <div className="text-2xl font-bold">{referralCodes.filter((c) => c.is_active).length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Total de Usos</div>
          <div className="text-2xl font-bold">{referralCodes.reduce((sum, c) => sum + c.uses_count, 0)}</div>
        </Card>
      </div>

      {/* Table */}
      <Card>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Código</TableHead>
                <TableHead>Nome</TableHead>
                <TableHead>Usos</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8">
                    Carregando...
                  </TableCell>
                </TableRow>
              ) : referralCodes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                    Nenhum código cadastrado
                  </TableCell>
                </TableRow>
              ) : (
                referralCodes.map((code) => (
                  <TableRow key={code.id}>
                    <TableCell className="font-mono font-bold">{code.code}</TableCell>
                    <TableCell>
                      <div>
                        <div className="font-medium">{code.name}</div>
                        {code.description && <div className="text-sm text-muted-foreground">{code.description}</div>}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{code.uses_count} usos</Badge>
                    </TableCell>
                    <TableCell>
                      <Switch checked={code.is_active} onCheckedChange={() => toggleActive(code.id, code.is_active)} />
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => copyToClipboard(getReferralUrl(code.code), code.code)}
                          title="Copiar URL"
                        >
                          {copiedCode === code.code ? (
                            <Check className="h-4 w-4 text-green-600" />
                          ) : (
                            <Link2 className="h-4 w-4" />
                          )}
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => copyToClipboard(code.code, `code-${code.code}`)}
                          title="Copiar código"
                        >
                          {copiedCode === `code-${code.code}` ? (
                            <Check className="h-4 w-4 text-green-600" />
                          ) : (
                            <Copy className="h-4 w-4" />
                          )}
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => generateQRCode(code)} title="Gerar QR Code">
                          <QrCode className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => deleteCode(code.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* QR Code Dialog */}
      <Dialog open={showQRDialog} onOpenChange={setShowQRDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>QR Code - {selectedCode?.code}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="flex justify-center p-6 bg-white rounded-lg">
              {qrCodeDataUrl && (
                <img src={qrCodeDataUrl || "/placeholder.svg"} alt="QR Code" className="w-full max-w-sm" />
              )}
            </div>
            <div className="space-y-2">
              <Label>URL de Indicação</Label>
              <div className="flex gap-2">
                <Input value={selectedCode ? getReferralUrl(selectedCode.code) : ""} readOnly />
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() =>
                    selectedCode && copyToClipboard(getReferralUrl(selectedCode.code), `dialog-${selectedCode.code}`)
                  }
                >
                  {copiedCode === `dialog-${selectedCode?.code}` ? (
                    <Check className="h-4 w-4 text-green-600" />
                  ) : (
                    <Copy className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            <Button onClick={downloadQRCode} className="w-full">
              Baixar QR Code
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
