"use client"

import { useState, useEffect } from "react"
import { createBrowserClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Search, Eye, Trash2, Loader2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"

interface Referral {
  id: string
  your_name: string
  your_email: string
  your_phone: string
  friend_name: string
  friend_email: string
  friend_phone: string
  message: string | null
  status: string
  created_at: string
}

export function ReferralsManager() {
  const { toast } = useToast()
  const [referrals, setReferrals] = useState<Referral[]>([])
  const [filteredReferrals, setFilteredReferrals] = useState<Referral[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [selectedReferral, setSelectedReferral] = useState<Referral | null>(null)
  const [isDetailOpen, setIsDetailOpen] = useState(false)

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

  useEffect(() => {
    filterReferrals()
  }, [referrals, searchTerm, statusFilter])

  const fetchReferrals = async () => {
    try {
      const supabase = createBrowserClient()
      const { data, error } = await supabase.from("referrals").select("*").order("created_at", { ascending: false })

      if (error) throw error
      setReferrals(data || [])
    } catch (error) {
      toast({
        title: "Erro ao carregar",
        description: "Não foi possível carregar as indicações.",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }

  const filterReferrals = () => {
    let filtered = referrals

    if (statusFilter !== "all") {
      filtered = filtered.filter((ref) => ref.status === statusFilter)
    }

    if (searchTerm) {
      filtered = filtered.filter(
        (ref) =>
          ref.your_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          ref.friend_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          ref.your_email.toLowerCase().includes(searchTerm.toLowerCase()) ||
          ref.friend_email.toLowerCase().includes(searchTerm.toLowerCase()),
      )
    }

    setFilteredReferrals(filtered)
  }

  const handleStatusChange = async (id: string, newStatus: string) => {
    try {
      const supabase = createBrowserClient()
      const { error } = await supabase
        .from("referrals")
        .update({ status: newStatus, updated_at: new Date().toISOString() })
        .eq("id", id)

      if (error) throw error

      setReferrals((prev) => prev.map((ref) => (ref.id === id ? { ...ref, status: newStatus } : ref)))

      toast({
        title: "Status atualizado",
        description: "O status da indicação foi atualizado com sucesso.",
      })
    } catch (error) {
      toast({
        title: "Erro ao atualizar",
        description: "Não foi possível atualizar o status.",
        variant: "destructive",
      })
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm("Tem certeza que deseja excluir esta indicação?")) return

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

      if (error) throw error

      setReferrals((prev) => prev.filter((ref) => ref.id !== id))

      toast({
        title: "Indicação excluída",
        description: "A indicação foi removida com sucesso.",
      })
    } catch (error) {
      toast({
        title: "Erro ao excluir",
        description: "Não foi possível excluir a indicação.",
        variant: "destructive",
      })
    }
  }

  const getStatusBadge = (status: string) => {
    const variants: Record<string, "default" | "secondary" | "destructive"> = {
      pending: "secondary",
      contacted: "default",
      converted: "default",
    }

    const labels: Record<string, string> = {
      pending: "Pendente",
      contacted: "Contatado",
      converted: "Convertido",
    }

    return <Badge variant={variants[status] || "default"}>{labels[status] || status}</Badge>
  }

  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>Gerenciar Indicações de Amigos</CardTitle>
          <CardDescription>Visualize e gerencie todas as indicações recebidas</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4 mb-6">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Buscar por nome ou e-mail..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="pending">Pendente</SelectItem>
                <SelectItem value="contacted">Contatado</SelectItem>
                <SelectItem value="converted">Convertido</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Indicado Por</TableHead>
                  <TableHead>Amigo</TableHead>
                  <TableHead>Contato Amigo</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Data</TableHead>
                  <TableHead className="text-right">Ações</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredReferrals.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                      Nenhuma indicação encontrada
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredReferrals.map((referral) => (
                    <TableRow key={referral.id}>
                      <TableCell>
                        <div>
                          <div className="font-medium">{referral.your_name}</div>
                          <div className="text-sm text-muted-foreground">{referral.your_email}</div>
                        </div>
                      </TableCell>
                      <TableCell>{referral.friend_name}</TableCell>
                      <TableCell>
                        <div>
                          <div className="text-sm">{referral.friend_email}</div>
                          <div className="text-sm text-muted-foreground">{referral.friend_phone}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Select
                          value={referral.status}
                          onValueChange={(value) => handleStatusChange(referral.id, value)}
                        >
                          <SelectTrigger className="w-[130px]">{getStatusBadge(referral.status)}</SelectTrigger>
                          <SelectContent>
                            <SelectItem value="pending">Pendente</SelectItem>
                            <SelectItem value="contacted">Contatado</SelectItem>
                            <SelectItem value="converted">Convertido</SelectItem>
                          </SelectContent>
                        </Select>
                      </TableCell>
                      <TableCell>{new Date(referral.created_at).toLocaleDateString("pt-BR")}</TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setSelectedReferral(referral)
                              setIsDetailOpen(true)
                            }}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => handleDelete(referral.id)}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={isDetailOpen} onOpenChange={setIsDetailOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Detalhes da Indicação</DialogTitle>
          </DialogHeader>
          {selectedReferral && (
            <div className="space-y-4">
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <h3 className="font-semibold mb-2">Dados de Quem Indicou</h3>
                  <div className="space-y-1 text-sm">
                    <p>
                      <strong>Nome:</strong> {selectedReferral.your_name}
                    </p>
                    <p>
                      <strong>E-mail:</strong> {selectedReferral.your_email}
                    </p>
                    <p>
                      <strong>Telefone:</strong> {selectedReferral.your_phone}
                    </p>
                  </div>
                </div>
                <div>
                  <h3 className="font-semibold mb-2">Dados do Amigo</h3>
                  <div className="space-y-1 text-sm">
                    <p>
                      <strong>Nome:</strong> {selectedReferral.friend_name}
                    </p>
                    <p>
                      <strong>E-mail:</strong> {selectedReferral.friend_email}
                    </p>
                    <p>
                      <strong>Telefone:</strong> {selectedReferral.friend_phone}
                    </p>
                  </div>
                </div>
              </div>
              {selectedReferral.message && (
                <div>
                  <h3 className="font-semibold mb-2">Mensagem</h3>
                  <p className="text-sm text-muted-foreground">{selectedReferral.message}</p>
                </div>
              )}
              <div>
                <p className="text-sm text-muted-foreground">
                  Data da indicação: {new Date(selectedReferral.created_at).toLocaleString("pt-BR")}
                </p>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  )
}
