"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { ArrowLeft, Plus, MessageCircle, Clock, CheckCircle, XCircle } from "lucide-react"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"

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

export default function ArtistSupportPage() {
  const router = useRouter()
  const { user, isAuthenticated, isLoading } = useAuth()
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [formData, setFormData] = useState({
    subject: "",
    category: "technical",
    priority: "medium",
    message: "",
  })

  const { data: tickets, mutate } = useSWR(user?.id ? `/api/support?userId=${user.id}` : null, fetcher)

  useEffect(() => {
    if (!isLoading && (!isAuthenticated || user?.role !== "artist")) {
      router.push("/")
    }
  }, [isAuthenticated, isLoading, user, router])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-purple-500"></div>
      </div>
    )
  }

  if (!isAuthenticated || user?.role !== "artist") {
    return null
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    const res = await fetch("/api/support", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...formData,
        userId: user.id,
        userType: "artist",
      }),
    })

    if (res.ok) {
      setShowCreateForm(false)
      setFormData({ subject: "", category: "technical", priority: "medium", message: "" })
      mutate()
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "open":
        return <MessageCircle className="w-5 h-5 text-blue-400" />
      case "pending":
        return <Clock className="w-5 h-5 text-yellow-400" />
      case "resolved":
        return <CheckCircle className="w-5 h-5 text-green-400" />
      case "closed":
        return <XCircle className="w-5 h-5 text-zinc-400" />
      default:
        return <MessageCircle className="w-5 h-5 text-zinc-400" />
    }
  }

  return (
    <div className="min-h-screen bg-zinc-950">
      <div className="max-w-4xl mx-auto p-4">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Link href="/artist" className="text-zinc-400 hover:text-white">
              <ArrowLeft className="w-6 h-6" />
            </Link>
            <div>
              <h1 className="text-2xl font-bold text-white">Support</h1>
              <p className="text-zinc-400 text-sm">Vos tickets de support</p>
            </div>
          </div>
          <Button onClick={() => setShowCreateForm(!showCreateForm)} className="bg-purple-500 hover:bg-purple-600">
            <Plus className="w-4 h-4 mr-2" />
            Nouveau ticket
          </Button>
        </div>

        {/* Create Form */}
        {showCreateForm && (
          <Card className="p-6 mb-6 bg-zinc-900 border-zinc-800">
            <h2 className="text-xl font-semibold text-white mb-4">Créer un ticket</h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="text-sm text-zinc-400 mb-2 block">Sujet</label>
                <input
                  type="text"
                  value={formData.subject}
                  onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                  className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-4 py-2 text-white"
                  required
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-zinc-400 mb-2 block">Catégorie</label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-4 py-2 text-white"
                  >
                    <option value="technical">Technique</option>
                    <option value="billing">Facturation</option>
                    <option value="content">Contenu</option>
                    <option value="account">Compte</option>
                    <option value="other">Autre</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-zinc-400 mb-2 block">Priorité</label>
                  <select
                    value={formData.priority}
                    onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                    className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-4 py-2 text-white"
                  >
                    <option value="low">Basse</option>
                    <option value="medium">Moyenne</option>
                    <option value="high">Haute</option>
                    <option value="urgent">Urgente</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="text-sm text-zinc-400 mb-2 block">Message</label>
                <textarea
                  value={formData.message}
                  onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                  className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-4 py-2 text-white min-h-32"
                  required
                />
              </div>
              <div className="flex gap-2">
                <Button type="submit" className="bg-purple-500 hover:bg-purple-600">
                  Créer le ticket
                </Button>
                <Button
                  type="button"
                  onClick={() => setShowCreateForm(false)}
                  className="bg-zinc-800 hover:bg-zinc-700"
                >
                  Annuler
                </Button>
              </div>
            </form>
          </Card>
        )}

        {/* Tickets List */}
        <div className="space-y-3">
          {tickets?.tickets?.length === 0 ? (
            <div className="text-center py-12">
              <MessageCircle className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
              <p className="text-zinc-400">Aucun ticket de support</p>
            </div>
          ) : (
            tickets?.tickets?.map((ticket: any) => (
              <Link key={ticket.id} href={`/support/${ticket.id}`}>
                <Card className="p-4 bg-zinc-900 border-zinc-800 hover:border-purple-500/50 transition-colors cursor-pointer">
                  <div className="flex items-start gap-4">
                    {getStatusIcon(ticket.status)}
                    <div className="flex-1 min-w-0">
                      <h3 className="text-white font-medium mb-1">{ticket.subject}</h3>
                      <div className="flex items-center gap-3 text-xs text-zinc-400">
                        <span className="capitalize">{ticket.category}</span>
                        <span>•</span>
                        <span className="capitalize">{ticket.priority}</span>
                        <span>•</span>
                        <span className="capitalize">{ticket.status}</span>
                        <span>•</span>
                        <span>
                          {new Date(ticket.created_at).toLocaleDateString("fr-FR", {
                            day: "numeric",
                            month: "short",
                          })}
                        </span>
                      </div>
                    </div>
                  </div>
                </Card>
              </Link>
            ))
          )}
        </div>
      </div>
    </div>
  )
}
