import { useMemo, useState } from "react";
import { CheckCircle2, Filter, MessageSquare, ThumbsDown, ThumbsUp } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import {
  useAIFeedbackList,
  useResolveAIFeedback,
} from "@/hooks/queries/useAIFeedback";
import type {
  AIFeedback,
  AIFeedbackStatus,
  AIFeedbackSubjectType,
} from "@/types/ai-feedback";

const STATUS_COLORS: Record<AIFeedbackStatus, string> = {
  open: "bg-amber-100 text-amber-900 border-amber-300",
  acknowledged: "bg-sky-100 text-sky-900 border-sky-300",
  fixed: "bg-emerald-100 text-emerald-900 border-emerald-300",
  dismissed: "bg-slate-100 text-slate-700 border-slate-300",
};

type ResolveChoice = Exclude<AIFeedbackStatus, "open">;

function ResolveDialog({
  feedback,
  onClose,
}: {
  feedback: AIFeedback | null;
  onClose: () => void;
}) {
  const resolve = useResolveAIFeedback();
  const [status, setStatus] = useState<ResolveChoice>("acknowledged");
  const [notes, setNotes] = useState("");

  const open = !!feedback;

  return (
    <Dialog open={open} onOpenChange={(v) => (!v ? onClose() : null)}>
      <DialogContent
        className="max-w-lg"
        description="Triage this feedback by setting its status and leaving a short note for the audit trail."
      >
        <DialogHeader>
          <DialogTitle>Resolve feedback</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div className="space-y-1">
            <div className="text-muted-foreground text-xs uppercase">
              Status
            </div>
            <Select
              value={status}
              onValueChange={(v) => setStatus(v as ResolveChoice)}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="acknowledged">Acknowledged</SelectItem>
                <SelectItem value="fixed">Fixed</SelectItem>
                <SelectItem value="dismissed">Dismissed</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <div className="text-muted-foreground text-xs uppercase">
              Notes
            </div>
            <Textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={4}
              placeholder="What did you do? (optional)"
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button
            onClick={async () => {
              if (!feedback) return;
              try {
                await resolve.mutateAsync({
                  id: feedback.id,
                  status,
                  notes,
                });
                toast.success(`Marked ${status}`);
                setNotes("");
                onClose();
              } catch (err) {
                toast.error(
                  err instanceof Error ? err.message : "Resolve failed",
                );
              }
            }}
            disabled={resolve.isPending}
          >
            <CheckCircle2 className="mr-1 h-4 w-4" />
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default function AIFeedbackTriage() {
  const [statusFilter, setStatusFilter] = useState<AIFeedbackStatus | "all">("open");
  const [ratingFilter, setRatingFilter] = useState<"up" | "down" | "all">("down");
  const [subjectFilter, setSubjectFilter] = useState<
    AIFeedbackSubjectType | "all"
  >("all");
  const [selected, setSelected] = useState<AIFeedback | null>(null);

  const params = useMemo(
    () => ({
      status: statusFilter === "all" ? undefined : statusFilter,
      rating: ratingFilter === "all" ? undefined : ratingFilter,
      subject_type: subjectFilter === "all" ? undefined : subjectFilter,
      page: 0,
      size: 50,
    }),
    [statusFilter, ratingFilter, subjectFilter],
  );
  const { data, isLoading } = useAIFeedbackList(params);
  const items: AIFeedback[] = data?.items ?? [];

  return (
    <div className="mx-auto max-w-7xl space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          <MessageSquare className="mr-1 inline h-5 w-5" />
          AI feedback triage
        </h1>
        <p className="text-muted-foreground mt-1 text-sm">
          Student thumbs up/down on AI output — use this to catch broken
          prompts, bad questions, and low-quality coach replies.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>
            <Filter className="mr-1 inline h-4 w-4" />
            Filters
          </CardTitle>
          <CardDescription>
            Default view surfaces open thumbs-down reports, which are usually
            the most actionable.
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-3">
          <div className="space-y-1">
            <div className="text-muted-foreground text-xs uppercase">
              Status
            </div>
            <Select
              value={statusFilter}
              onValueChange={(v) =>
                setStatusFilter(v as AIFeedbackStatus | "all")
              }
            >
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="open">Open</SelectItem>
                <SelectItem value="acknowledged">Acknowledged</SelectItem>
                <SelectItem value="fixed">Fixed</SelectItem>
                <SelectItem value="dismissed">Dismissed</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1">
            <div className="text-muted-foreground text-xs uppercase">
              Rating
            </div>
            <Select
              value={ratingFilter}
              onValueChange={(v) => setRatingFilter(v as "up" | "down" | "all")}
            >
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="down">Thumbs down</SelectItem>
                <SelectItem value="up">Thumbs up</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1">
            <div className="text-muted-foreground text-xs uppercase">
              Type
            </div>
            <Select
              value={subjectFilter}
              onValueChange={(v) =>
                setSubjectFilter(v as AIFeedbackSubjectType | "all")
              }
            >
              <SelectTrigger className="w-44">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="question">Exam question</SelectItem>
                <SelectItem value="coach">Coach reply</SelectItem>
                <SelectItem value="explanation">Explanation</SelectItem>
                <SelectItem value="translation">Translation</SelectItem>
                <SelectItem value="narrative">Report narrative</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Feedback ({data?.total ?? 0})</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <Skeleton className="h-40 w-full" />
          ) : items.length === 0 ? (
            <p className="text-muted-foreground text-sm">
              No feedback matches the current filters.
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>When</TableHead>
                  <TableHead>User</TableHead>
                  <TableHead>Subject</TableHead>
                  <TableHead>Rating</TableHead>
                  <TableHead>Prompt</TableHead>
                  <TableHead>Comment</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((f) => (
                  <TableRow key={f.id}>
                    <TableCell className="text-muted-foreground text-xs whitespace-nowrap">
                      {f.create_date
                        ? new Date(f.create_date).toLocaleString()
                        : "—"}
                    </TableCell>
                    <TableCell className="text-sm">{f.user_name}</TableCell>
                    <TableCell className="font-mono text-xs">
                      {f.subject_key}
                    </TableCell>
                    <TableCell>
                      {f.rating === "up" ? (
                        <Badge className="bg-emerald-500 text-white hover:bg-emerald-500">
                          <ThumbsUp className="mr-1 h-3 w-3" />
                          Up
                        </Badge>
                      ) : (
                        <Badge className="bg-rose-500 text-white hover:bg-rose-500">
                          <ThumbsDown className="mr-1 h-3 w-3" />
                          Down
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell className="font-mono text-xs">
                      {f.prompt_key
                        ? `${f.prompt_key} v${f.prompt_version ?? "?"}`
                        : "—"}
                    </TableCell>
                    <TableCell className="max-w-md text-sm">
                      {f.comment || <span className="text-muted-foreground">—</span>}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant="outline"
                        className={STATUS_COLORS[f.status]}
                      >
                        {f.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      {f.status === "open" ? (
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => setSelected(f)}
                        >
                          Resolve
                        </Button>
                      ) : (
                        <span className="text-muted-foreground text-xs">
                          {f.resolution_notes || "—"}
                        </span>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <ResolveDialog feedback={selected} onClose={() => setSelected(null)} />
    </div>
  );
}
