import { useNavigate } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Plus, Trash2 } from "lucide-react";

import { StepWizard, type WizardStepDef } from "@/components/wizard/StepWizard";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { examsService } from "@/services/exams.service";
import { describeApiError } from "@/lib/api-client";
import type { ExamModule, ExamStructure } from "@/types";

/**
 * Exam Structure creation wizard (4 steps).
 *
 * 1. Basics — name, industry, exam type (academic/general)
 * 2. Modules — which modules this structure covers (multi-select)
 * 3. Writing tasks — min-words per task (only if writing module selected)
 * 4. Review — summary → Finish posts to /api/exam-structures
 *
 * The backend expects `modules` as a JSON-serialisable array and `config`
 * as an arbitrary JSON object. We only populate writing-task config from
 * the wizard; listening/reading/speaking can be refined later on the
 * full structure edit page.
 */

interface WritingTaskDraft {
  type: string;
  min_words: number;
  label: string;
}

interface StructureWizardState {
  name: string;
  industry: string;
  exam_type: "academic" | "general";
  modules: ExamModule[];
  writing_tasks: WritingTaskDraft[];
}

const INITIAL: StructureWizardState = {
  name: "",
  industry: "",
  exam_type: "academic",
  modules: ["writing"],
  writing_tasks: [
    { type: "task_1", label: "Task 1", min_words: 150 },
    { type: "task_2", label: "Task 2", min_words: 250 },
  ],
};

const ALL_MODULES: ExamModule[] = ["listening", "reading", "writing", "speaking"];

