"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useParams } from "@/lib/route-params";
import { useCallback, useEffect, useState } from "react";
import { CurriculumBookPdfsField, type CurriculumBookPdfItem } from "@/components/academic/CurriculumBookPdfsField";
import { CurriculumBooksPanel } from "@/components/academic/CurriculumBooksPanel";
import { CurriculumNav } from "@/components/academic/CurriculumNav";
import { SortableChapterList, SortableReorderList } from "@/components/academic/SortableChapterList";
import { AppShell } from "@/components/app/AppShell";
import { RequireAcademicAdmin } from "@/components/auth/RequirePermission";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input } from "@/components/ui/Field";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { ApiError, apiDelete, apiGet, apiPatch, apiPost, apiPostFormData, apiPut } from "@/lib/api";
import { canManageBranchSubjects, canManageOrgSubjects } from "@/lib/permissions";
import { getActiveBranchId } from "@/lib/session-context";

interface TopicRow {
  id: number;
  title: string;
  order: number;
}

interface ChapterRow {
  id: number;
  title: string;
  order: number;
  topics: TopicRow[];
}

interface LinkedSubjectRow {
  id: number;
  name: string;
  grade_level?: { id: number; name: string } | null;
  study_fields?: string[];
}

interface BookDetail {
  id: number;
  title: string;
  code?: string | null;
  branch_id?: number | null;
  can_edit?: boolean;
  chapters: ChapterRow[];
  linked_subjects?: LinkedSubjectRow[];
  pdfs?: CurriculumBookPdfItem[];
  branch?: { id: number; name: string } | null;
}

