"use client"

import type React from "react"

import { useState } from "react"
import Link from "next/link"
import { ChevronLeft, Plus, MessageSquare, Clock, CheckCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { BottomNav } from "@/components/bottom-nav"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"
import { formatDistanceToNow } from "date-fns"
import { fr } from "date-fns/locale"

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

export default function SupportPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const { data, mutate } = useSWR(user?.id ? `/api/support?userId=${user.id}` : null, fetcher)

  const [isOpen, setIsOpen] = useState(false)
  const [subject, setSubject] = useState("")
  const [category, setCategory] = useState("technical")
  const [priority, setPriority] = useState("medium")
  const [message, setMessage] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const tickets = data?.tickets || []

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!user?.id) return

    setIsSubmitting(true)
    try {
      const res = await fetch("/api/support", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          subject,
          category,
          priority,
          message,
        }),
      })

      if (res.ok) {
        toast({ title: "Ticket créé avec succès" })
        setIsOpen(false)
        setSubject("")
        setMessage("")
        mutate()
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de créer le ticket", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

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

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-2xl px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/settings" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <div>
              <h1 className="text-xl font-bold text-foreground">Support</h1>
              <p className="text-sm text-muted-foreground">Vos tickets d'assistance</p>
            </div>
          </div>

          <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger asChild>
              <Button className="bg-purple-600 hover:bg-purple-700">
                <Plus className="w-4 h-4 mr-2" />
                Nouveau ticket
              </Button>
            </DialogTrigger>
            <DialogContent className="bg-zinc-900 border-zinc-800">
              <DialogHeader>
                <DialogTitle className="text-white">Créer un ticket</DialogTitle>
                <DialogDescription className="text-zinc-400">
                  Décrivez votre problème, nous vous répondrons rapidement
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <Input
                    placeholder="Sujet"
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                    required
                    className="bg-zinc-800 border-zinc-700 text-white"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <Select value={category} onValueChange={setCategory}>
                    <SelectTrigger className="bg-zinc-800 border-zinc-700 text-white">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-zinc-800 border-zinc-700">
                      <SelectItem value="technical">Technique</SelectItem>
                      <SelectItem value="billing">Facturation</SelectItem>
                      <SelectItem value="content">Contenu</SelectItem>
                      <SelectItem value="account">Compte</SelectItem>
                      <SelectItem value="other">Autre</SelectItem>
                    </SelectContent>
                  </Select>
                  <Select value={priority} onValueChange={setPriority}>
                    <SelectTrigger className="bg-zinc-800 border-zinc-700 text-white">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-zinc-800 border-zinc-700">
                      <SelectItem value="low">Basse</SelectItem>
                      <SelectItem value="medium">Moyenne</SelectItem>
                      <SelectItem value="high">Haute</SelectItem>
                      <SelectItem value="urgent">Urgente</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Textarea
                    placeholder="Décrivez votre problème..."
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    required
                    rows={5}
                    className="bg-zinc-800 border-zinc-700 text-white"
                  />
                </div>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsOpen(false)}
                    className="flex-1 border-zinc-700"
                  >
                    Annuler
                  </Button>
                  <Button type="submit" disabled={isSubmitting} className="flex-1 bg-purple-600 hover:bg-purple-700">
                    {isSubmitting ? "Création..." : "Créer"}
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Tickets List */}
        <div className="space-y-3">
          {tickets.length > 0 ? (
            tickets.map((ticket: any) => (
              <Link key={ticket.id} href={`/support/${ticket.id}`}>
                <div className="p-4 rounded-xl border border-secondary/50 bg-secondary/30 hover:bg-secondary/50 transition-colors">
                  <div className="flex items-start justify-between mb-2">
                    <h3 className="font-semibold text-foreground">{ticket.subject}</h3>
                    {getStatusBadge(ticket.status)}
                  </div>
                  <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                    {ticket.last_message || "Aucun message"}
                  </p>
                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <span>
                      {formatDistanceToNow(new Date(ticket.created_at), {
                        addSuffix: true,
                        locale: fr,
                      })}
                    </span>
                    <span>{ticket.message_count || 0} message(s)</span>
                  </div>
                </div>
              </Link>
            ))
          ) : (
            <div className="text-center py-12">
              <MessageSquare className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
              <h3 className="text-lg font-semibold text-foreground mb-2">Aucun ticket</h3>
              <p className="text-sm text-muted-foreground mb-4">Créez un ticket si vous avez besoin d'aide</p>
              <Button onClick={() => setIsOpen(true)} className="bg-purple-600 hover:bg-purple-700">
                <Plus className="w-4 h-4 mr-2" />
                Créer un ticket
              </Button>
            </div>
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