export default function ExamStructureWizard() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const qc = useQueryClient();

  const createMut = useMutation({
    mutationFn: (data: Partial<ExamStructure>) =>
      examsService.createStructure(data as Partial<ExamStructure>),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["exam-structures"] });
      toast.success(t("wizard.structure.toastSuccess"));
      navigate("/admin/exam-structures");
    },
    onError: (err: unknown) => {
      toast.error(describeApiError(err, t("wizard.structure.toastError")));
    },
  });

  const steps: WizardStepDef<StructureWizardState>[] = [
    {
      id: "basics",
      titleKey: "wizard.structure.step1.title",
      descriptionKey: "wizard.structure.step1.description",
      validate: (s) => {
        if (!s.name.trim()) return t("wizard.structure.errors.nameRequired");
        return null;
      },
      render: ({ state, update }) => (
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="str-name">{t("wizard.structure.labels.name")}</Label>
            <Input
              id="str-name"
              value={state.name}
              onChange={(e) => update({ name: e.target.value })}
              placeholder={t("wizard.structure.placeholders.name")}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="str-industry">{t("wizard.structure.labels.industry")}</Label>
            <Input
              id="str-industry"
              value={state.industry}
              onChange={(e) => update({ industry: e.target.value })}
              placeholder={t("wizard.structure.placeholders.industry")}
            />
            <p className="text-xs text-muted-foreground">{t("wizard.structure.industryHint")}</p>
          </div>
          <div className="space-y-1.5">
            <Label>{t("wizard.structure.labels.examType")}</Label>
            <Select
              value={state.exam_type}
              onValueChange={(v) => update({ exam_type: v as StructureWizardState["exam_type"] })}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="academic">{t("wizard.structure.examTypes.academic")}</SelectItem>
                <SelectItem value="general">{t("wizard.structure.examTypes.general")}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      ),
    },

    {
      id: "modules",
      titleKey: "wizard.structure.step2.title",
      descriptionKey: "wizard.structure.step2.description",
      validate: (s) => {
        if (s.modules.length === 0) return t("wizard.structure.errors.moduleRequired");
        return null;
      },
      render: ({ state, update }) => (
        <div className="space-y-2">
          {ALL_MODULES.map((m) => {
            const checked = state.modules.includes(m);
            return (
              <label
                key={m}
                className="flex items-start gap-3 rounded-md border p-3 cursor-pointer hover:bg-muted/40"
              >
                <Checkbox
                  checked={checked}
                  onCheckedChange={(v) => {
                    const next = v
                      ? [...state.modules, m]
                      : state.modules.filter((x) => x !== m);
                    update({ modules: next });
                  }}
                />
                <div className="flex-1">
                  <div className="font-medium">{t(`wizard.structure.modules.${m}.title`)}</div>
                  <div className="text-xs text-muted-foreground">
                    {t(`wizard.structure.modules.${m}.description`)}
                  </div>
                </div>
              </label>
            );
          })}
        </div>
      ),
    },

    {
      id: "writing-tasks",
      titleKey: "wizard.structure.step3.title",
      descriptionKey: "wizard.structure.step3.description",
      validate: (s) => {
        if (!s.modules.includes("writing")) return null;
        if (s.writing_tasks.length === 0) {
          return t("wizard.structure.errors.writingTaskRequired");
        }
        for (const task of s.writing_tasks) {
          if (!task.label.trim()) return t("wizard.structure.errors.writingTaskLabel");
          if (task.min_words < 1) return t("wizard.structure.errors.writingTaskWords");
        }
        return null;
      },
      render: ({ state, update }) => {
        if (!state.modules.includes("writing")) {
          return (
            <p className="text-sm text-muted-foreground">
              {t("wizard.structure.writingSkipped")}
            </p>
          );
        }
        return (
          <div className="space-y-3">
            {state.writing_tasks.map((task, i) => (
              <div key={i} className="flex items-end gap-2 rounded-md border p-3">
                <div className="flex-1 space-y-1.5">
                  <Label htmlFor={`task-label-${i}`}>
                    {t("wizard.structure.labels.taskLabel")}
                  </Label>
                  <Input
                    id={`task-label-${i}`}
                    value={task.label}
                    onChange={(e) => {
                      const next = [...state.writing_tasks];
                      next[i] = { ...task, label: e.target.value };
                      update({ writing_tasks: next });
                    }}
                  />
                </div>
                <div className="w-28 space-y-1.5">
                  <Label htmlFor={`task-words-${i}`}>
                    {t("wizard.structure.labels.minWords")}
                  </Label>
                  <Input
                    id={`task-words-${i}`}
                    type="number"
                    min={1}
                    value={task.min_words}
                    onChange={(e) => {
                      const next = [...state.writing_tasks];
                      next[i] = { ...task, min_words: Number(e.target.value) || 0 };
                      update({ writing_tasks: next });
                    }}
                  />
                </div>
                <Button
                  variant="ghost"
                  size="icon"
                  aria-label={t("wizard.structure.removeTask")}
                  onClick={() => {
                    update({
                      writing_tasks: state.writing_tasks.filter((_, idx) => idx !== i),
                    });
                  }}
                  disabled={state.writing_tasks.length === 1}
                  className="text-destructive"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            ))}
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                update({
                  writing_tasks: [
                    ...state.writing_tasks,
                    {
                      type: `task_${state.writing_tasks.length + 1}`,
                      label: `Task ${state.writing_tasks.length + 1}`,
                      min_words: 250,
                    },
                  ],
                })
              }
            >
              <Plus className="mr-1 h-4 w-4" />
              {t("wizard.structure.addTask")}
            </Button>
          </div>
        );
      },
    },

    {
      id: "review",
      titleKey: "wizard.structure.step4.title",
      descriptionKey: "wizard.structure.step4.description",
      render: ({ state }) => (
        <div className="space-y-4 text-sm">
          <ReviewRow label={t("wizard.structure.labels.name")} value={state.name} />
          <ReviewRow
            label={t("wizard.structure.labels.industry")}
            value={state.industry || "—"}
          />
          <ReviewRow
            label={t("wizard.structure.labels.examType")}
            value={t(`wizard.structure.examTypes.${state.exam_type}`)}
          />
          <ReviewRow
            label={t("wizard.structure.labels.modules")}
            value={state.modules
              .map((m) => t(`wizard.structure.modules.${m}.title`))
              .join(", ")}
          />
          {state.modules.includes("writing") && (
            <div>
              <div className="font-medium mb-1">{t("wizard.structure.step3.title")}</div>
              <ul className="rounded-md border divide-y">
                {state.writing_tasks.map((task, i) => (
                  <li key={i} className="flex items-center justify-between p-2">
                    <span>{task.label}</span>
                    <span className="text-muted-foreground tabular-nums">
                      {task.min_words} {t("wizard.structure.wordsSuffix")}
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      ),
    },
  ];

  return (
    <StepWizard<StructureWizardState>
      titleKey="wizard.structure.title"
      subtitleKey="wizard.structure.subtitle"
      backTo="/admin/smart-wizard"
      steps={steps}
      initialState={INITIAL}
      submitting={createMut.isPending}
      finishLabelKey="wizard.structure.finish"
      onFinish={async (state) => {
        const config: Record<string, unknown> = {
          exam_type: state.exam_type,
        };
        if (state.modules.includes("writing")) {
          config.writing = {
            tasks: state.writing_tasks.map((t) => ({
              type: t.type,
              min_words: t.min_words,
              label: t.label,
            })),
          };
        }
        await createMut.mutateAsync({
          name: state.name.trim(),
          industry: state.industry.trim(),
          modules: state.modules,
          config,
        } as unknown as Partial<ExamStructure>);
      }}
    />
  );
}

function ReviewRow({ label, value, wrap }: { label: string; value: string; wrap?: boolean }) {
  return (
    <div className="grid grid-cols-[140px_1fr] gap-2">
      <div className="text-muted-foreground">{label}</div>
      <div className={wrap ? "whitespace-pre-wrap" : ""}>{value || "—"}</div>
    </div>
  );
}
