"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { AppShell } from "@/components/app/AppShell";
import { ApplicationDetailView } from "@/components/pre-registration/ApplicationDetailView";
import { ConvertToStudentBlock } from "@/components/pre-registration/ConvertToStudentBlock";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Textarea } from "@/components/ui/Field";
import { Skeleton } from "@/components/ui/Skeleton";
import { ApiError, apiGet, apiPatch, apiPostFormData } from "@/lib/api";
import {
  STATUS_LABELS,
  REVIEW_ACTIONS,
  reviewActionsForStatus,
  reviewStatusHint,
} from "@/lib/labels";
import type { ApplicationDetail } from "@/lib/types";

type ReviewActionValue = (typeof REVIEW_ACTIONS)[number]["value"];

export default function AdmissionApplicationDetailPage() {
  const params = useParams<{ id: string }>();
  const searchParams = useSearchParams();
  const applicationId = Number(params.id);
  const group = searchParams.get("group") ?? searchParams.get("bucket");
  const statusFilter = searchParams.get("status");
  const mode = searchParams.get("mode");
  const actionsRef = useRef<HTMLDivElement>(null);

  const [detail, setDetail] = useState<ApplicationDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [reviewAction, setReviewAction] = useState<ReviewActionValue | "">("");
  const [staffNotes, setStaffNotes] = useState("");

  const backHref = useMemo(() => {
    const qs = new URLSearchParams();
    if (group) qs.set("group", group);
    if (statusFilter) qs.set("status", statusFilter);
    const suffix = qs.toString() ? `?${qs.toString()}` : "";
    return `/pre-registration/admissions${suffix}`;
  }, [group, statusFilter]);

  const allowedActions = useMemo(
    () => (detail ? reviewActionsForStatus(detail.status) : []),
    [detail],
  );

  useEffect(() => {
    if (!allowedActions.length) {
      setReviewAction("");
      return;
    }
    setReviewAction((current) =>
      allowedActions.some((a) => a.value === current)
        ? current
        : allowedActions[0].value,
    );
  }, [allowedActions]);

  const loadDetail = useCallback(async (opts?: { quiet?: boolean }) => {
    if (!applicationId) return;
    if (!opts?.quiet) setLoading(true);
    setError(null);
    try {
      const data = await apiGet<ApplicationDetail>(`/pre-registrations/${applicationId}`);
      setDetail(data);
      setStaffNotes(data.staff_notes ?? "");
    } catch (err) {
      setDetail(null);
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری جزئیات");
    } finally {
      if (!opts?.quiet) setLoading(false);
    }
  }, [applicationId]);

  useEffect(() => {
    void loadDetail();
  }, [loadDetail]);

  useEffect(() => {
    if (mode !== "edit" || loading || !detail) return;
    actionsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  }, [mode, loading, detail]);

  const saveForm = async (formData: Record<string, unknown>) => {
    if (!detail) return;
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      await apiPatch(`/admissions/desk/${detail.id}`, { form_data: formData });
      setMessage("اطلاعات درخواست اصلاح شد.");
      await loadDetail({ quiet: true });
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره اطلاعات");
      throw err;
    } finally {
      setSubmitting(false);
    }
  };

  const replaceDocument = async (documentType: string, file: File) => {
    if (!detail) return;
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      const form = new FormData();
      form.append("document_type", documentType);
      form.append("file", file);
      await apiPostFormData(`/admissions/desk/${detail.id}/documents`, form);
      setMessage("مدرک جایگزین شد.");
      await loadDetail({ quiet: true });
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در جایگزینی مدرک");
    } finally {
      setSubmitting(false);
    }
  };

  const submitReview = async () => {
    if (!detail || !reviewAction) return;
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      await apiPatch(`/pre-registrations/${detail.id}/review`, {
        action: reviewAction,
      });
      setMessage("تصمیم بررسی ثبت شد.");
      await loadDetail();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ثبت تصمیم");
    } finally {
      setSubmitting(false);
    }
  };

  const saveStaffNotes = async () => {
    if (!detail) return;
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      await apiPatch(`/admissions/desk/${detail.id}/staff-notes`, {
        staff_notes: staffNotes.trim() || null,
      });
      setMessage("یادداشت مدیر ذخیره شد.");
      await loadDetail({ quiet: true });
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره یادداشت");
    } finally {
      setSubmitting(false);
    }
  };

  const titleName = detail
    ? `${String(detail.form_data?.first_name ?? "")} ${String(detail.form_data?.last_name ?? "")}`.trim()
      || detail.applicant_national_code
    : "جزئیات درخواست";

  return (
    <AppShell
      title={titleName}
      breadcrumbLabels={{
        admission: titleName === "جزئیات درخواست" ? undefined : titleName,
        detail: detail
          ? [STATUS_LABELS[detail.status] ?? detail.status, detail.grade_level?.name].filter(Boolean).join(" · ")
          : undefined,
      }}
    >
      <div className="space-y-4">
        <div className="flex flex-wrap gap-2">
          <Link
            href={backHref}
            className="rounded-xl bg-slate-100 px-3 py-2 text-xs font-semibold text-slate-700"
          >
            ← بازگشت به میز پذیرش
          </Link>
        </div>

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

        {loading ? (
          <div className="space-y-3">
            <Skeleton className="h-28 w-full" />
            <Skeleton className="h-40 w-full" />
            <Skeleton className="h-40 w-full" />
          </div>
        ) : detail ? (
          <>
            <ApplicationDetailView
              detail={detail}
              canEdit={detail.status !== "converted"}
              saving={submitting}
              onSave={saveForm}
              onReplaceDocument={replaceDocument}
            />

            {detail.status === "approved" ? (
              <ConvertToStudentBlock
                detail={detail}
                onConverted={(result) => {
                  const pending = !result.class_room_id;
                  setError(null);
                  setMessage(
                    pending
                      ? "تبدیل انجام شد. دانش‌آموز بدون کلاس ثبت شد و اطلاعات پنل برای دانش‌آموز و ولی ارسال می‌شود."
                      : "تبدیل انجام شد. دانش‌آموز با کلاس ثبت شد و اطلاعات پنل برای دانش‌آموز و ولی ارسال می‌شود.",
                  );
                  void loadDetail();
                }}
              />
            ) : null}

            {detail.status === "converted" && detail.sis_student_profile_id ? (
              <Alert tone="success">
                این درخواست به دانش‌آموز تبدیل شده است.{" "}
                <Link
                  href={`/students/${detail.sis_student_profile_id}`}
                  className="font-semibold text-primary underline"
                >
                  مشاهده پروفایل
                </Link>
                {" · "}
                <Link
                  href={`/students/${detail.sis_student_profile_id}/guardians`}
                  className="font-semibold text-primary underline"
                >
                  اولیا
                </Link>
                {detail.branch?.id ? (
                  <>
                    {" · "}
                    <Link
                      href={`/students?branch_id=${detail.branch.id}&pending_placement=1`}
                      className="font-semibold text-primary underline"
                    >
                      منتظر کلاس‌بندی این مدرسه
                    </Link>
                  </>
                ) : null}
              </Alert>
            ) : null}

            <div
              ref={actionsRef}
              id="review-actions"
              className="space-y-4"
            >
              <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
                <div className="mb-4">
                  <h3 className="text-sm font-bold">وضعیت پیش‌ثبت‌نام</h3>
                  <p className="mt-1 text-xs text-[var(--muted)]">
                    وضعیت فعلی:{" "}
                    <span className="font-semibold text-slate-800">
                      {STATUS_LABELS[detail.status] ?? detail.status}
                    </span>
                  </p>
                  <p className="mt-2 text-sm leading-6 text-slate-700">
                    {reviewStatusHint(detail.status)}
                  </p>
                </div>

                {allowedActions.length ? (
                  <div className="space-y-3">
                    <div className="flex flex-wrap gap-2">
                      {allowedActions.map((action) => (
                        <button
                          key={action.value}
                          type="button"
                          onClick={() => setReviewAction(action.value)}
                          className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                            reviewAction === action.value
                              ? "bg-primary text-white"
                              : "bg-slate-100 text-slate-700 hover:bg-slate-200"
                          }`}
                        >
                          {action.label}
                        </button>
                      ))}
                    </div>
                    <Button
                      loading={submitting}
                      disabled={!reviewAction}
                      onClick={() => void submitReview()}
                    >
                      ثبت تصمیم
                      {reviewAction
                        ? ` (${allowedActions.find((a) => a.value === reviewAction)?.label ?? ""})`
                        : ""}
                    </Button>
                  </div>
                ) : (
                  <Alert tone="info">{reviewStatusHint(detail.status)}</Alert>
                )}
              </div>

              <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
                <h3 className="text-sm font-bold">یادداشت مدیر</h3>
                <p className="mt-1 text-xs text-[var(--muted)]">
                  این یادداشت فقط برای کادر مدرسه است و برای ولی ارسال نمی‌شود.
                </p>
                <div className="mt-3 space-y-3">
                  <Field label="یادداشت داخلی">
                    <Textarea
                      rows={4}
                      value={staffNotes}
                      onChange={(e) => setStaffNotes(e.target.value)}
                      placeholder="مثلاً مدارک ناقص، تماس با ولی، یا توضیح برای همکار بعدی"
                    />
                  </Field>
                  <Button
                    variant="secondary"
                    loading={submitting}
                    onClick={() => void saveStaffNotes()}
                  >
                    ذخیره یادداشت
                  </Button>
                </div>
              </div>
            </div>
          </>
        ) : (
          <Alert tone="warning">درخواست یافت نشد.</Alert>
        )}
      </div>
    </AppShell>
  );
}
