"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  DatePicker,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  LoadingArea,
  Select,
  StatCard,
  StatusBadge,
  Textarea,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { IconBook, IconCheck, IconClipboard, IconEdit, IconPlus, IconTrash } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface Week {
  id: number;
  weekNo: number;
  topic: string;
  homework: string | null;
  isDone: boolean;
}

interface Plan {
  id: number;
  classItemId: number | null;
  className: string | null;
  classNameBn: string | null;
  sectionItemId: number | null;
  sectionName: string | null;
  subjectItemId: number | null;
  subjectName: string | null;
  subjectNameBn: string | null;
  chapter: string;
  topics: string | null;
  startDate: string;
  endDate: string | null;
  totalPeriods: number;
  completedPeriods: number;
  status: string;
  weeks: Week[];
}

interface SchedulePair {
  classItemId: number | null;
  sectionItemId: number | null;
  subjectItemId: number | null;
  className: string | null;
  sectionName: string | null;
  subjectName: string | null;
}

const emptyForm = {
  classItemId: "",
  sectionItemId: "",
  subjectItemId: "",
  chapter: "",
  topics: "",
  startDate: "",
  endDate: "",
  totalPeriods: "10",
  completedPeriods: "0",
};

const emptyWeek = { topic: "", homework: "", isDone: false };

/** Teacher's own lesson plans — full self-service CRUD (create, edit,
    weekly breakdown, progress updates, delete) scoped to the classes and
    subjects they actually teach, mirroring the admin Lesson Plans page. */
