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 { FileUploader } from "@/components/common/FileUploader";
import { toast } from "sonner";
import type { Punishment } from "@/types";
import type { UploadedFile } from "@/lib/upload";
import { appealsService } from "@/services/api/appeals";
import { useAuthStore } from "@/store/auth";
import { useNavigate } from "@tanstack/react-router";

export function AppealDialog({ punishment, trigger }: { punishment: Punishment; trigger: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState("");
  const [explanation, setExplanation] = useState("");
  const [videoUrl, setVideoUrl] = useState("");
  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 (reason.trim().length < 3) { toast.error("Enter a reason"); return; }
    if (explanation.trim().length < 20) { toast.error("Explanation must be at least 20 characters"); return; }
    if (!confirm) { toast.error("Confirm accuracy to submit"); return; }
    const dup = await appealsService.hasOpenFor(punishment.id, user.id);
    if (dup) { toast.error("You already have an open appeal for this punishment"); return; }
    setSubmitting(true);
    try {
      const a = await appealsService.submit({
        punishmentId: punishment.id, playerId: user.id, playerName: user.name,
        reason, explanation, evidenceLinks: linkStr.split(",").map((s) => s.trim()).filter(Boolean),
        attachments: files, videoUrl: videoUrl || undefined,
      });
      toast.success("Appeal submitted");
      setOpen(false);
      navigate({ to: "/account/appeals/$id", params: { id: a.id } });
    } catch { toast.error("Failed to submit appeal"); } finally { setSubmitting(false); }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent className="max-w-lg">
        <DialogHeader><DialogTitle>Appeal punishment #{punishment.id}</DialogTitle></DialogHeader>
        <div className="space-y-3">
          <div className="rounded-md border border-border bg-surface/60 p-3 text-xs">
            <div><span className="text-muted-foreground">Type:</span> {punishment.type} · <span className="text-muted-foreground">Reason:</span> {punishment.reason}</div>
            <div><span className="text-muted-foreground">Admin:</span> {punishment.admin} · <span className="text-muted-foreground">Duration:</span> {punishment.duration}</div>
          </div>
          <div><Label>Reason<span className="text-destructive"> *</span></Label><Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Short summary" /></div>
          <div><Label>Detailed explanation<span className="text-destructive"> *</span></Label><Textarea rows={5} value={explanation} onChange={(e) => setExplanation(e.target.value)} placeholder="Provide context, timestamps, other players involved…" /></div>
          <div><Label>Evidence links</Label><Input value={linkStr} onChange={(e) => setLinkStr(e.target.value)} placeholder="Comma-separated URLs" /></div>
          <div><Label>Video URL</Label><Input value={videoUrl} onChange={(e) => setVideoUrl(e.target.value)} placeholder="https://youtu.be/…" /></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 appeal is truthful and accurate.</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 appeal"}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}