export default function CurriculumBookPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const searchParams = useSearchParams();
  const canCreateOrg = canManageOrgSubjects();
  const canCreateSchool = canManageBranchSubjects();
  const isNew = params.id === "new";
  const bookId = isNew ? null : Number(params.id);
  const requestedBranchId = Number(searchParams.get("branch_id") || "") || null;
  const createBranchId = isNew
    ? requestedBranchId ?? (canCreateOrg ? null : getActiveBranchId())
    : null;
  const canCreate = isNew && (createBranchId ? canCreateSchool : canCreateOrg);

  const [book, setBook] = useState<BookDetail | null>(null);
  const [canEdit, setCanEdit] = useState(canCreate);
  const [meta, setMeta] = useState({ title: "", code: "" });
  const [pdfs, setPdfs] = useState<CurriculumBookPdfItem[]>([]);
  const [pendingPdfs, setPendingPdfs] = useState<File[]>([]);
  const [chapterTitle, setChapterTitle] = useState("");
  const [topicDrafts, setTopicDrafts] = useState<Record<number, string>>({});
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [panelKey, setPanelKey] = useState(0);

  const load = useCallback(async () => {
    if (isNew || !bookId) return;
    setLoading(true);
    try {
      const detail = await apiGet<BookDetail>(`/curriculum-books/${bookId}`);
      setBook(detail);
      setCanEdit(Boolean(detail.can_edit));
      setMeta({
        title: detail.title,
        code: detail.code ?? "",
      });
      setPdfs(detail.pdfs ?? []);
      setError(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setLoading(false);
    }
  }, [isNew, bookId]);

  useEffect(() => {
    load().catch((err) => setError(err instanceof ApiError ? err.message : "خطا"));
  }, [load]);

  useEffect(() => {
    if (isNew && !canCreate) {
      router.replace("/academic/curriculum/books");
    }
  }, [isNew, canCreate, router]);

  const saveBook = async () => {
    if (!meta.title.trim()) return;
    setSaving(true);
    try {
      const body: { title: string; code: string | null; branch_id?: number } = {
        title: meta.title.trim(),
        code: meta.code || null,
      };
      if (isNew && createBranchId) {
        body.branch_id = createBranchId;
      }
      if (isNew) {
        const created = await apiPost<BookDetail>("/curriculum-books", body);
        for (const file of pendingPdfs) {
          const form = new FormData();
          form.append("file", file);
          try {
            await apiPostFormData(`/curriculum-books/${created.id}/pdfs`, form);
          } catch (err) {
            setError(err instanceof ApiError ? err.message : "کتاب ایجاد شد، اما آپلود PDF ناموفق بود.");
          }
        }
        setPendingPdfs([]);
        setPanelKey((k) => k + 1);
        router.replace(`/academic/curriculum/books/${created.id}`);
      } else if (bookId) {
        await apiPatch(`/curriculum-books/${bookId}`, body);
        await load();
        setPanelKey((k) => k + 1);
      }
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setSaving(false);
    }
  };

  const removeBook = async () => {
    if (!book || !window.confirm(`کتاب «${book.title}» حذف شود؟`)) return;
    try {
      await apiDelete(`/curriculum-books/${book.id}`);
      router.push("/academic/curriculum/books");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const addChapter = async () => {
    if (!book || !chapterTitle.trim()) return;
    setSaving(true);
    try {
      await apiPost(`/curriculum-books/${book.id}/chapters`, { title: chapterTitle.trim() });
      setChapterTitle("");
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setSaving(false);
    }
  };

  const reorderChapters = async (chapterIds: number[]) => {
    if (!book) return;
    try {
      const detail = await apiPut<BookDetail>(
        `/curriculum-books/${book.id}/chapters/reorder`,
        { chapter_ids: chapterIds },
      );
      setBook(detail);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const reorderTopics = async (chapterId: number, topicIds: number[]) => {
    if (!book) return;
    try {
      await apiPut(`/curriculum-chapters/${chapterId}/topics/reorder`, {
        topic_ids: topicIds,
      });
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const addTopic = async (chapterId: number) => {
    const title = topicDrafts[chapterId]?.trim();
    if (!title) return;
    setSaving(true);
    try {
      await apiPost(`/curriculum-chapters/${chapterId}/topics`, { title });
      setTopicDrafts((d) => ({ ...d, [chapterId]: "" }));
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setSaving(false);
    }
  };

  const removeChapter = async (chapterId: number) => {
    if (!window.confirm("فصل و موضوعات آن حذف شوند؟")) return;
    await apiDelete(`/curriculum-chapters/${chapterId}`);
    await load();
  };

  const removeTopic = async (topic: TopicRow) => {
    if (!window.confirm(`موضوع «${topic.title}» حذف شود؟`)) return;
    await apiDelete(`/curriculum-topics/${topic.id}`);
    await load();
  };

  const renderChapterBody = (chapter: ChapterRow, index: number) => (
    <>
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2 px-3 pt-3">
        <h3 className="font-semibold">
          فصل {(index + 1).toLocaleString("fa-IR")}: {chapter.title}
        </h3>
        {canEdit ? (
          <Button
            variant="danger"
            className="!px-3 !py-1 text-xs"
            onClick={() => removeChapter(chapter.id)}
          >
            حذف فصل
          </Button>
        ) : null}
      </div>
      {canEdit && chapter.topics.length > 0 ? (
        <p className="mb-2 px-3 text-[11px] text-[var(--muted)]">
          برای تغییر ترتیب موضوعات بکشید؛ سپس «اعمال تغییرات» را بزنید.
        </p>
      ) : null}
      <div className="mb-3 px-3">
        {canEdit ? (
          <SortableReorderList
            items={chapter.topics}
            variant="row"
            handleAriaLabel="جابجایی موضوع"
            onApply={(topicIds) => reorderTopics(chapter.id, topicIds)}
            renderItem={(topic, topicIndex) => (
              <div className="flex items-center justify-between gap-2 py-0.5">
                <span>
                  {(topicIndex + 1).toLocaleString("fa-IR")}. {topic.title}
                </span>
                <button
                  type="button"
                  className="text-xs text-red-600"
                  onClick={() => removeTopic(topic)}
                >
                  حذف
                </button>
              </div>
            )}
          />
        ) : (
          <ul className="space-y-1">
            {chapter.topics.map((topic) => (
              <li
                key={topic.id}
                className="rounded-lg border border-[var(--border)] px-3 py-2 text-sm"
              >
                {topic.order.toLocaleString("fa-IR")}. {topic.title}
              </li>
            ))}
          </ul>
        )}
      </div>
      {canEdit ? (
        <div className="flex flex-wrap gap-2 px-3 pb-3">
          <Input
            className="max-w-sm"
            value={topicDrafts[chapter.id] ?? ""}
            onChange={(e) => setTopicDrafts((d) => ({ ...d, [chapter.id]: e.target.value }))}
            placeholder="موضوع جدید"
          />
          <Button
            variant="secondary"
            className="!px-3 !py-1 text-xs"
            onClick={() => addTopic(chapter.id)}
            disabled={saving}
          >
            افزودن موضوع
          </Button>
        </div>
      ) : (
        <div className="pb-3" />
      )}
    </>
  );

  return (
    <RequireAcademicAdmin>
      <AppShell
        title={isNew ? "کتاب درسی جدید" : book?.title ?? "کتاب درسی"}
        subtitle={
          book?.branch?.name || createBranchId
            ? undefined
            : "سرفصل مشترک هلدینگ — قابل استفاده در چند پایه و رشته"
        }
        breadcrumbLabels={{
          book: book?.title,
          school: book?.branch?.name,
          detail: book?.branch?.name || createBranchId ? "اختصاصی مدرسه" : undefined,
        }}
      >
        <CurriculumNav current={isNew ? "new-book" : "books"} />

        {error ? (
          <div className="mb-4">
            <Alert tone="error">{error}</Alert>
          </div>
        ) : null}

        <div className="grid gap-4 lg:grid-cols-[18rem_minmax(0,1fr)]">
          <CurriculumBooksPanel
            key={panelKey}
            currentBookId={isNew ? "new" : bookId ?? undefined}
            branchId={book?.branch_id ?? createBranchId}
            compact
          />

          <div>
            {loading ? (
              <PageContentSkeleton />
            ) : (
              <>
                <div className="mb-4 space-y-3 rounded-2xl border border-[var(--border)] bg-white p-4">
                  <div className="grid gap-3 md:grid-cols-2">
                    <Field label="عنوان کتاب">
                      <Input
                        value={meta.title}
                        onChange={(e) => setMeta({ ...meta, title: e.target.value })}
                        disabled={!canEdit}
                      />
                    </Field>
                    <Field label="کد">
                      <Input
                        value={meta.code}
                        onChange={(e) => setMeta({ ...meta, code: e.target.value })}
                        disabled={!canEdit}
                      />
                    </Field>
                  </div>
                  {canEdit || pdfs.length > 0 ? (
                    <CurriculumBookPdfsField
                      bookId={isNew ? null : bookId}
                      pdfs={pdfs}
                      pendingFiles={pendingPdfs}
                      onPdfsChange={setPdfs}
                      onPendingFilesChange={setPendingPdfs}
                      disabled={!canEdit}
                    />
                  ) : null}
                  <p className="text-xs text-[var(--muted)]">
                    کتاب مستقل از پایه است. سرفصل یک‌بار تعریف می‌شود و به چند درس وصل می‌شود.
                  </p>
                  {canEdit ? (
                    <div className="flex flex-wrap gap-2">
                      <Button onClick={saveBook} disabled={saving}>
                        {isNew ? "ایجاد کتاب" : "ذخیره مشخصات"}
                      </Button>
                      {!isNew && book ? (
                        <Button variant="danger" onClick={removeBook}>
                          حذف کتاب
                        </Button>
                      ) : null}
                    </div>
                  ) : null}
                </div>

                {!isNew && book ? (
                  <div className="space-y-4">
                    {(book.linked_subjects?.length ?? 0) > 0 ? (
                      <div className="rounded-2xl border border-[var(--border)] bg-white p-4">
                        <h2 className="mb-2 text-sm font-bold text-primary">دروس متصل</h2>
                        <ul className="space-y-1 text-sm">
                          {book.linked_subjects!.map((subject) => {
                            const grade = subject.grade_level?.name ?? "—";
                            const fields =
                              subject.study_fields && subject.study_fields.length > 0
                                ? ` (${subject.study_fields.join("، ")})`
                                : "";
                            return (
                              <li key={subject.id} className="text-[var(--muted)]">
                                {subject.name} — {grade}
                                {fields}
                              </li>
                            );
                          })}
                        </ul>
                      </div>
                    ) : (
                      <Alert tone="info">
                        این کتاب هنوز به درسی وصل نشده. از صفحه برنامه درسی، کتاب را به درس
                        اختصاص دهید.
                      </Alert>
                    )}

                    {canEdit ? (
                      <div className="rounded-2xl border border-[var(--border)] bg-white p-4">
                        <h2 className="mb-3 font-bold text-primary">افزودن فصل</h2>
                        <div className="flex flex-wrap gap-2">
                          <Input
                            className="max-w-md"
                            value={chapterTitle}
                            onChange={(e) => setChapterTitle(e.target.value)}
                            placeholder="عنوان فصل"
                          />
                          <Button onClick={addChapter} disabled={saving}>
                            افزودن فصل
                          </Button>
                        </div>
                      </div>
                    ) : null}

                    {book.chapters.length === 0 ? (
                      <Alert tone="info">هنوز فصلی تعریف نشده است.</Alert>
                    ) : (
                      <>
                        {canEdit ? (
                          <p className="text-xs text-[var(--muted)]">
                            برای تغییر ترتیب فصول، آیکون ⠿ را بگیرید و بکشید؛ سپس «اعمال تغییرات» را
                            بزنید.
                          </p>
                        ) : null}
                        <SortableChapterList
                          chapters={book.chapters}
                          onReorder={reorderChapters}
                          disabled={!canEdit}
                          renderChapter={renderChapterBody}
                        />
                      </>
                    )}
                  </div>
                ) : null}
              </>
            )}
          </div>
        </div>
      </AppShell>
    </RequireAcademicAdmin>
  );
}
