import type { PendingAttachment, StepAttachment } from "@/components/teacher/StepAttachmentsEditor";

export interface AssignmentEditPayload {
  id: number;
  title: string;
  instructions?: string | null;
  max_score?: number | string | null;
  category?: string | null;
}

export type StepType = "content" | "submit" | "auto_complete" | "quiz";
export type OutputFormat = "text" | "voice" | "video" | "file";

export interface StepDraft {
  id?: number;
  title: string;
  instructions: string;
  step_type: StepType;
  content_url: string;
  content_attachments: StepAttachment[];
  pending_attachments: PendingAttachment[];
  starts_at: string;
  ends_at: string;
  auto_check: boolean;
  required_outputs: OutputFormat[];
  allow_late_submission: boolean;
  late_penalty_percent: string;
  max_score: string;
}

export const CATEGORY_OPTIONS = [
  ["homework", "تکلیف"],
  ["project", "پروژه"],
  ["practice", "تمرین"],
  ["other", "سایر"],
] as const;

export const STEP_TYPE_OPTIONS: Array<[StepType, string]> = [
  ["content", "محتوا (مشاهده)"],
  ["submit", "ارسال پاسخ"],
  ["auto_complete", "تکمیل خودکار"],
  ["quiz", "آزمونک (آزمایشی)"],
];

export const OUTPUT_OPTIONS: Array<[OutputFormat, string]> = [
  ["text", "متن"],
  ["voice", "صوت"],
  ["video", "ویدیو"],
  ["file", "عکس / فایل"],
];

export function emptyStep(partial?: Partial<StepDraft>): StepDraft {
  return {
    title: "",
    instructions: "",
    step_type: "submit",
    content_url: "",
    content_attachments: [],
    pending_attachments: [],
    starts_at: "",
    ends_at: "",
    auto_check: false,
    required_outputs: ["text"],
    allow_late_submission: false,
    late_penalty_percent: "0",
    max_score: "20",
    ...partial,
  };
}

export function deriveAssignmentEndsAt(steps: StepDraft[]): string | null {
  const timestamps = steps
    .map((s) => s.ends_at)
    .filter(Boolean)
    .map((d) => new Date(d).getTime())
    .filter((t) => !Number.isNaN(t));

  if (!timestamps.length) return null;

  const max = Math.max(...timestamps);
  return new Date(max).toISOString().slice(0, 10);
}

export function categoryLabel(category?: string | null): string {
  const found = CATEGORY_OPTIONS.find(([value]) => value === category);
  return found?.[1] ?? category ?? "تکلیف";
}
