"use client"

import type React from "react"
import { useState } from "react"
import {
  Search,
  MoreHorizontal,
  MessageSquare,
  Clock,
  CheckCircle,
  Send,
  Loader2,
  ArrowLeft,
  AlertCircle,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import useSWR from "swr"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/components/auth-provider"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

export default function AdminSupportPage() {
  const { user } = useAuth()
  const { data, isLoading, error, mutate } = useSWR("/api/admin/support", fetcher)
  const { toast } = useToast()

  const [selectedTicket, setSelectedTicket] = useState<any | null>(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [priorityFilter, setPriorityFilter] = useState("all")
  const [replyMessage, setReplyMessage] = useState("")
  const [isSending, setIsSending] = useState(false)

  const { data: ticketData, mutate: mutateTicket } = useSWR(
    selectedTicket ? `/api/admin/support/${selectedTicket.id}` : null,
    fetcher,
  )

  const tickets = data?.tickets || []
  const messages = ticketData?.messages || []

  const filteredTickets = tickets.filter((ticket: any) => {
    const matchesSearch =
      ticket.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
      ticket.user.name.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || ticket.status === statusFilter
    const matchesPriority = priorityFilter === "all" || ticket.priority === priorityFilter
    return matchesSearch && matchesStatus && matchesPriority
  })

  const getStatusBadge = (status: string) => {
    const statuses: Record<string, { color: string; label: string; icon: React.ReactNode }> = {
      open: { color: "bg-blue-500/20 text-blue-400", label: "Ouvert", icon: <MessageSquare className="w-3 h-3" /> },
      in_progress: {
        color: "bg-yellow-500/20 text-yellow-400",
        label: "En cours",
        icon: <AlertCircle className="w-3 h-3" />,
      },
      waiting: { color: "bg-orange-500/20 text-orange-400", label: "En attente", icon: <Clock className="w-3 h-3" /> },
      resolved: {
        color: "bg-green-500/20 text-green-400",
        label: "Résolu",
        icon: <CheckCircle className="w-3 h-3" />,
      },
      closed: { color: "bg-zinc-500/20 text-zinc-400", label: "Fermé", icon: <CheckCircle className="w-3 h-3" /> },
    }
    const s = statuses[status] || { color: "bg-zinc-500/20 text-zinc-400", label: status, icon: null }
    return (
      <Badge className={`${s.color} border-0 flex items-center gap-1`}>
        {s.icon}
        {s.label}
      </Badge>
    )
  }

  const getPriorityBadge = (priority: string) => {
    const priorities: Record<string, { color: string; label: string }> = {
      urgent: { color: "bg-red-500/20 text-red-400", label: "Urgent" },
      high: { color: "bg-orange-500/20 text-orange-400", label: "Haute" },
      medium: { color: "bg-yellow-500/20 text-yellow-400", label: "Moyenne" },
      low: { color: "bg-zinc-500/20 text-zinc-400", label: "Basse" },
    }
    const p = priorities[priority] || { color: "bg-zinc-500/20 text-zinc-400", label: priority }
    return <Badge className={`${p.color} border-0`}>{p.label}</Badge>
  }

  const handleUpdateStatus = async (ticketId: string, newStatus: string) => {
    try {
      const res = await fetch("/api/admin/support", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: ticketId, status: newStatus }),
      })

      if (res.ok) {
        toast({ title: "Statut mis à jour" })
        mutate()
        if (selectedTicket?.id === ticketId) {
          setSelectedTicket({ ...selectedTicket, status: newStatus })
        }
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de mettre à jour le statut", variant: "destructive" })
    }
  }

  const handleSendReply = async () => {
    if (!replyMessage.trim() || !selectedTicket || !user?.id) return

    setIsSending(true)
    try {
      const res = await fetch(`/api/admin/support/${selectedTicket.id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          message: replyMessage.trim(),
        }),
      })

      if (res.ok) {
        toast({ title: "Réponse envoyée" })
        setReplyMessage("")
        mutateTicket()
        mutate()
      } else {
        throw new Error("Failed to send reply")
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible d'envoyer la réponse", variant: "destructive" })
    } finally {
      setIsSending(false)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-red-400">Erreur lors du chargement des données</p>
      </div>
    )
  }

  return (
    <div className="flex h-[calc(100vh-8rem)] gap-4">
      {/* Tickets List */}
      <div className={`flex flex-col ${selectedTicket ? "hidden md:flex md:w-96" : "flex-1"}`}>
        <div className="space-y-4 mb-4">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-white">Support</h1>
            <Badge className="bg-red-500/20 text-red-400 border-0">
              {tickets.filter((t: any) => t.status === "open").length} ouverts
            </Badge>
          </div>

          <div className="flex gap-2">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
              <Input
                placeholder="Rechercher..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32 bg-zinc-800/50 border-zinc-700 text-white">
                <SelectValue placeholder="Statut" />
              </SelectTrigger>
              <SelectContent className="bg-zinc-800 border-zinc-700">
                <SelectItem value="all">Tous</SelectItem>
                <SelectItem value="open">Ouverts</SelectItem>
                <SelectItem value="in_progress">En cours</SelectItem>
                <SelectItem value="waiting">En attente</SelectItem>
                <SelectItem value="resolved">Résolus</SelectItem>
                <SelectItem value="closed">Fermés</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="flex-1 overflow-auto space-y-2">
          {filteredTickets.length > 0 ? (
            filteredTickets.map((ticket: any) => (
              <div
                key={ticket.id}
                onClick={() => setSelectedTicket(ticket)}
                className={`p-4 rounded-lg border cursor-pointer transition-colors ${
                  selectedTicket?.id === ticket.id
                    ? "bg-purple-500/20 border-purple-500/50"
                    : "bg-zinc-800/30 border-zinc-700/50 hover:bg-zinc-800/50"
                }`}
              >
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={ticket.user.avatar || "/placeholder.svg"} />
                      <AvatarFallback>{ticket.user.name[0]}</AvatarFallback>
                    </Avatar>
                    <div>
                      <p className="text-sm font-medium text-white">{ticket.user.name}</p>
                      <p className="text-xs text-zinc-400">{ticket.id.slice(0, 8)}</p>
                    </div>
                  </div>
                  {getPriorityBadge(ticket.priority)}
                </div>
                <p className="text-white font-medium mb-2">{ticket.subject}</p>
                <div className="flex items-center justify-between">
                  {getStatusBadge(ticket.status)}
                  <span className="text-xs text-zinc-400">{ticket.lastReply}</span>
                </div>
              </div>
            ))
          ) : (
            <div className="p-8 text-center text-zinc-400">Aucun ticket trouvé</div>
          )}
        </div>
      </div>

      {/* Conversation View */}
      {selectedTicket && (
        <div className="flex-1 flex flex-col bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
          {/* Header */}
          <div className="p-4 border-b border-zinc-700/50 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Button
                variant="ghost"
                size="icon"
                className="md:hidden text-zinc-400"
                onClick={() => setSelectedTicket(null)}
              >
                <ArrowLeft className="w-5 h-5" />
              </Button>
              <Avatar>
                <AvatarImage src={selectedTicket.user.avatar || "/placeholder.svg"} />
                <AvatarFallback>{selectedTicket.user.name[0]}</AvatarFallback>
              </Avatar>
              <div>
                <p className="font-medium text-white">{selectedTicket.subject}</p>
                <p className="text-sm text-zinc-400">
                  {selectedTicket.user.name} - {selectedTicket.user.email}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {getStatusBadge(selectedTicket.status)}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" className="text-zinc-400">
                    <MoreHorizontal className="w-5 h-5" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                  <DropdownMenuItem
                    onClick={() => handleUpdateStatus(selectedTicket.id, "in_progress")}
                    className="text-zinc-300"
                  >
                    Marquer en cours
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleUpdateStatus(selectedTicket.id, "waiting")}
                    className="text-zinc-300"
                  >
                    Marquer en attente
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleUpdateStatus(selectedTicket.id, "resolved")}
                    className="text-zinc-300"
                  >
                    Marquer comme résolu
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleUpdateStatus(selectedTicket.id, "closed")}
                    className="text-red-400"
                  >
                    Fermer le ticket
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>

          <div className="flex-1 overflow-auto p-4 space-y-4">
            {messages.length > 0 ? (
              messages.map((msg: any) => (
                <div key={msg.id} className={`flex gap-3 ${msg.is_staff_reply ? "justify-end" : ""}`}>
                  {!msg.is_staff_reply && (
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={msg.avatar_url || "/placeholder.svg"} />
                      <AvatarFallback>{msg.user_name?.[0] || "U"}</AvatarFallback>
                    </Avatar>
                  )}
                  <div className={`max-w-md ${msg.is_staff_reply ? "items-end" : ""}`}>
                    <div
                      className={`p-3 rounded-lg ${
                        msg.is_staff_reply ? "bg-purple-600 text-white" : "bg-zinc-700/50 text-white"
                      }`}
                    >
                      <p>{msg.message}</p>
                    </div>
                    <p className="text-xs text-zinc-500 mt-1">
                      {msg.user_name || "Admin"} - {new Date(msg.created_at).toLocaleString("fr-FR")}
                    </p>
                  </div>
                  {msg.is_staff_reply && (
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={msg.avatar_url || "/placeholder.svg"} />
                      <AvatarFallback>{msg.user_name?.[0] || "A"}</AvatarFallback>
                    </Avatar>
                  )}
                </div>
              ))
            ) : (
              <div className="text-center text-zinc-400 py-8">Aucun message</div>
            )}
          </div>

          {/* Reply Input */}
          <div className="p-4 border-t border-zinc-700/50">
            <div className="flex gap-2">
              <Textarea
                placeholder="Votre réponse..."
                value={replyMessage}
                onChange={(e) => setReplyMessage(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    e.preventDefault()
                    handleSendReply()
                  }
                }}
                className="bg-zinc-800 border-zinc-700 text-white min-h-10 resize-none"
                rows={2}
                disabled={isSending}
              />
              <Button
                className="bg-purple-600 hover:bg-purple-700"
                onClick={handleSendReply}
                disabled={isSending || !replyMessage.trim()}
              >
                {isSending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
