"use client";

import Link from "next/link";
import { useLang } from "@/context/LanguageContext";
import {
  Card,
  EmptyState,
  LoadingArea,
  PageHeader,
  StatCard,
} from "@/components/ui";
import { useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import { WEEK_DAYS } from "@/lib/constants";
import {
  IconAlertTriangle,
  IconAward,
  IconBell,
  IconCalendar,
  IconCard,
  IconClipboard,
  IconUser,
  IconUserCheck,
  IconUsers,
  IconWallet,
} from "@/components/icons";

interface Overview {
  role: string;
  name: string;
  username: string | null;
  institution: { id: number; name: string; code: string; type: string };
  notices: {
    id: number;
    title: string;
    titleBn: string | null;
    body: string;
    publishDate: string;
    isPinned: boolean;
  }[];
  student: {
    roll: string;
    name: string;
    nameBn: string | null;
    guardianName: string;
    guardianPhone: string;
    status: string;
    className: string | null;
    classNameBn: string | null;
    sectionName: string | null;
    sectionNameBn: string | null;
    shiftName: string | null;
    shiftNameBn: string | null;
    attendanceMonth: { PRESENT: number; ABSENT: number; LEAVE: number; marked: number; percent: number | null };
    fees: { assigned: number; paid: number; due: number };
    marks: {
      examName: string;
      examNameBn: string | null;
      subjectName: string | null;
      subjectNameBn: string | null;
      fullMarks: number;
      cq: number | null;
      mcq: number | null;
      applied: number | null;
      total: number | null;
    }[];
    routine: {
      days: string[];
      startTime: string;
      endTime: string;
      subjectName: string | null;
      subjectNameBn: string | null;
      roomName: string | null;
      roomNameBn: string | null;
      teacherName: string | null;
    }[];
  } | null;
  staff: {
    employeeCode: string;
    name: string;
    designation: string;
    department: string | null;
    phone: string;
    joinDate: string | null;
    schedule: {
      days: string[];
      startTime: string;
      endTime: string;
      className: string | null;
      classNameBn: string | null;
      sectionName: string | null;
      sectionNameBn: string | null;
      subjectName: string | null;
      subjectNameBn: string | null;
      roomName: string | null;
      roomNameBn: string | null;
    }[];
  } | null;
}

function daysLabel(days: string[], t: { days: Record<string, string> }): string {
  return days
    .slice()
    .sort((a, b) => WEEK_DAYS.indexOf(a as never) - WEEK_DAYS.indexOf(b as never))
    .map((d) => t.days[d] ?? d)
    .join(", ");
}

export default function MemberDashboardPage() {
  const { t, locale } = useLang();
  const { data, loading, error } = useApi<Overview>("/api/me/overview");

  if (loading) return <LoadingArea label={t.common.loading} />;
  if (error || !data) return <EmptyState title={t.common.tryAgain} />;

  const roleLabel = t.status[data.role as keyof typeof t.status] ?? data.role;
  const isStudentView = data.role === "STUDENT" || data.role === "PARENT";
  const student = data.student;

  return (
    <div>
      <PageHeader
        title={`${roleLabel} — ${data.name}`}
        subtitle={`${data.institution.name} · ${data.institution.code}`}
      />

      {isStudentView && student && (
        <>
          {/* Student / child summary */}
          <div className="row g-3 mb-4">
            <div className="col-xl-3 col-sm-6">
              <StatCard
                label={t.me.attendanceMonth}
                value={student.attendanceMonth.percent == null ? "—" : `${student.attendanceMonth.percent}%`}
                icon={<IconUser />}
                accent="teal"
                hint={`P ${student.attendanceMonth.PRESENT} · A ${student.attendanceMonth.ABSENT} · L ${student.attendanceMonth.LEAVE}`}
              />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard
                label={t.portal.dashboard.totalPaid}
                value={formatBDT(student.fees.paid, locale)}
                icon={<IconWallet />}
                accent="blue"
                hint={`${t.portal.studentsPage.totalAssigned}: ${formatBDT(student.fees.assigned, locale)}`}
              />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard
                label={t.portal.dashboard.outstandingDue}
                value={formatBDT(student.fees.due, locale)}
                icon={<IconWallet />}
                accent="red"
              />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard
                label={t.me.classRoutine}
                value={String(student.routine.length)}
                icon={<IconCalendar />}
                accent="purple"
              />
            </div>
          </div>

          {/* Quick access to the member modules */}
          <div className="row g-2 mb-4">
            {[
              { href: "/me/results", label: t.me.navResults, icon: <IconAward className="svg-16" /> },
              { href: "/me/exams", label: t.me.navExams, icon: <IconCalendar className="svg-16" /> },
              { href: "/me/attendance", label: t.me.navAttendance, icon: <IconUserCheck className="svg-16" /> },
              { href: "/me/fees", label: t.me.navFees, icon: <IconWallet className="svg-16" /> },
              { href: "/me/notices", label: t.me.navNotices, icon: <IconBell className="svg-16" /> },
              { href: "/me/complaints", label: t.me.navComplaints, icon: <IconAlertTriangle className="svg-16" /> },
              { href: "/me/idcard", label: t.me.navIdCard, icon: <IconCard className="svg-16" /> },
              { href: "/me/profile", label: t.me.navProfile, icon: <IconUser className="svg-16" /> },
            ].map((m) => (
              <div className="col-auto" key={m.href}>
                <Link href={m.href} className="btn btn-sm btn-outline-secondary f-w-600">
                  {m.icon}
                  <span className="ms-1">{m.label}</span>
                </Link>
              </div>
            ))}
          </div>

          <div className="row g-3">
            {/* Profile */}
            <div className="col-xl-4">
              <Card title={t.me.profile}>
                <dl className="mb-0 ems-fs-13">
                  <dt className="text-muted f-w-600">{t.common.name}</dt>
                  <dd className="mb-2">
                    {student.name}
                    {student.nameBn && <span className="text-muted"> ({student.nameBn})</span>}
                    <span className="ems-roll-badge ms-2">{student.roll}</span>
                  </dd>
                  <dt className="text-muted f-w-600">{t.portal.studentsPage.classLabel}</dt>
                  <dd className="mb-2">
                    {student.className ? (locale === "bn" ? student.classNameBn : student.className) : "—"}
                    {student.sectionName ? ` · ${locale === "bn" ? student.sectionNameBn : student.sectionName}` : ""}
                    {student.shiftName ? ` · ${locale === "bn" ? student.shiftNameBn : student.shiftName}` : ""}
                  </dd>
                  <dt className="text-muted f-w-600">{t.portal.studentsPage.guardian}</dt>
                  <dd className="mb-2">
                    {student.guardianName}
                    <p className="mb-0 ems-fs-12 text-muted">{student.guardianPhone}</p>
                  </dd>
                  <dt className="text-muted f-w-600">{t.me.usernameLabel}</dt>
                  <dd className="mb-0">
                    <code className="ems-invoice-badge">{data.username}</code>
                  </dd>
                </dl>
              </Card>
            </div>

            {/* Class routine */}
            <div className="col-xl-8">
              <Card title={t.me.classRoutine}>
                {student.routine.length === 0 ? (
                  <EmptyState icon={<IconCalendar />} title={t.common.noData} />
                ) : (
                  <div className="table-responsive">
                    <table className="table table-hover align-middle mb-0">
                      <thead className="ems-table-head">
                        <tr>
                          <th>{t.common.days}</th>
                          <th>{t.me.time}</th>
                          <th>{t.common.subject}</th>
                          <th>{t.me.room}</th>
                          <th>{t.me.teacher}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {student.routine.map((r, i) => (
                          <tr key={i}>
                            <td className="ems-fs-12">{daysLabel(r.days, t)}</td>
                            <td className="f-w-600">{r.startTime}–{r.endTime}</td>
                            <td>{r.subjectName ? (locale === "bn" ? r.subjectNameBn : r.subjectName) : "—"}</td>
                            <td className="ems-fs-12">{r.roomName ? (locale === "bn" ? r.roomNameBn : r.roomName) : "—"}</td>
                            <td className="ems-fs-12">{r.teacherName ?? "—"}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </Card>
            </div>

            {/* Results */}
            <div className="col-xl-12">
              <Card title={t.me.results}>
                {student.marks.length === 0 ? (
                  <EmptyState icon={<IconUsers />} title={t.me.noResults} />
                ) : (
                  <div className="table-responsive">
                    <table className="table table-hover align-middle mb-0">
                      <thead className="ems-table-head">
                        <tr>
                          <th>{t.me.exam}</th>
                          <th>{t.common.subject}</th>
                          <th>{t.me.totalMarks}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {student.marks.map((m, i) => (
                          <tr key={i}>
                            <td className="f-w-600">{locale === "bn" ? m.examNameBn ?? m.examName : m.examName}</td>
                            <td>{m.subjectName ? (locale === "bn" ? m.subjectNameBn : m.subjectName) : "—"}</td>
                            <td>
                              <span className="f-w-800">{m.total ?? 0}</span>
                              <span className="text-muted"> / {m.fullMarks}</span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </Card>
            </div>
          </div>
        </>
      )}

      {data.staff && (
        <>
          {/* Quick access to the staff/teacher modules */}
          <div className="row g-2 mb-4">
            {[
              { href: "/me/marks", label: t.me.navMarks, icon: <IconClipboard className="svg-16" /> },
              { href: "/me/attendance", label: t.me.navAttendance, icon: <IconUserCheck className="svg-16" /> },
              { href: "/me/leaves", label: t.me.navLeaves, icon: <IconCalendar className="svg-16" /> },
              { href: "/me/payroll", label: t.me.navPayroll, icon: <IconWallet className="svg-16" /> },
              { href: "/me/lesson-plans", label: t.me.navLessonPlans, icon: <IconClipboard className="svg-16" /> },
              { href: "/me/notices", label: t.me.navNotices, icon: <IconBell className="svg-16" /> },
              { href: "/me/complaints", label: t.me.navComplaints, icon: <IconAlertTriangle className="svg-16" /> },
              { href: "/me/profile", label: t.me.navProfile, icon: <IconUser className="svg-16" /> },
            ].map((m) => (
              <div className="col-auto" key={m.href}>
                <Link href={m.href} className="btn btn-sm btn-outline-secondary f-w-600">
                  {m.icon}
                  <span className="ms-1">{m.label}</span>
                </Link>
              </div>
            ))}
          </div>

          <div className="row g-3">
          {/* Staff / teacher profile */}
          <div className="col-xl-4">
            <Card title={t.me.profile}>
              <dl className="mb-0 ems-fs-13">
                <dt className="text-muted f-w-600">{t.common.name}</dt>
                <dd className="mb-2">
                  {data.staff.name}
                  <span className="ems-roll-badge ms-2">{data.staff.employeeCode}</span>
                </dd>
                <dt className="text-muted f-w-600">{t.common.designation}</dt>
                <dd className="mb-2">
                  {t.designations[data.staff.designation as keyof typeof t.designations] ?? data.staff.designation}
                  {data.staff.department && (
                    <p className="mb-0 ems-fs-12 text-muted">
                      {t.designations[data.staff.department as keyof typeof t.designations] ?? data.staff.department}
                    </p>
                  )}
                </dd>
                <dt className="text-muted f-w-600">{t.common.phone}</dt>
                <dd className="mb-2">{data.staff.phone}</dd>
                <dt className="text-muted f-w-600">{t.me.usernameLabel}</dt>
                <dd className="mb-0">
                  <code className="ems-invoice-badge">{data.username}</code>
                </dd>
              </dl>
            </Card>
          </div>

          {/* Teaching schedule (teachers) */}
          <div className="col-xl-8">
            <Card title={t.me.mySchedule}>
              {data.staff.schedule.length === 0 ? (
                <EmptyState icon={<IconCalendar />} title={t.common.noData} />
              ) : (
                <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{t.common.days}</th>
                        <th>{t.me.time}</th>
                        <th>{t.portal.studentsPage.classLabel}</th>
                        <th>{t.common.subject}</th>
                        <th>{t.me.room}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.staff.schedule.map((r, i) => (
                        <tr key={i}>
                          <td className="ems-fs-12">{daysLabel(r.days, t)}</td>
                          <td className="f-w-600">{r.startTime}–{r.endTime}</td>
                          <td>
                            {r.className ? (locale === "bn" ? r.classNameBn : r.className) : "—"}
                            {r.sectionName ? ` · ${locale === "bn" ? r.sectionNameBn : r.sectionName}` : ""}
                          </td>
                          <td>{r.subjectName ? (locale === "bn" ? r.subjectNameBn : r.subjectName) : "—"}</td>
                          <td className="ems-fs-12">{r.roomName ? (locale === "bn" ? r.roomNameBn : r.roomName) : "—"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          </div>
        </div>
        </>
      )}

      {/* Notices */}
      <div className="mt-4">
        <Card title={t.portal.noticesPage.title}>
          {data.notices.length === 0 ? (
            <EmptyState icon={<IconBell />} title={t.common.noData} />
          ) : (
            <ul className="list-group list-group-flush">
              {data.notices.map((n) => (
                <li className="list-group-item px-0" key={n.id}>
                  <div className="d-flex justify-content-between align-items-start gap-2">
                    <div>
                      <p className="mb-1 f-w-700">
                        {n.isPinned && <span className="badge badge-primary me-1">{t.me.pinned}</span>}
                        {locale === "bn" ? n.titleBn ?? n.title : n.title}
                      </p>
                      <p className="mb-0 ems-fs-12 text-muted" style={{ whiteSpace: "pre-wrap" }}>
                        {n.body}
                      </p>
                    </div>
                    <small className="text-muted text-nowrap">{formatDate(n.publishDate, locale)}</small>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>
    </div>
  );
}
