import { useState, useId } from "react";
import { useForm, useFieldArray, useWatch, type Control, type UseFormReturn } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useNavigate } from "react-router-dom";
import { ChevronDown, ChevronUp, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Slider } from "@/components/ui/slider";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useCreateCustomExam, useSaveAsTemplate } from "@/hooks/queries/useExamTemplates";
import { useSubjects } from "@/hooks/queries/useAdaptive";
import type { CustomExamCreateRequest, CustomScoringMethod } from "@/types";
import { toast } from "sonner";

const sectionSchema = z.object({
  title: z.string().min(1),
  skill: z.string().optional(),
  question_count: z.coerce.number().min(1),
  time_limit_min: z.coerce.number().optional(),
  scoring_method: z.enum(["auto", "rubric", "mixed"]),
  sequence: z.number(),
  question_ids: z.array(z.number()),
});

const formSchema = z.object({
  title: z.string().min(2),
  subject_id: z.coerce.number().min(1),
  description: z.string().optional(),
  total_time_min: z.coerce.number().min(1),
  pass_threshold: z.coerce.number().min(0).max(100),
  results_release_mode: z.enum(["auto", "manual_approval"]),
  randomize: z.boolean(),
  sections: z.array(sectionSchema).min(1),
  save_as_template: z.boolean(),
  template_name: z.string().optional(),
});

type FormValues = z.infer<typeof formSchema>;

const SKILL_OPTIONS = ["Reading", "Listening", "Writing", "Speaking", "Mixed"];

