"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ImportPreviewTable } from "@/components/import/ImportPreviewTable";
import { ImportStepper } from "@/components/import/ImportStepper";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ApiError } from "@/lib/api";
import {
  commitImportSession,
  downloadImportTemplate,
  type ImportColumn,
  type ImportErrorItem,
  type ImportSessionPayload,
  uploadImportFile,
} from "@/lib/import";

function friendlyError(err: unknown, fallback: string): string {
  if (err instanceof ApiError) {
    const message = err.message?.trim();
    if (message && !/sqlstate|exception|stack|eloquent|queryexception/i.test(message)) {
      return message;
    }
  }
  return fallback;
}

function sessionFromError(err: unknown): ImportSessionPayload | null {
  if (!(err instanceof ApiError) || !err.payload || typeof err.payload !== "object") {
    return null;
  }
  const errors = (err.payload as { errors?: ImportSessionPayload }).errors;
  if (errors && typeof errors === "object" && typeof errors.id === "number") {
    return errors;
  }
  return null;
}

export function ImportWizard({
  title,
  subtitle,
  backHref,
  templatePath,
  templateFilename,
  uploadPath,
  commitPath,
  columns,
}: {
  title: string;
  subtitle: string;
  backHref: string;
  templatePath: string;
  templateFilename: string;
  uploadPath: string;
  commitPath: (id: number) => string;
  columns: ImportColumn[];
}) {
  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const [step, setStep] = useState(1);
  const [file, setFile] = useState<File | null>(null);
  const [session, setSession] = useState<ImportSessionPayload | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [errorsOnly, setErrorsOnly] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [committing, setCommitting] = useState(false);
  const [downloading, setDownloading] = useState(false);

  const globalErrors: ImportErrorItem[] =
    session?.errors.filter((item) => item.row === null || item.code.startsWith("file.") || item.code.startsWith("header.")) ??
    [];

  const resetToUpload = () => {
    setStep(1);
    setFile(null);
    setSession(null);
    setError(null);
    setErrorsOnly(false);
    if (inputRef.current) inputRef.current.value = "";
  };

  const downloadTemplate = async () => {
    setError(null);
    setDownloading(true);
    try {
      await downloadImportTemplate(templatePath, templateFilename);
    } catch (err) {
      setError(friendlyError(err, "دانلود قالب با مشکل روبه‌رو شد."));
    } finally {
      setDownloading(false);
    }
  };

  const reviewFile = async () => {
    if (!file) {
      setError("ابتدا فایل Excel را انتخاب کنید.");
      return;
    }
    setError(null);
    setUploading(true);
    try {
      const result = await uploadImportFile(uploadPath, file);
      setSession(result);
      setStep(2);
    } catch (err) {
      setError(friendlyError(err, "بررسی فایل انجام نشد. لطفاً قالب را دانلود و دوباره تلاش کنید."));
    } finally {
      setUploading(false);
    }
  };

  const confirmImport = async () => {
    if (!session?.can_commit) return;
    setError(null);
    setCommitting(true);
    try {
      const result = await commitImportSession(commitPath(session.id));
      setSession(result);
      setStep(5);
    } catch (err) {
      const failed = sessionFromError(err);
      if (failed) setSession(failed);
      setError(friendlyError(err, "ثبت اطلاعات انجام نشد. هیچ رکوردی ذخیره نشده است."));
      setStep(3);
    } finally {
      setCommitting(false);
    }
  };

  return (
    <div>
      <ImportStepper step={step} />
      {error ? <Alert tone="error">{error}</Alert> : null}

      {step === 1 ? (
        <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-white p-5 shadow-card">
          <h2 className="text-base font-bold">{title}</h2>
          <p className="text-sm leading-7 text-[var(--muted)]">{subtitle}</p>
          <div className="flex flex-wrap gap-3">
            <Button variant="secondary" loading={downloading} onClick={downloadTemplate}>
              دانلود قالب Excel
            </Button>
          </div>
          <div>
            <input
              ref={inputRef}
              type="file"
              accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              className="block w-full text-sm file:ml-3 file:rounded-xl file:border-0 file:bg-slate-100 file:px-4 file:py-2 file:text-sm file:font-semibold"
              onChange={(event) => {
                setFile(event.target.files?.[0] ?? null);
                setError(null);
              }}
            />
            {file ? (
              <p className="mt-2 text-xs text-[var(--muted)]" dir="ltr">
                {file.name}
              </p>
            ) : null}
          </div>
          <div className="flex flex-wrap gap-3">
            <Button loading={uploading} onClick={reviewFile} disabled={!file}>
              بررسی فایل
            </Button>
            <Button variant="secondary" onClick={() => router.push(backHref)}>
              بازگشت
            </Button>
          </div>
        </div>
      ) : null}

      {step === 2 && session ? (
        <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-white p-5 shadow-card">
          <h2 className="text-base font-bold">نتیجه بررسی فایل</h2>
          <p className="text-sm text-[var(--muted)]">فایل: {session.filename}</p>
          {globalErrors.length > 0 ? (
            <Alert tone="error">
              <ul className="list-disc pr-5 leading-7">
                {globalErrors.map((item, index) => (
                  <li key={`${item.code}-${index}`}>{item.message}</li>
                ))}
              </ul>
            </Alert>
          ) : (
            <Alert tone="success">ساختار فایل و ستون‌ها درست است. در مرحله بعد اطلاعات ردیف‌ها را بررسی کنید.</Alert>
          )}
          <div className="flex flex-wrap gap-3">
            <Button onClick={() => setStep(3)}>ادامه و مشاهده اطلاعات</Button>
            <Button variant="secondary" onClick={resetToUpload}>
              انتخاب فایل دیگر
            </Button>
          </div>
        </div>
      ) : null}

      {step === 3 && session ? (
        <div className="space-y-4">
          <div className="rounded-2xl border border-[var(--border)] bg-white p-5 shadow-card">
            <h2 className="text-base font-bold">بررسی اطلاعات</h2>
            <p className="mt-2 text-sm leading-7 text-[var(--muted)]">
              تعداد ردیف‌ها: {session.total_rows} — معتبر: {session.valid_rows} — دارای خطا: {session.error_rows}
              {session.rows.some((row) => row.action === "update")
                ? ` — کاربر تکراری (ویرایش + حفظ مدرسه قبلی): ${session.rows.filter((row) => row.action === "update").length}`
                : ""}
            </p>
            {!session.can_commit ? (
              <div className="mt-3">
                <Alert tone="warning">
                  تا وقتی همه ردیف‌ها درست نباشند هیچ اطلاعاتی ثبت نمی‌شود. فایل را اصلاح کنید و دوباره بارگذاری کنید.
                </Alert>
              </div>
            ) : (
              <div className="mt-3">
                <Alert tone="success">
                  آماده ثبت است. سلول‌های «قبلی» پروندهٔ موجود را نشان می‌دهند؛ نقش مدرسهٔ جدید اضافه می‌شود.
                </Alert>
              </div>
            )}
            <div className="mt-4 flex flex-wrap gap-2">
              <button
                type="button"
                className={`rounded-xl px-5 py-2.5 text-sm font-semibold transition ${
                  errorsOnly
                    ? "border border-[var(--border)] bg-white text-slate-600 hover:bg-slate-50"
                    : "bg-slate-500 text-white hover:bg-slate-600"
                }`}
                onClick={() => setErrorsOnly(false)}
              >
                همه ردیف‌ها
              </button>
              <button
                type="button"
                className={`rounded-xl px-5 py-2.5 text-sm font-semibold transition ${
                  errorsOnly
                    ? "bg-slate-500 text-white hover:bg-slate-600"
                    : "border border-[var(--border)] bg-white text-slate-600 hover:bg-slate-50"
                }`}
                onClick={() => setErrorsOnly(true)}
              >
                فقط خطا / هشدار
              </button>
            </div>
            <div className="mt-4 flex flex-wrap gap-3">
              <Button onClick={() => setStep(4)} disabled={!session.can_commit}>
                ادامه برای تأیید
              </Button>
              <Button variant="secondary" onClick={resetToUpload}>
                اصلاح و بارگذاری مجدد
              </Button>
              <Button variant="ghost" onClick={() => setStep(2)}>
                بازگشت
              </Button>
            </div>
          </div>
          <ImportPreviewTable columns={columns} rows={session.rows} errorsOnly={errorsOnly} />
        </div>
      ) : null}

      {step === 4 && session ? (
        <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-white p-5 shadow-card">
          <h2 className="text-base font-bold">تأیید ثبت نهایی</h2>
          <p className="text-sm leading-7 text-[var(--muted)]">
            {session.total_rows} ردیف معتبر آماده ثبت است. پس از تأیید، همه این اطلاعات یک‌جا در سامانه ذخیره می‌شود.
            اگر هنگام ثبت خطایی رخ دهد هیچ رکوردی باقی نمی‌ماند.
          </p>
          <p className="text-sm font-semibold">آیا تأیید می‌کنید که این اطلاعات ثبت شود؟</p>
          <div className="flex flex-wrap gap-3">
            <Button loading={committing} onClick={confirmImport} disabled={!session.can_commit}>
              بله، ثبت شود
            </Button>
            <Button variant="secondary" onClick={() => setStep(3)} disabled={committing}>
              انصراف
            </Button>
          </div>
        </div>
      ) : null}

      {step === 5 && session ? (
        <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-white p-5 shadow-card">
          <h2 className="text-base font-bold">نتیجه ورود اطلاعات</h2>
          <Alert tone="success">
            {session.message || `${session.created_rows} کاربر با موفقیت ثبت شد.`}
          </Alert>
          <p className="text-sm text-[var(--muted)]">تعداد ثبت‌شده: {session.created_rows}</p>
          <div className="flex flex-wrap gap-3">
            <Button onClick={() => router.push(backHref || "/dashboard")}>بازگشت</Button>
          </div>
        </div>
      ) : null}
    </div>
  );
}
