import { useState } from "react";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { FileUploader } from "@/components/common/FileUploader";
import { toast } from "sonner";
import type { ReportCategory } from "@/types";
import type { UploadedFile } from "@/lib/upload";
import { reportsService } from "@/services/api/reports";
import { useAuthStore } from "@/store/auth";
import { useNavigate } from "@tanstack/react-router";

const CATEGORIES: { value: ReportCategory; label: string }[] = [
  { value: "cheating", label: "Cheating" },
  { value: "toxic", label: "Toxic behavior" },
  { value: "voice_abuse", label: "Voice abuse" },
  { value: "text_abuse", label: "Text abuse" },
  { value: "griefing", label: "Griefing" },
  { value: "team_kill", label: "Team killing" },
  { value: "bug_exploit", label: "Bug exploitation" },
  { value: "advertising", label: "Advertising" },
  { value: "impersonation", label: "Impersonation" },
  { value: "scamming", label: "Scamming" },
  { value: "inappropriate_profile", label: "Inappropriate profile" },
  { value: "other", label: "Other" },
];

export function ReportDialog({
  playerId, playerName, serverId, matchId, relatedMessage, trigger,
}: {
  playerId: string; playerName: string; serverId?: string; matchId?: string; relatedMessage?: string;
  trigger: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const [category, setCategory] = useState<ReportCategory>("cheating");
  const [description, setDescription] = useState("");
  const [incidentAt, setIncidentAt] = useState(new Date().toISOString().slice(0, 16));
  const [linkStr, setLinkStr] = useState("");
  const [files, setFiles] = useState<UploadedFile[]>([]);
  const [confirm, setConfirm] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const user = useAuthStore((s) => s.user);
  const navigate = useNavigate();

  async function submit() {
    if (!user) { toast.error("Please sign in"); return; }
    if (description.trim().length < 15) { toast.error("Please describe the incident (15+ chars)"); return; }
    if (!confirm) { toast.error("Confirm the report is truthful"); return; }
    if (reportsService.isRateLimited()) { toast.error("Please wait a moment before submitting another report"); return; }
    const dup = await reportsService.findDuplicate(user.id, playerId);
    if (dup) { toast.warning("You already have an open report on this player"); }
    setSubmitting(true);
    try {
      const r = await reportsService.submit({
        reporterId: user.id, reportedPlayerId: playerId, reportedPlayerName: playerName,
        category, serverId, matchId, incidentAt, description,
        evidenceLinks: linkStr.split(",").map((s) => s.trim()).filter(Boolean),
        attachments: files, relatedMessage,
      });
      toast.success("Report submitted");
      setOpen(false);
      navigate({ to: "/account/reports" });
      void r;
    } catch { toast.error("Failed to submit report"); } finally { setSubmitting(false); }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent className="max-w-lg">
        <DialogHeader><DialogTitle>Report {playerName}</DialogTitle></DialogHeader>
        <div className="space-y-3">
          <div><Label>Category<span className="text-destructive"> *</span></Label>
            <Select value={category} onValueChange={(v) => setCategory(v as ReportCategory)}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>{CATEGORIES.map((c) => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
            </Select>
          </div>
          <div><Label>Incident date & time</Label><Input type="datetime-local" value={incidentAt} onChange={(e) => setIncidentAt(e.target.value)} /></div>
          {relatedMessage && <div className="rounded-md border border-border bg-surface/60 p-2 text-xs">Related message: “{relatedMessage}”</div>}
          <div><Label>Description<span className="text-destructive"> *</span></Label><Textarea rows={5} value={description} onChange={(e) => setDescription(e.target.value)} placeholder="What happened, and when. Include round numbers, timestamps, other players involved…" /></div>
          <div><Label>Evidence links</Label><Input value={linkStr} onChange={(e) => setLinkStr(e.target.value)} placeholder="Comma-separated URLs (demos, videos, screenshots)" /></div>
          <div><Label>Attachments</Label><FileUploader files={files} onChange={setFiles} /></div>
          <label className="flex items-start gap-2 text-xs text-muted-foreground"><Checkbox checked={confirm} onCheckedChange={(v) => setConfirm(v === true)} className="mt-0.5" /> I confirm this report is truthful. False reports may result in punishment.</label>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
          <Button onClick={submit} disabled={submitting} className="gradient-primary text-primary-foreground">{submitting ? "Submitting…" : "Submit report"}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}