"use client"

import { useEffect, useState } from "react"
import { LifeBuoy, Send } from "lucide-react"

interface Ticket {
  id: string
  title: string
  description: string
  severity: string
  status: string
  created_at: string
  resolution_notes: string
}

export default function ClientSupport() {
  const [tickets, setTickets] = useState<Ticket[]>([])
  const [loading, setLoading] = useState(true)
  const [title, setTitle] = useState("")
  const [description, setDescription] = useState("")
  const [severity, setSeverity] = useState("medium")
  const [submitting, setSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState("")
  const [showForm, setShowForm] = useState(false)

  const loadTickets = () => {
    setLoading(true)
    fetch("/client-portal/api/support", { credentials: "include" })
      .then((r) => r.json())
      .then((d) => setTickets(d.tickets || []))
      .catch(() => {})
      .finally(() => setLoading(false))
  }

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    setSubmitError("")

    try {
      const res = await fetch("/client-portal/api/support", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, description, severity }),
      })

      if (!res.ok) {
        const data = await res.json()
        setSubmitError(data.error || "Failed to submit")
        return
      }

      setTitle("")
      setDescription("")
      setSeverity("medium")
      setShowForm(false)
      loadTickets()
    } catch {
      setSubmitError("Connection error")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-white mb-1">Support</h1>
          <p className="text-sm text-[#6a6a75]">Submit and track support requests</p>
        </div>
        <button
          onClick={() => setShowForm(!showForm)}
          className="bg-[#1BB0CE] hover:bg-[#1BB0CE]/80 text-white text-sm px-4 py-2 rounded-lg transition-all"
        >
          {showForm ? "Cancel" : "New Ticket"}
        </button>
      </div>

      {/* Submit form */}
      {showForm && (
        <form onSubmit={handleSubmit} className="bg-[#0d1117] border border-[#1a1a24] rounded-xl p-5 mb-6 space-y-4">
          <div>
            <label className="block text-sm text-[#8a8a95] mb-1">Title</label>
            <input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-white placeholder-[#6a6a75] outline-none focus:border-[#1BB0CE]/50"
              placeholder="Brief summary of the issue"
              required
            />
          </div>

          <div>
            <label className="block text-sm text-[#8a8a95] mb-1">Description</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={4}
              className="w-full bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-white placeholder-[#6a6a75] outline-none focus:border-[#1BB0CE]/50 resize-none"
              placeholder="Detailed description of your issue"
              required
            />
          </div>

          <div>
            <label className="block text-sm text-[#8a8a95] mb-1">Severity</label>
            <select
              value={severity}
              onChange={(e) => setSeverity(e.target.value)}
              className="w-full bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-white outline-none focus:border-[#1BB0CE]/50"
            >
              <option value="low">Low</option>
              <option value="medium">Medium</option>
              <option value="high">High</option>
              <option value="critical">Critical</option>
            </select>
          </div>

          {submitError && (
            <div className="text-xs text-red-400 bg-red-400/5 border border-red-400/10 rounded-lg px-3 py-2">
              {submitError}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting}
            className="flex items-center gap-2 bg-[#1BB0CE] hover:bg-[#1BB0CE]/80 text-white text-sm px-4 py-2 rounded-lg transition-all disabled:opacity-40"
          >
            <Send className="h-3.5 w-3.5" />
            {submitting ? "Submitting..." : "Submit Ticket"}
          </button>
        </form>
      )}

      {/* Tickets list */}
      {loading ? (
        <div className="flex items-center justify-center h-32">
          <div className="w-6 h-6 border-2 border-[#1BB0CE] border-t-transparent rounded-full animate-spin" />
        </div>
      ) : tickets.length === 0 ? (
        <div className="text-center py-16">
          <LifeBuoy className="h-10 w-10 text-[#2a2a35] mx-auto mb-3" />
          <p className="text-sm text-[#6a6a75]">No support tickets yet</p>
        </div>
      ) : (
        <div className="space-y-2">
          {tickets.map((t) => (
            <div key={t.id} className="bg-[#0d1117] border border-[#1a1a24] rounded-xl p-4">
              <div className="flex items-center justify-between mb-1">
                <h3 className="text-white text-sm font-medium">{t.title}</h3>
                <div className="flex gap-2">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded ${
                    t.severity === "critical" ? "bg-red-500/10 text-red-400" :
                    t.severity === "high" ? "bg-orange-500/10 text-orange-400" :
                    t.severity === "medium" ? "bg-amber-500/10 text-amber-400" :
                    "bg-zinc-500/10 text-zinc-400"
                  }`}>
                    {t.severity}
                  </span>
                  <span className={`text-[10px] px-1.5 py-0.5 rounded ${
                    t.status === "closed" ? "bg-emerald-500/10 text-emerald-400" :
                    t.status === "resolved" ? "bg-blue-500/10 text-blue-400" :
                    t.status === "in_progress" ? "bg-amber-500/10 text-amber-400" :
                    "bg-zinc-500/10 text-zinc-400"
                  }`}>
                    {t.status.replace("_", " ")}
                  </span>
                </div>
              </div>
              <p className="text-sm text-[#8a8a95] line-clamp-2">{t.description}</p>
              <div className="flex items-center justify-between mt-2">
                <span className="text-[10px] text-[#6a6a75]">
                  {new Date(t.created_at).toLocaleDateString()}
                </span>
              </div>
              {t.resolution_notes && (
                <div className="mt-2 text-xs text-[#6a6a75] bg-[#1a1a24] rounded-lg px-3 py-2">
                  <span className="text-[#8a8a95]">Resolution: </span>{t.resolution_notes}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
