import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { PageHeader, SectionHeader } from "@/components/common/PageHeader";
import { AdminDataTable, type Column } from "@/components/common/AdminDataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { toast } from "sonner";
import { LifeBuoy, Plus } from "lucide-react";

export const Route = createFileRoute("/_public/account/support")({
  head: () => ({ meta: [
    { title: "Support — Purple Zone Account" },
    { name: "description", content: "Support tickets, help center and contact." },
  ]}),
  component: SupportPage,
});

type Ticket = { id: string; subject: string; category: string; status: "open" | "waiting" | "resolved" | "closed"; updated: string; priority: "low" | "normal" | "high" };
const seed: Ticket[] = [
  { id: "TK-3410", subject: "Purchase not credited", category: "Billing", status: "open", updated: "2h ago", priority: "high" },
  { id: "TK-3388", subject: "Skin loadout not syncing on srv-3", category: "Technical", status: "waiting", updated: "yesterday", priority: "normal" },
  { id: "TK-3255", subject: "Ban appeal question", category: "Punishments", status: "resolved", updated: "1w ago", priority: "normal" },
];
const STATUS: Record<Ticket["status"], string> = {
  open: "border-primary/40 text-primary",
  waiting: "border-warning/40 text-warning",
  resolved: "border-success/40 text-success",
  closed: "border-muted-foreground/40 text-muted-foreground",
};

function SupportPage() {
  const [tickets, setTickets] = useState<Ticket[]>(seed);
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);

  const cols: Column<Ticket>[] = [
    { key: "id", header: "Ticket", cell: (t) => <span className="font-mono text-xs">{t.id}</span> },
    { key: "s", header: "Subject", cell: (t) => <span className="font-medium">{t.subject}</span> },
    { key: "cat", header: "Category", cell: (t) => t.category },
    { key: "pri", header: "Priority", cell: (t) => <Badge variant="outline" className="capitalize">{t.priority}</Badge> },
    { key: "st", header: "Status", cell: (t) => <Badge variant="outline" className={`capitalize ${STATUS[t.status]}`}>{t.status}</Badge> },
    { key: "u", header: "Updated", cell: (t) => <span className="text-muted-foreground">{t.updated}</span> },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Support"
        description="Get help from the Purple Zone team."
        actions={
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild><Button className="gradient-primary text-primary-foreground"><Plus className="mr-1 h-4 w-4" /> New ticket</Button></DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>Open a support ticket</DialogTitle></DialogHeader>
              <div className="grid gap-3">
                <div className="space-y-1.5"><Label>Subject</Label><Input placeholder="Briefly describe the issue" /></div>
                <div className="space-y-1.5"><Label>Category</Label>
                  <Select defaultValue="Billing">
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Billing">Billing</SelectItem>
                      <SelectItem value="Technical">Technical</SelectItem>
                      <SelectItem value="Punishments">Punishments</SelectItem>
                      <SelectItem value="Other">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5"><Label>Message</Label><Textarea rows={5} placeholder="Include as many details as possible." /></div>
              </div>
              <DialogFooter>
                <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>
                <Button className="gradient-primary text-primary-foreground" onClick={() => {
                  setTickets((xs) => [{ id: `TK-${3500 + xs.length}`, subject: "New ticket", category: "Billing", status: "open", updated: "just now", priority: "normal" }, ...xs]);
                  setOpen(false); toast.success("Ticket submitted");
                }}>Submit</Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        }
      />

      <section className="grid gap-3 md:grid-cols-3">
        {[
          ["Help center", "Browse FAQs and guides"],
          ["Discord community", "Chat with staff and players"],
          ["Contact by email", "support@purplezone.gg"],
        ].map(([t, h]) => (
          <a key={t} className="rounded-xl border border-border bg-card p-4 transition-colors hover:border-primary/40">
            <div className="flex items-center gap-2 font-display text-base font-semibold"><LifeBuoy className="h-4 w-4 text-secondary" /> {t}</div>
            <div className="mt-1 text-sm text-muted-foreground">{h}</div>
          </a>
        ))}
      </section>

      <section>
        <SectionHeader title="My tickets" />
        <AdminDataTable rows={tickets.filter((t) => q === "" || t.subject.toLowerCase().includes(q.toLowerCase()) || t.id.includes(q))} columns={cols} search={q} onSearchChange={setQ} />
      </section>
    </div>
  );
}