export default function MeLessonPlansPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ plans: Plan[]; schedule: SchedulePair[] }>("/api/me/lesson-plans");

  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<Plan | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [weeks, setWeeks] = useState<Array<{ topic: string; homework: string; isDone: boolean }>>([]);
  const [saving, setSaving] = useState(false);

  const [progressOpen, setProgressOpen] = useState<Plan | null>(null);
  const [progressValue, setProgressValue] = useState("0");
  const [progressSaving, setProgressSaving] = useState(false);

  const L = t.portal.lessonPlanPage;
  const schedule = data?.schedule ?? [];

  /** classes/sections/subjects offered in the form = the teacher's own pairs */
  const myClasses = useMemo(() => {
    const map = new Map<number, string>();
    for (const p of schedule) if (p.classItemId) map.set(p.classItemId, p.className ?? "—");
    return [...map.entries()].map(([id, name]) => ({ id, name }));
  }, [schedule]);
  const mySections = useMemo(() => {
    const set = new Map<number, string>();
    for (const p of schedule) {
      if (p.classItemId && String(p.classItemId) === form.classItemId && p.sectionItemId)
        set.set(p.sectionItemId, p.sectionName ?? "—");
    }
    return [...set.entries()].map(([id, name]) => ({ id, name }));
  }, [schedule, form.classItemId]);
  const mySubjects = useMemo(() => {
    const set = new Map<number, string>();
    for (const p of schedule) {
      if (p.classItemId && String(p.classItemId) === form.classItemId && p.subjectItemId)
        set.set(p.subjectItemId, p.subjectName ?? "—");
    }
    return [...set.entries()].map(([id, name]) => ({ id, name }));
  }, [schedule, form.classItemId]);

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function openCreate() {
    setEditing(null);
    setForm({ ...emptyForm, startDate: new Date().toISOString().slice(0, 10) });
    setWeeks([]);
    setFormOpen(true);
  }

  function openEdit(p: Plan) {
    setEditing(p);
    setForm({
      classItemId: p.classItemId ? String(p.classItemId) : "",
      sectionItemId: p.sectionItemId ? String(p.sectionItemId) : "",
      subjectItemId: p.subjectItemId ? String(p.subjectItemId) : "",
      chapter: p.chapter,
      topics: p.topics ?? "",
      startDate: p.startDate,
      endDate: p.endDate ?? "",
      totalPeriods: String(p.totalPeriods),
      completedPeriods: String(p.completedPeriods),
    });
    setWeeks(p.weeks.map((w) => ({ topic: w.topic, homework: w.homework ?? "", isDone: w.isDone })));
    setFormOpen(true);
  }

  async function save() {
    setSaving(true);
    try {
      const payload = {
        ...form,
        classItemId: form.classItemId || null,
        sectionItemId: form.sectionItemId || null,
        subjectItemId: form.subjectItemId || null,
        totalPeriods: Number(form.totalPeriods) || 0,
        completedPeriods: Number(form.completedPeriods) || 0,
        endDate: form.endDate || null,
        weeks,
      };
      if (editing) {
        await api(`/api/me/lesson-plans/${editing.id}`, { method: "PUT", body: JSON.stringify(payload) });
        notify("success", L.planUpdated);
      } else {
        await api("/api/me/lesson-plans", { method: "POST", body: JSON.stringify(payload) });
        notify("success", L.planCreated);
      }
      setFormOpen(false);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSaving(false);
    }
  }

  function openProgress(p: Plan) {
    setProgressOpen(p);
    setProgressValue(String(p.completedPeriods));
  }

  async function saveProgress() {
    if (!progressOpen) return;
    setProgressSaving(true);
    try {
      await api(`/api/me/lesson-plans/${progressOpen.id}`, {
        method: "PUT",
        body: JSON.stringify({ completedPeriods: Number(progressValue) || 0 }),
      });
      setProgressOpen(null);
      reload();
      notify("success", L.progressSaved);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setProgressSaving(false);
    }
  }

  async function remove(p: Plan) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/me/lesson-plans/${p.id}`, { method: "DELETE" });
      notify("success", t.common.deletedSuccessfully);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    }
  }

  if (loading) return <LoadingArea label={t.common.loading} />;
  const plans = data?.plans ?? [];
  const stats = {
    total: plans.length,
    inProgress: plans.filter((p) => p.status === "IN_PROGRESS").length,
    completed: plans.filter((p) => p.status === "COMPLETED").length,
    periods: plans.reduce((sum, p) => sum + p.completedPeriods, 0),
  };

  return (
    <div>
      <PageHeader
        title={t.me.lessonPlansTitle}
        subtitle={t.me.lessonPlansSubtitle}
        action={
          <Button onClick={openCreate}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{L.newPlan}</span>
          </Button>
        }
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <div className="row g-3 mb-4">
        <div className="col-xl-3 col-sm-6">
          <StatCard label={L.totalPlans} value={String(stats.total)} icon={<IconBook />} accent="teal" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.status.IN_PROGRESS} value={String(stats.inProgress)} icon={<IconEdit />} accent="sky" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.status.COMPLETED} value={String(stats.completed)} icon={<IconCheck />} accent="purple" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={L.periodsTaught} value={String(stats.periods)} icon={<IconBook />} accent="orange" />
        </div>
      </div>

      {plans.length === 0 ? (
        <div className="card">
          <EmptyState
            icon={<IconClipboard />}
            title={t.me.noLessonPlans}
            action={
              <Button onClick={openCreate}>
                <IconPlus className="svg-16" />
                <span className="ms-1">{L.newPlan}</span>
              </Button>
            }
          />
        </div>
      ) : (
        <div className="row g-3">
          {plans.map((p) => {
            const pct = p.totalPeriods > 0 ? Math.min(100, Math.round((p.completedPeriods / p.totalPeriods) * 100)) : 0;
            return (
              <div className="col-xl-6" key={p.id}>
                <Card>
                  <div className="d-flex justify-content-between align-items-start gap-2">
                    <div className="min-w-0">
                      <h5 className="f-w-700 mb-1">{p.chapter}</h5>
                      <p className="mb-1 ems-fs-12 text-muted">
                        {(locale === "bn" && p.subjectNameBn ? p.subjectNameBn : p.subjectName) ?? "—"}
                        {p.className ? ` · ${(locale === "bn" && p.classNameBn ? p.classNameBn : p.className)}` : ""}
                        {p.sectionName ? ` (${p.sectionName})` : ""}
                      </p>
                      <p className="mb-2 ems-fs-12 text-muted">
                        {formatDate(p.startDate, locale)}
                        {p.endDate ? ` — ${formatDate(p.endDate, locale)}` : ""}
                      </p>
                    </div>
                    <div className="d-flex flex-shrink-0">
                      <button className="btn btn-soft-primary btn-sm me-1" onClick={() => openProgress(p)} type="button" title={L.updateProgress}>
                        <IconCheck className="svg-16" />
                      </button>
                      <button className="btn btn-soft-secondary btn-sm me-1" onClick={() => openEdit(p)} type="button">
                        <IconEdit className="svg-16" />
                      </button>
                      <button className="btn btn-soft-danger btn-sm" onClick={() => remove(p)} type="button">
                        <IconTrash className="svg-16" />
                      </button>
                    </div>
                  </div>

                  {p.topics && <p className="mb-2 ems-fs-13">{p.topics}</p>}

                  {/* Progress */}
                  <div className="mb-2">
                    <div className="d-flex justify-content-between ems-fs-12 mb-1">
                      <span className="text-muted">
                        {L.progress}: {p.completedPeriods}/{p.totalPeriods} {L.periods}
                      </span>
                      <span className="f-w-700">{pct}%</span>
                    </div>
                    <div className="progress ems-progress-thin">
                      <div
                        className="progress-bar bg-success"
                        role="progressbar"
                        style={{ width: `${pct}%` }}
                        aria-valuenow={pct}
                        aria-valuemin={0}
                        aria-valuemax={100}
                      />
                    </div>
                  </div>

                  <div className="d-flex align-items-center gap-2">
                    <StatusBadge status={p.status} label={t.lessonStatuses[p.status as keyof typeof t.lessonStatuses] ?? p.status} />
                    <span className="ems-fs-11 text-muted">
                      {p.weeks.filter((w) => w.isDone).length}/{p.weeks.length} {L.weeksDone}
                    </span>
                  </div>
                </Card>
              </div>
            );
          })}
        </div>
      )}

      {/* Create/edit modal */}
      <Modal
        open={formOpen}
        onClose={() => setFormOpen(false)}
        title={editing ? L.editPlan : L.newPlan}
        wide
      >
        <div className="row">
          <div className="col-md-6">
            <Input label={L.chapter} value={form.chapter} onChange={(e) => setForm({ ...form, chapter: e.target.value })} placeholder={L.chapterPlaceholder} />
          </div>
          <div className="col-md-6">
            <Select
              label={t.categories.CLASS}
              value={form.classItemId}
              onChange={(e) => setForm({ ...form, classItemId: e.target.value, sectionItemId: "", subjectItemId: "" })}
            >
              <option value="">—</option>
              {myClasses.map((i) => (
                <option key={i.id} value={i.id}>{i.name}</option>
              ))}
            </Select>
          </div>
          <div className="col-md-4">
            <Select label={t.categories.SECTION} value={form.sectionItemId} onChange={(e) => setForm({ ...form, sectionItemId: e.target.value })}>
              <option value="">—</option>
              {mySections.map((i) => (
                <option key={i.id} value={i.id}>{i.name}</option>
              ))}
            </Select>
          </div>
          <div className="col-md-4">
            <Select label={t.categories.SUBJECT} value={form.subjectItemId} onChange={(e) => setForm({ ...form, subjectItemId: e.target.value })}>
              <option value="">—</option>
              {mySubjects.map((i) => (
                <option key={i.id} value={i.id}>{i.name}</option>
              ))}
            </Select>
          </div>
          <div className="col-md-4">
            <DatePicker label={L.startLabel} value={form.startDate} onChange={(e) => setForm({ ...form, startDate: e.target.value })} />
          </div>
          <div className="col-md-4">
            <DatePicker label={`${L.endLabel} (${t.common.optional})`} value={form.endDate} onChange={(e) => setForm({ ...form, endDate: e.target.value })} />
          </div>
          <div className="col-md-4">
            <Input label={L.totalPeriods} type="number" min="0" value={form.totalPeriods} onChange={(e) => setForm({ ...form, totalPeriods: e.target.value })} />
          </div>
          <div className="col-md-12">
            <Textarea label={`${L.topics} (${t.common.optional})`} value={form.topics} onChange={(e) => setForm({ ...form, topics: e.target.value })} />
          </div>
        </div>

        {/* Weekly breakdown editor */}
        <label className="col-form-label pt-0 f-w-600">{L.weeklyBreakdown}</label>
        {weeks.map((w, i) => (
          <div className="row g-2 align-items-center mb-2" key={i}>
            <div className="col-auto ems-fs-12 f-w-700 text-muted">#{i + 1}</div>
            <div className="col">
              <input
                className="form-control form-control-sm"
                placeholder={L.weekTopic}
                value={w.topic}
                onChange={(e) => setWeeks(weeks.map((x, j) => (j === i ? { ...x, topic: e.target.value } : x)))}
              />
            </div>
            <div className="col">
              <input
                className="form-control form-control-sm"
                placeholder={L.homework}
                value={w.homework}
                onChange={(e) => setWeeks(weeks.map((x, j) => (j === i ? { ...x, homework: e.target.value } : x)))}
              />
            </div>
            <div className="col-auto">
              <input
                type="checkbox"
                className="form-check-input mt-0"
                checked={w.isDone}
                title={L.weekDone}
                onChange={(e) => setWeeks(weeks.map((x, j) => (j === i ? { ...x, isDone: e.target.checked } : x)))}
              />
            </div>
            <div className="col-auto">
              <button
                type="button"
                className="btn btn-soft-danger btn-sm"
                onClick={() => setWeeks(weeks.filter((_, j) => j !== i))}
              >
                <IconTrash className="svg-14" />
              </button>
            </div>
          </div>
        ))}
        <Button size="sm" variant="secondary" onClick={() => setWeeks([...weeks, { ...emptyWeek }])}>
          <IconPlus className="svg-14" />
          <span className="ms-1">{L.addWeek}</span>
        </Button>

        <div className="d-flex justify-content-end gap-2 mt-3">
          <Button variant="secondary" onClick={() => setFormOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button onClick={save} loading={saving} disabled={!form.chapter.trim() || !form.startDate}>
            {t.common.save}
          </Button>
        </div>
      </Modal>

      {/* Progress modal */}
      <Modal open={!!progressOpen} onClose={() => setProgressOpen(null)} title={L.updateProgress}>
        {progressOpen && (
          <>
            <h6 className="f-w-700 mb-1">{progressOpen.chapter}</h6>
            <p className="ems-fs-12 text-muted mb-3">
              {(locale === "bn" && progressOpen.subjectNameBn ? progressOpen.subjectNameBn : progressOpen.subjectName) ?? ""} · {progressOpen.completedPeriods}/{progressOpen.totalPeriods} {L.periods}
            </p>
            <Input
              label={L.completedPeriods}
              type="number"
              min="0"
              max={progressOpen.totalPeriods}
              value={progressValue}
              onChange={(e) => setProgressValue(e.target.value)}
            />
            <div className="d-flex justify-content-end gap-2">
              <Button variant="secondary" onClick={() => setProgressOpen(null)}>
                {t.common.cancel}
              </Button>
              <Button onClick={saveProgress} loading={progressSaving}>
                {t.common.save}
              </Button>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}