export default function CustomExamCreate() {
  const navigate = useNavigate();
  const [step, setStep] = useState(1);
  const subjectsQ = useSubjects();
  const createExam = useCreateCustomExam();
  const saveTemplate = useSaveAsTemplate();

  const subjects = subjectsQ.data ?? [];

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: "",
      subject_id: 0,
      description: "",
      total_time_min: 60,
      pass_threshold: 50,
      results_release_mode: "auto",
      randomize: false,
      sections: [
        {
          title: "Section A",
          skill: "Reading",
          question_count: 10,
          time_limit_min: 20,
          scoring_method: "auto",
          sequence: 0,
          question_ids: [],
        },
      ],
      save_as_template: false,
      template_name: "",
    },
  });

  const { fields, append, remove, move } = useFieldArray({ control: form.control, name: "sections" });

  const validateStep = async (s: number) => {
    if (s === 1) {
      return form.trigger(["title", "subject_id", "total_time_min", "pass_threshold", "results_release_mode", "randomize"]);
    }
    if (s === 2) {
      return form.trigger("sections");
    }
    if (s === 3) {
      return form.trigger("sections");
    }
    return true;
  };

  const next = async () => {
    const ok = await validateStep(step);
    if (ok) setStep((x) => Math.min(4, x + 1));
  };

  const back = () => setStep((x) => Math.max(1, x - 1));

  const buildPayload = (): CustomExamCreateRequest => {
    const v = form.getValues();
    return {
      title: v.title,
      subject_id: v.subject_id,
      description: v.description,
      total_time_min: v.total_time_min,
      pass_threshold: v.pass_threshold,
      results_release_mode: v.results_release_mode,
      randomize: v.randomize,
      sections: v.sections.map((sec, i) => ({
        title: sec.title,
        skill: sec.skill,
        question_count: sec.question_count,
        time_limit_min: sec.time_limit_min,
        scoring_method: sec.scoring_method as CustomScoringMethod,
        sequence: i,
        question_ids: sec.question_ids,
      })),
    };
  };

  const onSaveDraft = async () => {
    try {
      const payload = buildPayload();
      await createExam.mutateAsync(payload);
      toast.success("Draft saved.");
    } catch {
      toast.error("Could not save.");
    }
  };

  const onPublish = async () => {
    try {
      const payload = buildPayload();
      const res = await createExam.mutateAsync(payload);
      const raw = res as { exam_id?: number; data?: { exam_id?: number } };
      const id = raw.exam_id ?? raw.data?.exam_id;
      if (form.getValues("save_as_template")) {
        const name = form.getValues("template_name")?.trim() || form.getValues("title");
        await saveTemplate.mutateAsync({
          name,
          structure: { sections: buildPayload().sections },
          editable: true,
          type: "custom",
        });
      }
      toast.success("Exam published.");
      if (id != null) navigate(`/admin/exam`);
    } catch {
      toast.error("Publish failed.");
    }
  };

  return (
    <div className="p-6 max-w-3xl mx-auto space-y-8">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Custom exam</h1>
        <p className="text-muted-foreground mt-1">Build sections, attach questions, then review.</p>
      </div>

      <div className="flex gap-2">
        {[1, 2, 3, 4].map((n) => (
          <button
            key={n}
            type="button"
            onClick={() => setStep(n)}
            className={`flex-1 rounded-md border px-2 py-2 text-sm ${
              step === n ? "border-primary bg-primary/5 font-medium" : "border-muted text-muted-foreground"
            }`}
          >
            {n === 1 && "Properties"}
            {n === 2 && "Sections"}
            {n === 3 && "Questions"}
            {n === 4 && "Review"}
          </button>
        ))}
      </div>

      <Form {...form}>
        <form className="space-y-6">
          {step === 1 ? (
            <Card>
              <CardHeader>
                <CardTitle>Properties</CardTitle>
                <CardDescription>Basics and scoring policy.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <FormField
                  control={form.control}
                  name="title"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Title</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="subject_id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Subject</FormLabel>
                      <Select
                        onValueChange={(v) => field.onChange(Number(v))}
                        value={field.value ? String(field.value) : ""}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Select subject" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {subjects.map((s) => (
                            <SelectItem key={s.id} value={String(s.id)}>
                              {s.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description</FormLabel>
                      <FormControl>
                        <Textarea rows={3} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="total_time_min"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Total time (minutes)</FormLabel>
                      <FormControl>
                        <Input type="number" min={1} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="pass_threshold"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Pass threshold ({field.value}%)</FormLabel>
                      <FormControl>
                        <Slider
                          min={0}
                          max={100}
                          step={1}
                          value={[field.value]}
                          onValueChange={(v) => field.onChange(v[0] ?? 0)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="results_release_mode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Score release</FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="auto">Automatic</SelectItem>
                          <SelectItem value="manual_approval">Manual approval</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="randomize"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div>
                        <FormLabel>Randomize</FormLabel>
                        <FormDescription>Shuffle questions where allowed.</FormDescription>
                      </div>
                      <FormControl>
                        <Switch checked={field.value} onCheckedChange={field.onChange} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
          ) : null}

          {step === 2 ? (
            <Card>
              <CardHeader className="flex flex-row items-center justify-between gap-4">
                <div>
                  <CardTitle>Section builder</CardTitle>
                  <CardDescription>Add, remove, and order sections.</CardDescription>
                </div>
                <Button
                  type="button"
                  size="sm"
                  onClick={() =>
                    append({
                      title: `Section ${fields.length + 1}`,
                      skill: "Reading",
                      question_count: 5,
                      time_limit_min: 15,
                      scoring_method: "auto",
                      sequence: fields.length,
                      question_ids: [],
                    })
                  }
                >
                  <Plus className="h-4 w-4 mr-1" />
                  Add section
                </Button>
              </CardHeader>
              <CardContent className="space-y-4">
                {fields.map((f, index) => (
                  <div key={f.id} className="rounded-lg border p-4 space-y-3">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="text-sm font-medium">Section {index + 1}</span>
                      <div className="flex gap-1">
                        <Button type="button" size="icon" variant="outline" disabled={index === 0} onClick={() => move(index, index - 1)}>
                          <ChevronUp className="h-4 w-4" />
                        </Button>
                        <Button
                          type="button"
                          size="icon"
                          variant="outline"
                          disabled={index === fields.length - 1}
                          onClick={() => move(index, index + 1)}
                        >
                          <ChevronDown className="h-4 w-4" />
                        </Button>
                        <Button type="button" size="icon" variant="ghost" onClick={() => remove(index)}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </div>
                    <FormField
                      control={form.control}
                      name={`sections.${index}.title`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Title</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name={`sections.${index}.skill`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Skill</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value ?? ""}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {SKILL_OPTIONS.map((sk) => (
                                <SelectItem key={sk} value={sk}>
                                  {sk}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <div className="grid gap-3 sm:grid-cols-2">
                      <FormField
                        control={form.control}
                        name={`sections.${index}.question_count`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Question count</FormLabel>
                            <FormControl>
                              <Input type="number" min={1} {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`sections.${index}.time_limit_min`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Time limit (min)</FormLabel>
                            <FormControl>
                              <Input type="number" min={1} {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={form.control}
                      name={`sections.${index}.scoring_method`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Scoring method</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="auto">Auto</SelectItem>
                              <SelectItem value="rubric">Rubric</SelectItem>
                              <SelectItem value="mixed">Mixed</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                ))}
              </CardContent>
            </Card>
          ) : null}

          {step === 3 ? (
            <Card>
              <CardHeader>
                <CardTitle>Question assignment</CardTitle>
                <CardDescription>Attach pool items or create new ones per section.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {fields.map((f, index) => (
                  <div key={f.id} className="rounded-lg border p-4 space-y-3">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="font-medium">{form.watch(`sections.${index}.title`)}</span>
                      <SectionQuestionCount control={form.control} index={index} />
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Button type="button" variant="secondary" size="sm" onClick={() => navigate("/admin/resources")}>
                        Browse content pool
                      </Button>
                    </div>
                    <NewQuestionInline sectionIndex={index} form={form} />
                  </div>
                ))}
              </CardContent>
            </Card>
          ) : null}

          {step === 4 ? (
            <Card>
              <CardHeader>
                <CardTitle>Review & publish</CardTitle>
                <CardDescription>Confirm details before students see this exam.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <ScrollArea className="h-48 rounded-md border p-3 text-sm">
                  <pre className="whitespace-pre-wrap font-sans">{JSON.stringify(buildPayload(), null, 2)}</pre>
                </ScrollArea>
                <FormField
                  control={form.control}
                  name="save_as_template"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                      <FormControl>
                        <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                      </FormControl>
                      <div className="space-y-1 leading-none">
                        <FormLabel>Save as reusable template</FormLabel>
                        <FormDescription>Stores section layout for future exams.</FormDescription>
                      </div>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="template_name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Template name</FormLabel>
                      <FormControl>
                        <Input placeholder="Optional; defaults to exam title" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
          ) : null}

          <Separator />

          <div className="flex flex-wrap justify-between gap-3">
            <Button type="button" variant="outline" onClick={back} disabled={step === 1}>
              Back
            </Button>
            <div className="flex flex-wrap gap-2">
              {step < 4 ? (
                <Button type="button" onClick={next}>
                  Next
                </Button>
              ) : (
                <>
                  <Button type="button" variant="secondary" onClick={onSaveDraft}>
                    Save draft
                  </Button>
                  <Button type="button" onClick={onPublish} disabled={createExam.isPending || saveTemplate.isPending}>
                    Publish
                  </Button>
                </>
              )}
            </div>
          </div>
        </form>
      </Form>
    </div>
  );
}

function SectionQuestionCount({ control, index }: { control: Control<FormValues>; index: number }) {
  const ids = useWatch({ control, name: `sections.${index}.question_ids` });
  const target = useWatch({ control, name: `sections.${index}.question_count` });
  const n = ids?.length ?? 0;
  const t = typeof target === "number" ? target : Number(target) || 0;
  return (
    <span className="text-sm text-muted-foreground">
      {n}/{t} selected
    </span>
  );
}

function NewQuestionInline({ sectionIndex, form }: { sectionIndex: number; form: UseFormReturn<FormValues> }) {
  const [stem, setStem] = useState("");
  const baseId = useId();
  return (
    <div className="space-y-2 rounded-md bg-muted/40 p-3">
      <Label htmlFor={`${baseId}-stem`}>Create new question</Label>
      <Input
        id={`${baseId}-stem`}
        value={stem}
        onChange={(e) => setStem(e.target.value)}
        placeholder="Stem or reference label"
      />
      <Button
        type="button"
        size="sm"
        disabled={!stem.trim()}
        onClick={async () => {
          if (!stem.trim()) return;
          try {
            const res = await fetch("/api/exam/questions/quick-create", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("encoach_token")}`,
              },
              body: JSON.stringify({ stem: stem.trim(), question_type: "short_answer", skill: form.getValues(`sections.${sectionIndex}.skill`) || "reading" }),
            });
            const data = await res.json();
            const qId = data?.question_id;
            if (qId) {
              const cur = form.getValues(`sections.${sectionIndex}.question_ids`) ?? [];
              form.setValue(`sections.${sectionIndex}.question_ids`, [...cur, qId]);
            }
          } catch {
            // fallback: still add with a placeholder notice
          }
          setStem("");
        }}
      >
        Add to section
      </Button>
    </div>
  );
}
