"use client";

import { useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Textarea } from "@/components/ui/Field";
import { ApiError, apiPost, apiPostFormData } from "@/lib/api";

export type ProgressState = "done" | "current" | "locked" | "future";

export interface ProgressStep {
  id: number;
  sort_order: number;
  title: string;
  instructions?: string | null;
  step_type: string;
  content_url?: string | null;
  content_attachments?: Array<{
    type: string;
    path?: string;
    name?: string;
    mime?: string | null;
    url?: string | null;
  }>;
  starts_at?: string | null;
  ends_at?: string | null;
  auto_check: boolean;
  required_outputs: string[];
  allow_late_submission: boolean;
  late_penalty_percent: number;
  max_score?: number | string | null;
  state: ProgressState;
  late_message?: string | null;
  submission?: {
    id: number;
    status: string;
    score?: number | string | null;
    is_late?: boolean;
    submitted_at?: string | null;
    payload?: Record<string, unknown> | null;
    feedback?: {
      comment?: string | null;
      score?: number | string | null;
      returned_for_revision?: boolean;
      revision_deadline?: string | null;
      full_score_override?: boolean;
    } | null;
  } | null;
}

export interface ProgressPayload {
  assignment: {
    id: number;
    title: string;
    instructions?: string | null;
    max_score?: number | string | null;
  };
  steps: ProgressStep[];
}

function formatDate(value?: string | null): string {
  if (!value) return "";
  try {
    return new Date(value).toLocaleString("fa-IR");
  } catch {
    return value;
  }
}

function stateMeta(state: ProgressState): { label: string; className: string; marker: string } {
  switch (state) {
    case "done":
      return { label: "انجام‌شده", className: "border-emerald-300 bg-emerald-50", marker: "✓" };
    case "current":
      return { label: "جاری", className: "border-primary bg-teal-50/60", marker: "●" };
    case "future":
      return { label: "آینده", className: "border-slate-200 bg-white", marker: "○" };
    default:
      return { label: "قفل", className: "border-slate-200 bg-slate-50 opacity-80", marker: "○" };
  }
}

