"use client"

import { useEffect, useState } from "react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
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((err) => console.error("Failed to fetch tickets:", err))
      .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-foreground mb-1">Support</h1>
          <p className="text-sm text-muted-foreground">Submit and track support requests</p>
        </div>
        <button
          onClick={() => setShowForm(!showForm)}
          className="bg-primary hover:bg-primary/80 text-foreground text-sm px-4 py-2 rounded-lg transition-all"
        >
          {showForm ? "Cancel" : "New Ticket"}
        </button>
      </div>

      {/* Submit form */}
      {showForm && (
        <form onSubmit={handleSubmit} className="bg-card border border-border rounded-xl p-5 mb-6 space-y-4">
          <div>
            <label className="block text-sm text-muted-foreground mb-1">Title</label>
            <input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full bg-muted border border-border rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none focus:border-primary/50"
              placeholder="Brief summary of the issue"
              required
            />
          </div>

          <div>
            <label className="block text-sm text-muted-foreground mb-1">Description</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={4}
              className="w-full bg-muted border border-border rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none focus:border-primary/50 resize-none"
              placeholder="Detailed description of your issue"
              required
            />
          </div>

          <div>
            <label className="block text-sm text-muted-foreground mb-1">Severity</label>
            <Select value={severity} onValueChange={setSeverity}>
              <SelectTrigger className="w-full bg-muted">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="low">Low</SelectItem>
                <SelectItem value="medium">Medium</SelectItem>
                <SelectItem value="high">High</SelectItem>
                <SelectItem value="critical">Critical</SelectItem>
              </SelectContent>
            </Select>
          </div>

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

          <button
            type="submit"
            disabled={submitting}
            className="flex items-center gap-2 bg-primary hover:bg-primary/80 text-foreground 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-primary border-t-transparent rounded-full animate-spin" />
        </div>
      ) : tickets.length === 0 ? (
        <div className="text-center py-16">
          <LifeBuoy className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
          <p className="text-sm text-muted-foreground">No support tickets yet</p>
        </div>
      ) : (
        <div className="space-y-2">
          {(tickets || []).map((t) => (
            <div key={t.id} className="bg-card border border-border rounded-xl p-4">
              <div className="flex items-center justify-between mb-1">
                <h3 className="text-foreground 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-muted-foreground line-clamp-2">{t.description}</p>
              <div className="flex items-center justify-between mt-2">
                <span className="text-[10px] text-muted-foreground">
                  {new Date(t.created_at).toLocaleDateString()}
                </span>
              </div>
              {t.resolution_notes && (
                <div className="mt-2 text-xs text-muted-foreground bg-muted rounded-lg px-3 py-2">
                  <span className="text-muted-foreground">Resolution: </span>{t.resolution_notes}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
