import { useEffect } from "react";
import { Link, useParams, useSearchParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useCourseDetail, useUpdateCourse, useCreateCourse } from "@/hooks/queries/useCourseGeneration";
import type { ProgressionModel } from "@/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Slider } from "@/components/ui/slider";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollArea } from "@/components/ui/scroll-area";

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

const schema = z.object({
  title: z.string().min(1),
  exam_type: z.string().optional(),
  target_band: z.coerce.number().min(0).max(9).optional(),
  target_level: z.string().optional(),
  duration_weeks: z.coerce.number().min(1),
  study_hours_week: z.coerce.number().min(1),
  skills: z.array(z.string()).min(1),
  skill_weightings: z.record(z.string(), z.number().min(0).max(100)),
  progression_model: z.enum(["linear", "parallel", "adaptive"]),
});

type FormValues = z.infer<typeof schema>;

export default function CourseConfig() {
  const { courseId: courseIdParam } = useParams();
  const courseId = Number(courseIdParam);
  const [searchParams] = useSearchParams();
  const individual = searchParams.get("path") === "individual";

  const { data: course, isLoading } = useCourseDetail(courseId);
  const updateCourse = useUpdateCourse();
  const createCourse = useCreateCourse();

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      title: "",
      exam_type: "IELTS",
      duration_weeks: 8,
      study_hours_week: 5,
      skills: ["Listening", "Reading"],
      skill_weightings: { Listening: 25, Reading: 25, Writing: 25, Speaking: 25 },
      progression_model: "adaptive",
    },
  });

  useEffect(() => {
    if (!course) return;
    const w: Record<string, number> = {};
    SKILL_OPTIONS.forEach((s) => {
      w[s] = course.skill_weightings[s] ?? 25;
    });
    form.reset({
      title: course.title,
      exam_type: course.exam_type ?? "IELTS",
      target_band: course.target_band,
      target_level: course.target_level,
      duration_weeks: course.duration_weeks,
      study_hours_week: course.study_hours_week,
      skills: course.skills?.length ? course.skills : SKILL_OPTIONS,
      skill_weightings: w,
      progression_model: course.progression_model,
    });
  }, [course, form]);

  const onSubmit = (values: FormValues) => {
    if (!Number.isFinite(courseId) || courseId <= 0) return;
    updateCourse.mutate({
      courseId,
      payload: {
        title: values.title,
        exam_type: values.exam_type,
        target_band: values.target_band,
        target_level: values.target_level,
        duration_weeks: values.duration_weeks,
        study_hours_week: values.study_hours_week,
        skills: values.skills,
        skill_weightings: values.skill_weightings,
        progression_model: values.progression_model as ProgressionModel,
      },
    });
  };

  if (isLoading) {
    return (
      <div className="p-6">
        <Skeleton className="h-10 w-64 mb-4" />
        <Skeleton className="h-96 w-full" />
      </div>
    );
  }

  if (individual) {
    return (
      <div className="mx-auto max-w-3xl space-y-6 p-6">
        <Card>
          <CardHeader>
            <CardTitle>{course?.title ?? "Course Preview"}</CardTitle>
            <CardDescription>Auto-generated course preview</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <ScrollArea className="h-64 rounded-md border p-4 text-sm">
              <p className="mb-2 font-medium">Modules</p>
              <ul className="list-inside list-disc space-y-1">
                {(course?.modules ?? []).map((m) => (
                  <li key={m.id}>
                    {m.title} · {m.estimated_hours}h · {m.skill}
                  </li>
                ))}
              </ul>
            </ScrollArea>
            <div className="flex flex-wrap gap-2">
              <Button type="button" asChild>
                <Link to={`/student/course/${course?.id ?? courseId}`}>Start Course</Link>
              </Button>
              <Button type="button" variant="outline" asChild>
                <Link to={`/admin/course/configure/${course?.id ?? courseId}?path=entity`}>Customize</Link>
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold">Configure course</h1>
        <p className="text-muted-foreground">Course #{courseId}</p>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Basics</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Course Title</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="exam_type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Exam Type</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="target_band"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Target Band</FormLabel>
                      <FormControl>
                        <Input type="number" step="0.5" {...field} value={field.value ?? ""} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="target_level"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Target Level</FormLabel>
                      <FormControl>
                        <Input {...field} value={field.value ?? ""} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <FormField
                control={form.control}
                name="duration_weeks"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Duration (weeks)</FormLabel>
                    <FormControl>
                      <Input type="number" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="study_hours_week"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Study Hours / Week</FormLabel>
                    <FormControl>
                      <Slider
                        min={1}
                        max={40}
                        step={1}
                        value={[field.value]}
                        onValueChange={(v) => field.onChange(v[0])}
                      />
                    </FormControl>
                    <p className="text-sm text-muted-foreground">{field.value} h</p>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Skills</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <FormField
                control={form.control}
                name="skills"
                render={() => (
                  <FormItem>
                    <div className="space-y-2">
                      {SKILL_OPTIONS.map((s) => (
                        <FormField
                          key={s}
                          control={form.control}
                          name="skills"
                          render={({ field }) => (
                            <FormItem className="flex items-center space-x-2 space-y-0">
                              <FormControl>
                                <Checkbox
                                  checked={field.value.includes(s)}
                                  onCheckedChange={(ck) => {
                                    const on = ck === true;
                                    if (on) field.onChange([...field.value, s]);
                                    else field.onChange(field.value.filter((x) => x !== s));
                                  }}
                                />
                              </FormControl>
                              <FormLabel className="font-normal">{s}</FormLabel>
                            </FormItem>
                          )}
                        />
                      ))}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {SKILL_OPTIONS.map((s) => (
                <FormField
                  key={s}
                  control={form.control}
                  name={`skill_weightings.${s}`}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{s} weight</FormLabel>
                      <FormControl>
                        <Slider
                          min={0}
                          max={100}
                          step={5}
                          value={[field.value ?? 0]}
                          onValueChange={(v) => field.onChange(v[0])}
                        />
                      </FormControl>
                      <p className="text-sm text-muted-foreground">{field.value ?? 0}%</p>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Progression</CardTitle>
            </CardHeader>
            <CardContent>
              <FormField
                control={form.control}
                name="progression_model"
                render={({ field }) => (
                  <FormItem className="space-y-3">
                    <FormControl>
                      <RadioGroup value={field.value} onValueChange={field.onChange} className="grid gap-3 md:grid-cols-3">
                        {(["linear", "parallel", "adaptive"] as const).map((m) => (
                          <div key={m} className="flex items-start space-x-3 rounded-lg border p-4">
                            <RadioGroupItem value={m} id={`prog-${m}`} />
                            <div className="space-y-1 leading-none">
                              <Label htmlFor={`prog-${m}`} className="font-medium capitalize">
                                {m}
                              </Label>
                              <p className="text-xs text-muted-foreground">
                                {m === "linear" && "Sequential modules"}
                                {m === "parallel" && "Multiple tracks"}
                                {m === "adaptive" && "Adjusts to performance"}
                              </p>
                            </div>
                          </div>
                        ))}
                      </RadioGroup>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          <div className="flex flex-wrap gap-2">
            <Button type="submit" disabled={updateCourse.isPending}>
              Save changes
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={() =>
                createCourse.mutate({
                  title: `${form.getValues("title")} (copy)`,
                  duration_weeks: form.getValues("duration_weeks"),
                  study_hours_week: form.getValues("study_hours_week"),
                  skills: form.getValues("skills"),
                  skill_weightings: form.getValues("skill_weightings"),
                  progression_model: form.getValues("progression_model"),
                })
              }
              disabled={createCourse.isPending}
            >
              Duplicate as new
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