export function AssignmentProgressRoadmap({
  data,
  onUpdated,
}: {
  data: ProgressPayload;
  onUpdated: () => void;
}) {
  const [error, setError] = useState<string | null>(null);
  const [busyStep, setBusyStep] = useState<number | null>(null);
  const [textByStep, setTextByStep] = useState<Record<number, string>>({});
  const [filesByStep, setFilesByStep] = useState<
    Record<number, { voice?: File; video?: File; file?: File }>
  >({});

  const completeStep = async (step: ProgressStep) => {
    setBusyStep(step.id);
    setError(null);
    try {
      await apiPost(`/assignments/steps/${step.id}/complete`, {});
      onUpdated();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در تکمیل مرحله");
    } finally {
      setBusyStep(null);
    }
  };

  const submitStep = async (step: ProgressStep) => {
    setBusyStep(step.id);
    setError(null);
    try {
      const form = new FormData();
      const text = textByStep[step.id]?.trim();
      if (text) {
        form.append("content", text);
        form.append("text", text);
      }
      const files = filesByStep[step.id] ?? {};
      if (files.voice) form.append("voice", files.voice);
      if (files.video) form.append("video", files.video);
      if (files.file) form.append("file", files.file);

      await apiPostFormData(`/assignments/steps/${step.id}/submissions`, form);
      onUpdated();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ارسال");
    } finally {
      setBusyStep(null);
    }
  };

  return (
    <div className="space-y-4" dir="rtl">
      <div>
        <h2 className="text-xl font-bold">{data.assignment.title}</h2>
        {data.assignment.instructions ? (
          <p className="mt-1 text-sm text-[var(--muted)]">{data.assignment.instructions}</p>
        ) : null}
      </div>

      {error ? <Alert tone="error">{error}</Alert> : null}

      {/* Simple RTL stepper strip */}
      <div className="flex flex-wrap items-center gap-2 rounded-2xl border border-[var(--border)] bg-white p-3">
        {data.steps.map((step, index) => {
          const meta = stateMeta(step.state);
          return (
            <div key={step.id} className="flex items-center gap-2">
              {index > 0 ? <span className="text-[var(--muted)]">←</span> : null}
              <span
                className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs ${meta.className}`}
              >
                <span aria-hidden>{meta.marker}</span>
                {step.title}
              </span>
            </div>
          );
        })}
      </div>

      <div className="space-y-3">
        {data.steps.map((step) => {
          const meta = stateMeta(step.state);
          const feedback = step.submission?.feedback;
          const isReturned = step.submission?.status === "returned";
          const revisionDeadline = feedback?.revision_deadline;
          const showLateBanner =
            step.state === "current" &&
            Boolean(step.late_message) &&
            step.allow_late_submission;

          return (
            <section
              key={step.id}
              className={`rounded-2xl border p-4 ${meta.className}`}
            >
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                  <h3 className="font-bold">
                    {meta.marker} {step.title}
                  </h3>
                  <p className="mt-0.5 text-xs text-[var(--muted)]">
                    {meta.label}
                    {step.ends_at ? ` · موعد: ${formatDate(step.ends_at)}` : ""}
                    {step.max_score != null ? ` · بارم: ${step.max_score}` : ""}
                  </p>
                </div>
                {step.submission?.score != null ? (
                  <span className="rounded-lg bg-white/80 px-2 py-0.5 text-sm font-medium">
                    نمره: {step.submission.score}
                  </span>
                ) : null}
              </div>

              {step.instructions ? (
                <p className="mt-2 text-sm whitespace-pre-wrap">{step.instructions}</p>
              ) : null}

              {step.content_url && (step.state === "current" || step.state === "done") ? (
                <p className="mt-2 text-sm">
                  <a
                    href={step.content_url}
                    target="_blank"
                    rel="noreferrer"
                    className="text-primary underline"
                  >
                    مشاهده محتوا
                  </a>
                </p>
              ) : null}

              {step.content_attachments?.length &&
              (step.state === "current" || step.state === "done") ? (
                <div className="mt-3 space-y-2">
                  {step.content_attachments.map((attachment) => (
                    <div key={attachment.path ?? attachment.url ?? attachment.name}>
                      {attachment.type === "photo" && attachment.url ? (
                        <img
                          src={attachment.url}
                          alt={attachment.name ?? "عکس"}
                          className="max-h-48 rounded-lg border border-[var(--border)]"
                        />
                      ) : null}
                      {attachment.type === "video" && attachment.url ? (
                        <video src={attachment.url} controls className="max-h-48 w-full rounded-lg" />
                      ) : null}
                      {attachment.type === "voice" && attachment.url ? (
                        <audio src={attachment.url} controls className="w-full" />
                      ) : null}
                      {attachment.type === "file" && attachment.url ? (
                        <a
                          href={attachment.url}
                          target="_blank"
                          rel="noreferrer"
                          className="text-sm text-primary underline"
                        >
                          {attachment.name ?? "دانلود فایل"}
                        </a>
                      ) : null}
                    </div>
                  ))}
                </div>
              ) : null}

              {showLateBanner ? <div className="mt-3"><Alert tone="warning">{step.late_message}</Alert></div> : null}

              {isReturned && revisionDeadline ? (
                <div className="mt-3">
                  <Alert tone="warning">
                    عودت برای اصلاح — مهلت تا {formatDate(revisionDeadline)}
                    {feedback?.comment ? ` · ${feedback.comment}` : ""}
                  </Alert>
                </div>
              ) : null}

              {step.state === "locked" || step.state === "future" ? (
                <p className="mt-3 text-sm text-[var(--muted)]">
                  این مرحله پس از تکمیل مرحله قبلی باز می‌شود.
                </p>
              ) : null}

              {step.state === "done" ? (
                <div className="mt-3 space-y-1 text-sm text-[var(--muted)]">
                  <p>وضعیت: {step.submission?.status}</p>
                  {feedback?.comment ? <p>بازخورد: {feedback.comment}</p> : null}
                  {step.submission?.is_late ? (
                    <p>
                      ارسال با تأخیر
                      {feedback?.full_score_override ? " (نمره کامل توسط استاد)" : ""}
                    </p>
                  ) : null}
                </div>
              ) : null}

              {step.state === "current" ? (
                <div className="mt-4 space-y-3">
                  {step.submission &&
                  ["submitted", "resubmitted"].includes(step.submission.status) ? (
                    <p className="text-sm text-amber-800">
                      پاسخ شما دریافت شد و در انتظار تصحیح استاد است.
                    </p>
                  ) : (
                    <>
                      {(step.step_type === "content" ||
                        step.step_type === "auto_complete" ||
                        (step.auto_check && step.step_type !== "submit")) && (
                        <Button
                          loading={busyStep === step.id}
                          onClick={() => completeStep(step)}
                        >
                          انجام شد
                        </Button>
                      )}

                      {(step.step_type === "submit" || step.step_type === "quiz") &&
                      !step.auto_check ? (
                        <>
                          {step.required_outputs.includes("text") ? (
                            <Field label="پاسخ متنی">
                              <Textarea
                                rows={4}
                                value={textByStep[step.id] ?? ""}
                                onChange={(e) =>
                                  setTextByStep((prev) => ({
                                    ...prev,
                                    [step.id]: e.target.value,
                                  }))
                                }
                              />
                            </Field>
                          ) : null}
                          {(["voice", "video", "file"] as const)
                            .filter((f) => step.required_outputs.includes(f))
                            .map((format) => (
                              <Field
                                key={format}
                                label={
                                  format === "voice"
                                    ? "فایل صوت"
                                    : format === "video"
                                      ? "فایل ویدیو"
                                      : "فایل پیوست"
                                }
                              >
                                <Input
                                  type="file"
                                  accept={
                                    format === "voice"
                                      ? "audio/*"
                                      : format === "video"
                                        ? "video/*"
                                        : undefined
                                  }
                                  onChange={(e) => {
                                    const file = e.target.files?.[0];
                                    setFilesByStep((prev) => ({
                                      ...prev,
                                      [step.id]: { ...prev[step.id], [format]: file },
                                    }));
                                  }}
                                />
                              </Field>
                            ))}
                          <Button
                            loading={busyStep === step.id}
                            onClick={() => submitStep(step)}
                          >
                            {isReturned ? "ارسال مجدد" : "ارسال پاسخ"}
                          </Button>
                        </>
                      ) : null}

                      {step.step_type === "submit" && step.auto_check ? (
                        <>
                          {step.required_outputs.includes("text") ? (
                            <Field label="یادداشت (اختیاری)">
                              <Textarea
                                rows={3}
                                value={textByStep[step.id] ?? ""}
                                onChange={(e) =>
                                  setTextByStep((prev) => ({
                                    ...prev,
                                    [step.id]: e.target.value,
                                  }))
                                }
                              />
                            </Field>
                          ) : null}
                          <Button
                            loading={busyStep === step.id}
                            onClick={() =>
                              step.required_outputs.length
                                ? submitStep(step)
                                : completeStep(step)
                            }
                          >
                            تکمیل مرحله
                          </Button>
                        </>
                      ) : null}
                    </>
                  )}
                </div>
              ) : null}

            </section>
          );
        })}
      </div>
    </div>
  );
}
