"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { Clock, FileText, Loader2, Send, Star } from "lucide-react";
import { toast } from "sonner";

import { reviewApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";
import { tToast } from "@/lib/utils/translated-toast";
import { cn } from "@/lib/utils/cn";
import type { Review } from "@/types";

const RECOMMENDATIONS = [
  { value: "ACCEPT", labelKey: "accept", fallback: "Accept", color: "bg-green-100 text-green-700 border-green-300" },
  { value: "MINOR_REVISION", labelKey: "minor_revision", fallback: "Minor Revision", color: "bg-yellow-100 text-yellow-700 border-yellow-300" },
  { value: "MAJOR_REVISION", labelKey: "major_revision", fallback: "Major Revision", color: "bg-orange-100 text-orange-700 border-orange-300" },
  { value: "REJECT", labelKey: "reject", fallback: "Reject", color: "bg-red-100 text-red-700 border-red-300" },
] as const;

const SCORE_FIELDS = [
  { key: "originalityScore", labelKey: "originality", fallback: "Originality" },
  { key: "methodologyScore", labelKey: "methodology", fallback: "Methodology" },
  { key: "clarityScore", labelKey: "clarity", fallback: "Clarity" },
  { key: "relevanceScore", labelKey: "relevance", fallback: "Relevance" },
  { key: "referencesScore", labelKey: "references", fallback: "References" },
] as const;

export interface ReviewFormProps {
  reviewId: string;
  review: Review | undefined;
}

/**
 * Reviewer submission form. Extracted verbatim from the former inline
 * implementation in {@code src/app/(dashboard)/reviewer/review/[id]/page.tsx}
 * as part of Phase 3c-ii. No logic changes — scoring, recommendation
 * selection, comment validation, and the submit mutation all behave
 * identically to the pre-extraction page file.
 *
 * <p>The parent page owns the {@code useQuery} for pending reviews and
 * passes the resolved {@code review} down so both this form and the
 * left-pane preview/download components read from one fetch.
 */
export function ReviewForm({ reviewId, review }: ReviewFormProps) {
  const router = useRouter();
  const { t: cms } = useTranslation(["REVIEWER", "COMMON"]);

  const [scores, setScores] = useState<Record<string, number>>({
    originalityScore: 0,
    methodologyScore: 0,
    clarityScore: 0,
    relevanceScore: 0,
    referencesScore: 0,
  });
  const [recommendation, setRecommendation] = useState("");
  const [commentsToAuthor, setCommentsToAuthor] = useState("");
  const [confidentialNotes, setConfidentialNotes] = useState("");

  const submitMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => reviewApi.submit(reviewId, data),
    onSuccess: () => {
      tToast("success", "reviewer.review_submitted", "Review submitted successfully");
      router.push("/reviewer");
    },
    onError: (err: unknown) => {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message
        ?? "Failed to submit review";
      toast.error(msg);
    },
  });

  function handleSubmit() {
    const allScoresSet = SCORE_FIELDS.every((f) => scores[f.key] >= 1 && scores[f.key] <= 10);
    if (!allScoresSet) {
      toast.error("Please rate all criteria (1-10)");
      return;
    }
    if (!recommendation) {
      toast.error("Please select a recommendation");
      return;
    }
    if (!commentsToAuthor.trim()) {
      toast.error("Please provide comments for the author");
      return;
    }

    submitMutation.mutate({
      ...scores,
      recommendation,
      commentsToAuthor,
      confidentialNotes: confidentialNotes || undefined,
    });
  }

  const inputCls =
    "w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm placeholder:text-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500";

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-900">
        {cms("REVIEWER.review_form.title", "Submit Review")}
      </h1>

      {/* Paper info */}
      {review && (
        <div className="rounded-lg bg-gray-50 border border-gray-200 p-4">
          <div className="flex items-start gap-3">
            <FileText className="h-5 w-5 text-indigo-500 mt-0.5 shrink-0" />
            <div>
              <p className="font-medium text-gray-900">
                {review.paperTitleEn || review.paperTitleHi || "Paper"}
              </p>
              {review.paperReferenceNo && (
                <p className="text-sm text-gray-500 mt-0.5">Ref: {review.paperReferenceNo}</p>
              )}
              {review.deadlineAt && (
                <p className="flex items-center gap-1 text-sm text-amber-600 mt-1">
                  <Clock className="h-3.5 w-3.5" />
                  Deadline: {new Date(review.deadlineAt).toLocaleDateString("en-IN")}
                </p>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Scores */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">
          {cms("REVIEWER.review_form.scores_heading", "Evaluation Scores")}
        </h2>
        <p className="text-sm text-gray-500 mb-4">
          {cms("REVIEWER.review_form.scores_hint", "Rate each criterion from 1 (poor) to 10 (excellent)")}
        </p>

        <div className="space-y-4">
          {SCORE_FIELDS.map((field) => (
            <div key={field.key} className="flex items-center gap-4">
              <label className="w-32 text-sm font-medium text-gray-700 shrink-0">
                {cms(`REVIEWER.review_form.${field.labelKey}`, field.fallback)}
              </label>
              <div className="flex gap-1">
                {Array.from({ length: 10 }, (_, i) => i + 1).map((n) => (
                  <button
                    key={n}
                    type="button"
                    onClick={() => setScores((prev) => ({ ...prev, [field.key]: n }))}
                    className={cn(
                      "w-8 h-8 rounded-md text-xs font-semibold transition",
                      scores[field.key] >= n
                        ? "bg-indigo-600 text-white"
                        : "bg-gray-100 text-gray-500 hover:bg-gray-200"
                    )}
                  >
                    {n}
                  </button>
                ))}
                <span className="ml-2 w-8 text-sm font-bold text-indigo-600">
                  {scores[field.key] || "—"}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Recommendation */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">
          <Star className="inline h-5 w-5 text-amber-500 mr-1" />
          {cms("REVIEWER.review_form.recommendation_heading", "Recommendation")}
        </h2>
        <div className="grid grid-cols-2 gap-3">
          {RECOMMENDATIONS.map((rec) => (
            <button
              key={rec.value}
              type="button"
              onClick={() => setRecommendation(rec.value)}
              className={cn(
                "rounded-lg border-2 px-4 py-3 text-sm font-medium transition",
                recommendation === rec.value
                  ? rec.color + " border-current"
                  : "bg-white text-gray-600 border-gray-200 hover:border-gray-300"
              )}
            >
              {cms(`REVIEWER.review_form.rec_${rec.labelKey}`, rec.fallback)}
            </button>
          ))}
        </div>
      </div>

      {/* Comments */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">
          {cms("REVIEWER.review_form.comments_heading", "Comments")}
        </h2>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {cms("REVIEWER.review_form.comments_to_author", "Comments to Author")} *
            </label>
            <textarea
              rows={5}
              className={inputCls}
              placeholder={cms("REVIEWER.review_form.comments_placeholder", "Provide constructive feedback for the author...")}
              value={commentsToAuthor}
              onChange={(e) => setCommentsToAuthor(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {cms("REVIEWER.review_form.confidential_notes", "Confidential Notes to Editor")}
              <span className="text-gray-400 font-normal ml-1">(optional)</span>
            </label>
            <textarea
              rows={3}
              className={inputCls}
              placeholder={cms("REVIEWER.review_form.notes_placeholder", "Private notes visible only to the editor...")}
              value={confidentialNotes}
              onChange={(e) => setConfidentialNotes(e.target.value)}
            />
          </div>
        </div>
      </div>

      {/* Submit */}
      <div className="flex justify-end">
        <button
          type="button"
          onClick={handleSubmit}
          disabled={submitMutation.isPending}
          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-6 py-3 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition disabled:opacity-50"
        >
          {submitMutation.isPending ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {cms("COMMON.loading", "Submitting...")}
            </>
          ) : (
            <>
              <Send className="h-4 w-4" />
              {cms("REVIEWER.review_form.submit_button", "Submit Review")}
            </>
          )}
        </button>
      </div>
    </div>
  );
}

export default ReviewForm;
