import { useEffect } from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
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 { Slider } from "@/components/ui/slider";
import { useAdaptiveSettings, useUpdateAdaptiveSettings } from "@/hooks/queries/useAdaptiveEngine";
import { toast } from "sonner";

const schema = z.object({
  difficulty_step_up_threshold: z.number().min(0).max(100),
  difficulty_step_down_threshold: z.number().min(0).max(100),
  micro_lesson_trigger: z.number().min(0).max(50),
  module_skip_threshold: z.number().min(0).max(100),
  no_progress_alert_days: z.number().min(1).max(90),
  max_retries_per_exercise: z.number().min(0).max(20),
});

type FormValues = z.infer<typeof schema>;

const defaults: FormValues = {
  difficulty_step_up_threshold: 85,
  difficulty_step_down_threshold: 50,
  micro_lesson_trigger: 2,
  module_skip_threshold: 95,
  no_progress_alert_days: 3,
  max_retries_per_exercise: 3,
};

export default function AdaptiveSettings() {
  const { data, isLoading } = useAdaptiveSettings();
  const update = useUpdateAdaptiveSettings();

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: defaults,
  });

  useEffect(() => {
    if (data) {
      form.reset({
        difficulty_step_up_threshold: data.difficulty_step_up_threshold,
        difficulty_step_down_threshold: data.difficulty_step_down_threshold,
        micro_lesson_trigger: data.micro_lesson_trigger,
        module_skip_threshold: data.module_skip_threshold,
        no_progress_alert_days: data.no_progress_alert_days,
        max_retries_per_exercise: data.max_retries_per_exercise,
      });
    }
  }, [data, form]);

  const onSubmit = (values: FormValues) => {
    update.mutate(values, {
      onSuccess: () => toast.success("Settings saved."),
      onError: (e) => toast.error(e instanceof Error ? e.message : "Save failed"),
    });
  };

  if (isLoading && !data) {
    return <div className="p-6 text-muted-foreground">Loading settings…</div>;
  }

  return (
    <div className="space-y-6 p-6 max-w-xl mx-auto">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Adaptive thresholds</h1>
        <p className="text-muted-foreground text-sm mt-1">Tune pacing and escalation</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Engine parameters</CardTitle>
          <CardDescription>Sliders use whole percentages unless noted</CardDescription>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              <FormField
                control={form.control}
                name="difficulty_step_up_threshold"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Difficulty step-up threshold ({field.value}%)</FormLabel>
                    <FormControl>
                      <Slider
                        min={0}
                        max={100}
                        step={1}
                        value={[field.value]}
                        onValueChange={(v) => field.onChange(v[0])}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="difficulty_step_down_threshold"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Difficulty step-down threshold ({field.value}%)</FormLabel>
                    <FormControl>
                      <Slider
                        min={0}
                        max={100}
                        step={1}
                        value={[field.value]}
                        onValueChange={(v) => field.onChange(v[0])}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="micro_lesson_trigger"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Micro-lesson trigger</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        {...field}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="module_skip_threshold"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Module skip threshold ({field.value}%)</FormLabel>
                    <FormControl>
                      <Slider
                        min={0}
                        max={100}
                        step={1}
                        value={[field.value]}
                        onValueChange={(v) => field.onChange(v[0])}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="no_progress_alert_days"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>No-progress alert (days)</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        {...field}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="max_retries_per_exercise"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Max retries per exercise</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        {...field}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button type="submit" disabled={update.isPending}>
                Save Settings
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}
