"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Textarea } from "@/components/ui/Field";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { TeacherPanel } from "@/components/teacher/ui/TeacherPanel";
import { ClassLogHistory } from "@/components/teacher/ClassLogHistory";
import { SessionDateField } from "@/components/teacher/ui/SessionDateField";
import {
  SyllabusSearchSelect,
  type SyllabusPayload,
} from "@/components/teacher/SyllabusSearchSelect";
import { ApiError, apiGet, apiPatch, apiPost } from "@/lib/api";

interface ClassLogRow {
  id: number;
  log_date: string;
  subject_id?: number | null;
  topic?: string | null;
  chapters_note?: string | null;
  activities?: string | null;
  homework_note?: string | null;
  teacher_note?: string | null;
}

interface CoveredSyllabus {
  topicIds: number[];
  chapterIds: number[];
  legacy: string;
}

const TEACHER_ONLY_HINT =
  "فقط برای معلم نمایش داده می‌شود و در گزارش های سایر بخش ها نمایش داده نمیشود";

function parseCovered(note?: string | null): CoveredSyllabus {
  if (!note?.trim()) return { topicIds: [], chapterIds: [], legacy: "" };
  try {
    const parsed = JSON.parse(note) as { topic_ids?: unknown; chapter_ids?: unknown };
    if (parsed && typeof parsed === "object" && (Array.isArray(parsed.topic_ids) || Array.isArray(parsed.chapter_ids))) {
      return {
        topicIds: (parsed.topic_ids ?? []).map(Number).filter((id) => Number.isFinite(id) && id > 0),
        chapterIds: (parsed.chapter_ids ?? []).map(Number).filter((id) => Number.isFinite(id) && id > 0),
        legacy: "",
      };
    }
  } catch {
    // متن قدیمی دفتر
  }
  return { topicIds: [], chapterIds: [], legacy: note };
}

function serializeCovered(topicIds: number[], chapterIds: number[]): string | null {
  if (topicIds.length === 0 && chapterIds.length === 0) return null;
  return JSON.stringify({
    topic_ids: topicIds,
    chapter_ids: chapterIds,
  });
}

function coveredLabels(
  syllabus: SyllabusPayload | null,
  covered: CoveredSyllabus,
): string[] {
  if (covered.legacy) return [covered.legacy];
  if (!syllabus) return [];
  const topicSet = new Set(covered.topicIds);
  const chapterSet = new Set(covered.chapterIds);
  const labels: string[] = [];
  for (const chapter of syllabus.chapters) {
    if (chapter.topics.length === 0) {
      if (chapterSet.has(chapter.id)) labels.push(chapter.title);
      continue;
    }
    for (const topic of chapter.topics) {
      if (topicSet.has(topic.id)) labels.push(`${chapter.title} — ${topic.title}`);
    }
  }
  return labels;
}

function ReadValue({
  label,
  value,
  hint,
}: {
  label: string;
  value?: string | null;
  hint?: string;
}) {
  return (
    <div className="space-y-1">
      <div className="text-sm font-medium text-slate-800">{label}</div>
      {hint ? <div className="text-xs text-slate-500">{hint}</div> : null}
      <div className="whitespace-pre-wrap rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 text-sm text-slate-800">
        {value?.trim() || "—"}
      </div>
    </div>
  );
}

export function ClassLogTab({
  classRoomId,
  subjectId,
  logDate,
  onHistoryDateSelect,
}: {
  classRoomId: number;
  subjectId?: number | null;
  logDate?: string;
  onHistoryDateSelect?: (date: string) => void;
}) {
  const date = logDate ?? new Date().toISOString().slice(0, 10);
  const [topic, setTopic] = useState("");
  const [activities, setActivities] = useState("");
  const [teacherNote, setTeacherNote] = useState("");
  const [homeworkNote, setHomeworkNote] = useState("");
  const [topicIds, setTopicIds] = useState<number[]>([]);
  const [chapterIds, setChapterIds] = useState<number[]>([]);
  const [legacyChapters, setLegacyChapters] = useState("");
  const [syllabus, setSyllabus] = useState<SyllabusPayload | null>(null);
  const [history, setHistory] = useState<ClassLogRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editing, setEditing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [historyRefreshKey, setHistoryRefreshKey] = useState(0);

  const applyCovered = (note?: string | null) => {
    const covered = parseCovered(note);
    setTopicIds(covered.topicIds);
    setChapterIds(covered.chapterIds);
    setLegacyChapters(covered.legacy);
  };

  const load = useCallback(async (opts?: { silent?: boolean }) => {
    if (!opts?.silent) setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ class_room_id: String(classRoomId) });
      if (subjectId) params.set("subject_id", String(subjectId));
      const rows = await apiGet<ClassLogRow[]>(`/class-logs?${params}`);
      setHistory(rows);
      const today = rows.find((r) => r.log_date?.slice(0, 10) === date);
      if (today) {
        setTopic(today.topic ?? "");
        setActivities(today.activities ?? "");
        setTeacherNote(today.teacher_note ?? "");
        setHomeworkNote(today.homework_note ?? "");
        applyCovered(today.chapters_note);
      } else {
        setTopic("");
        setActivities("");
        setTeacherNote("");
        setHomeworkNote("");
        applyCovered(null);
      }
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      if (!opts?.silent) setLoading(false);
    }
  }, [classRoomId, date, subjectId]);

  const loadSyllabus = useCallback(async () => {
    if (!subjectId) {
      setSyllabus({ book: null, chapters: [] });
      return;
    }
    try {
      const data = await apiGet<SyllabusPayload>(
        `/teacher/classes/${classRoomId}/syllabus?subject_id=${subjectId}`,
      );
      setSyllabus(data);
    } catch {
      setSyllabus({ book: null, chapters: [] });
    }
  }, [classRoomId, subjectId]);

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

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

  useEffect(() => {
    setEditing(false);
    setSuccess(null);
  }, [date]);

  const existingLog = useMemo(
    () => history.find((r) => r.log_date?.slice(0, 10) === date) ?? null,
    [history, date],
  );

  const previousLog = useMemo(
    () => history.find((r) => r.log_date?.slice(0, 10) < date),
    [history, date],
  );

  const showForm = !existingLog || editing;
  const hasSyllabus = Boolean(syllabus?.chapters.length);

  const setCoveredIds = (next: { topicIds: number[]; chapterIds: number[] }) => {
    setLegacyChapters("");
    setTopicIds(next.topicIds);
    setChapterIds(next.chapterIds);
  };

  const save = async () => {
    if (!topic.trim()) {
      setError("موضوع تدریس الزامی است.");
      setSuccess(null);
      return;
    }
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      const body = {
        class_room_id: classRoomId,
        subject_id: subjectId ?? null,
        log_date: date,
        topic: topic.trim(),
        chapters_note: serializeCovered(topicIds, chapterIds) ?? (legacyChapters.trim() || null),
        activities: activities.trim() || null,
        teacher_note: teacherNote.trim() || null,
        homework_note: homeworkNote.trim() || null,
      };
      if (existingLog) {
        await apiPatch(`/class-logs/${existingLog.id}`, body);
      } else {
        await apiPost("/class-logs", body);
      }
      setSuccess("دفتر کلاسی ذخیره شد.");
      setEditing(false);
      setHistoryRefreshKey((k) => k + 1);
      await load({ silent: true });
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <PageContentSkeleton rows={5} />;

  const covered = parseCovered(existingLog?.chapters_note);
  const selectedSummary = coveredLabels(syllabus, {
    topicIds,
    chapterIds,
    legacy: legacyChapters,
  });

  return (
    <div className="grid gap-4 lg:grid-cols-[1fr_260px]">
      <TeacherPanel>
        <div className="space-y-4">
          {error ? <Alert tone="error">{error}</Alert> : null}
          {success ? <Alert tone="success">{success}</Alert> : null}

          <SessionDateField
            value={date}
            onChange={(next) => onHistoryDateSelect?.(next)}
            classRoomId={classRoomId}
            subjectId={subjectId}
          />

          {previousLog?.homework_note ? (
            <Alert tone="info">
              یادداشت جلسه قبل ({previousLog.log_date?.slice(0, 10)}): {previousLog.homework_note}
            </Alert>
          ) : null}

          {existingLog && !editing ? (
            <>
              <div className="flex flex-wrap items-center justify-between gap-2">
                <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-bold text-emerald-800">
                  گزارش ثبت شده
                </span>
                <Button
                  type="button"
                  variant="secondary"
                  className="h-9 rounded-xl px-3 text-xs"
                  onClick={() => {
                    setEditing(true);
                    setSuccess(null);
                  }}
                >
                  ویرایش گزارش
                </Button>
              </div>
              <ReadValue label="موضوع تدریس" value={existingLog.topic} />
              <div className="space-y-1">
                <div className="text-sm font-medium text-slate-800">سرفصل‌های مربوط به این جلسه</div>
                {hasSyllabus && syllabus ? (
                  <SyllabusSearchSelect
                    syllabus={syllabus}
                    topicIds={covered.topicIds}
                    chapterIds={covered.chapterIds}
                    disabled
                    onChange={() => undefined}
                  />
                ) : (
                  <div className="whitespace-pre-wrap rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 text-sm text-slate-800">
                    {selectedSummary.join("\n") || covered.legacy || "برای این درس سرفصلی تعریف نشده است."}
                  </div>
                )}
              </div>
              <ReadValue label="فعالیت‌های انجام‌شده در این جلسه (اختیاری)" value={existingLog.activities} />
              <ReadValue label="یادداشت معلم (اختیاری)" value={existingLog.teacher_note} hint={TEACHER_ONLY_HINT} />
              <ReadValue label="یادداشت جلسه بعد (اختیاری)" value={existingLog.homework_note} hint={TEACHER_ONLY_HINT} />
            </>
          ) : null}

          {showForm ? (
            <>
              {existingLog ? (
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <span className="text-sm font-semibold text-slate-800">ویرایش گزارش</span>
                  <Button
                    type="button"
                    variant="secondary"
                    className="h-9 rounded-xl px-3 text-xs"
                    onClick={() => {
                      setTopic(existingLog.topic ?? "");
                      setActivities(existingLog.activities ?? "");
                      setTeacherNote(existingLog.teacher_note ?? "");
                      setHomeworkNote(existingLog.homework_note ?? "");
                      applyCovered(existingLog.chapters_note);
                      setEditing(false);
                    }}
                  >
                    انصراف
                  </Button>
                </div>
              ) : null}
              <Field
                label="موضوع تدریس"
                error={error === "موضوع تدریس الزامی است." && !topic.trim() ? error : undefined}
              >
                <Input
                  required
                  value={topic}
                  onChange={(e) => setTopic(e.target.value)}
                  invalid={error === "موضوع تدریس الزامی است." && !topic.trim()}
                />
              </Field>
              <div className="space-y-1.5">
                <div className="text-sm font-medium text-foreground/85">سرفصل‌های مربوط به این جلسه</div>
                {hasSyllabus && syllabus ? (
                  <SyllabusSearchSelect
                    syllabus={syllabus}
                    topicIds={topicIds}
                    chapterIds={chapterIds}
                    onChange={setCoveredIds}
                  />
                ) : (
                  <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-3.5 py-2.5 text-sm text-slate-500">
                    {subjectId
                      ? "برای این درس هنوز سرفصلی در بخش برنامه درسی ثبت نشده است."
                      : "ابتدا درس جلسه را انتخاب کنید."}
                  </div>
                )}
              </div>
              <Field label="فعالیت‌های انجام‌شده در این جلسه (اختیاری)">
                <Textarea rows={3} value={activities} onChange={(e) => setActivities(e.target.value)} />
              </Field>
              <Field label="یادداشت معلم (اختیاری)" hint={TEACHER_ONLY_HINT}>
                <Textarea rows={2} value={teacherNote} onChange={(e) => setTeacherNote(e.target.value)} />
              </Field>
              <Field label="یادداشت جلسه بعد (اختیاری)" hint={TEACHER_ONLY_HINT}>
                <Textarea rows={2} value={homeworkNote} onChange={(e) => setHomeworkNote(e.target.value)} />
              </Field>

              <div className="flex flex-wrap gap-2">
                <Button onClick={save} loading={saving}>
                  {existingLog ? "ذخیره تغییرات" : "ذخیره دفتر"}
                </Button>
              </div>
            </>
          ) : null}
        </div>
      </TeacherPanel>

      <ClassLogHistory
        classRoomId={classRoomId}
        subjectId={subjectId}
        selectedDate={date}
        onSelectDate={onHistoryDateSelect ?? (() => {})}
        refreshKey={historyRefreshKey}
      />
    </div>
  );
}
