"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { type CannedTopicRow } from "@/components/messaging/CannedTopicEditor";
import { apiGet } from "@/lib/api";
import { getActiveBranchId } from "@/lib/session-context";
import type {
  AlertRow,
  ClassRow,
  ListFilter,
  SmsFilter,
  StudentRow,
  StudentStatusFilter,
} from "@/lib/attendance-report";
import {
  CompletionChip,
  DeliveryChip,
  EmptyState,
  SmsChip,
  StatusChip,
  fa,
  severityTone,
} from "./AttendancePrimitives";
import { faDate } from "./dateRange";

export type MessageRole = "parent" | "manager" | "teacher" | "bulk";
export type MessageTarget = { name: string; role: MessageRole; hint?: string };

export const STUDENT_FILTER_OPTIONS: Array<[StudentStatusFilter, string]> = [
  ["all", "همه"],
  ["unchecked", "ثبت‌نشده"],
  ["present", "حاضر"],
  ["late", "تأخیر"],
  ["absent", "غایب"],
  ["temporary_exit", "خروج موقت"],
  ["unjustified", "بدون توجیه"],
  ["atrisk", "در معرض خطر"],
  ["sms", "دارای پیامک"],
  ["virtual", "کلاس مجازی"],
];

export const LIST_FILTER_OPTIONS: Array<[ListFilter, string]> = [
  ["all", "همه لیست‌ها"],
  ["complete", "تکمیل"],
  ["pending", "ناقص یا پرنشده"],
  ["partial", "ناقص"],
  ["empty", "پرنشده"],
  ["delayed", "ارسال دیر"],
  ["virtual", "کلاس مجازی"],
];

export const SMS_FILTER_OPTIONS: Array<[SmsFilter, string]> = [
  ["all", "همه"],
  ["delivered", "تحویل‌شده"],
  ["queued", "در صف ارسال"],
  ["failed", "ناموفق"],
  ["none", "بدون پیامک"],
];

const ROLE_CANNED_TOPICS: Record<MessageRole, string[]> = {
  parent: ["student_absence", "invite_parent_to_school"],
  teacher: ["teacher_attendance_form_delay", "invite_teacher_to_office"],
  manager: ["teacher_attendance_form_delay"],
  bulk: [
    "student_absence",
    "invite_parent_to_school",
    "teacher_attendance_form_delay",
    "invite_teacher_to_office",
  ],
};

export function Overlay({
  onClose,
  children,
  align = "center",
}: {
  onClose: () => void;
  children: React.ReactNode;
  align?: "center" | "bottom";
}) {
  return (
    <div
      className={`fixed inset-0 z-50 flex bg-slate-900/35 backdrop-blur-[2px] ${
        align === "bottom" ? "items-end justify-center" : "items-center justify-center p-4"
      }`}
    >
      <button type="button" className="absolute inset-0" aria-label="بستن" onClick={onClose} />
      {children}
    </div>
  );
}

export function Drawer({
  kicker,
  title,
  subtitle,
  footer,
  onClose,
  children,
}: {
  kicker?: string;
  title: string;
  subtitle?: string;
  footer?: React.ReactNode;
  onClose: () => void;
  children: React.ReactNode;
}) {
  return (
    <div className="fixed inset-0 z-50 flex justify-start bg-slate-900/30 backdrop-blur-[2px]">
      <button type="button" className="h-full flex-1" aria-label="بستن" onClick={onClose} />
      <aside className="flex h-full w-full max-w-md flex-col bg-white shadow-2xl">
        <div className="flex-1 overflow-y-auto p-5">
          <div className="mb-4 flex items-start justify-between gap-3">
            <div>
              {kicker ? (
                <p className="text-[11px] font-bold text-teal-700">{kicker}</p>
              ) : null}
              <h3 className="text-lg font-black">{title}</h3>
              {subtitle ? <p className="text-xs text-slate-500">{subtitle}</p> : null}
            </div>
            <button type="button" onClick={onClose} className="text-sm text-slate-500">
              بستن
            </button>
          </div>
          {children}
        </div>
        {footer ? (
          <div className="flex gap-2 border-t border-slate-100 bg-white/95 p-4">{footer}</div>
        ) : null}
      </aside>
    </div>
  );
}

export function ChipGroup<T extends string>({
  options,
  value,
  counts,
  onChange,
}: {
  options: Array<[T, string]>;
  value: T;
  counts?: Partial<Record<string, number>>;
  onChange: (value: T) => void;
}) {
  return (
    <div className="flex flex-wrap gap-1.5">
      {options.map(([key, label]) => {
        const count = counts?.[key];
        return (
          <button
            key={key}
            type="button"
            onClick={() => onChange(key)}
            className={`rounded-full px-3 py-1.5 text-[11px] font-bold ring-1 transition ${
              value === key
                ? "bg-teal-600 text-white ring-teal-600"
                : "bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"
            }`}
          >
            {label}
            {typeof count === "number" ? ` · ${fa(count)}` : ""}
          </button>
        );
      })}
    </div>
  );
}

export function GroupSendButton({
  picking,
  count,
  onStart,
  onSend,
  onCancel,
}: {
  picking: boolean;
  count: number;
  onStart: () => void;
  onSend: () => void;
  onCancel: () => void;
}) {
  if (!picking) {
    return (
      <Button variant="secondary" onClick={onStart}>
        ارسال گروهی
      </Button>
    );
  }
  return (
    <div className="flex flex-wrap gap-2">
      <Button onClick={onSend}>{count > 0 ? `ارسال پیام · ${fa(count)} نفر` : "ارسال پیام"}</Button>
      <Button variant="secondary" onClick={onCancel}>
        انصراف
      </Button>
    </div>
  );
}

export function SendMsgBtn({ onClick }: { onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="shrink-0 rounded-lg bg-white px-2 py-1 text-[10px] font-bold text-teal-700 ring-1 ring-teal-200"
    >
      ارسال پیام
    </button>
  );
}

export function SmsStat({
  label,
  value,
  tone,
  time,
  href,
}: {
  label: string;
  value: number;
  tone: "emerald" | "amber" | "rose" | "slate";
  time: string;
  href?: string;
}) {
  const map = {
    emerald: "bg-emerald-50 text-emerald-800",
    amber: "bg-amber-50 text-amber-800",
    rose: "bg-rose-50 text-rose-800",
    slate: "bg-slate-100 text-slate-700",
  };
  const body = (
    <>
      <p className="text-[11px] font-bold">{label}</p>
      <p className="text-lg font-black tabular-nums">{fa(value)}</p>
      <p className="text-[10px] opacity-70">آخرین: {time}</p>
    </>
  );
  if (!href) {
    return <div className={`rounded-2xl px-3 py-2 ${map[tone]}`}>{body}</div>;
  }
  return (
    <Link
      href={href}
      className={`block rounded-2xl px-3 py-2 text-right transition hover:brightness-95 ${map[tone]}`}
    >
      {body}
    </Link>
  );
}

function timeOf(value: string | null): string {
  if (!value) return "—";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return value.slice(11, 16) || "—";
  return parsed.toLocaleTimeString("fa-IR", { hour: "2-digit", minute: "2-digit" });
}

/** ریز داده‌های دانش‌آموزان؛ هر ردیف یک (جلسه، دانش‌آموز) است. */
export function StudentsTable({
  rows,
  loading,
  showDate,
  onOpen,
  onMessage,
  picking,
  selectedIds,
  onToggle,
  onToggleAll,
}: {
  rows: StudentRow[];
  loading?: boolean;
  showDate?: boolean;
  onOpen: (row: StudentRow) => void;
  onMessage: (target: MessageTarget) => void;
  picking: boolean;
  selectedIds: string[];
  onToggle: (id: string) => void;
  onToggleAll: (ids: string[]) => void;
}) {
  const allIds = rows.map((row) => row.id);
  const allOn = allIds.length > 0 && allIds.every((id) => selectedIds.includes(id));
  const columns = 8 + (showDate ? 1 : 0) + (picking ? 1 : 0);

  return (
    <div className="overflow-x-auto rounded-2xl border border-slate-100">
      <table className="min-w-full text-sm">
        <thead className="bg-slate-50 text-xs text-slate-500">
          <tr>
            {picking ? (
              <th className="px-3 py-2.5 text-right font-bold">
                <input
                  type="checkbox"
                  checked={allOn}
                  onChange={() => onToggleAll(allOn ? [] : allIds)}
                  className="h-4 w-4 accent-teal-600"
                />
              </th>
            ) : null}
            {showDate ? <th className="px-3 py-2.5 text-right font-bold">تاریخ</th> : null}
            <th className="px-3 py-2.5 text-right font-bold">دانش‌آموز</th>
            <th className="px-3 py-2.5 text-right font-bold">کلاس</th>
            <th className="px-3 py-2.5 text-right font-bold">شعبه</th>
            <th className="px-3 py-2.5 text-right font-bold">زنگ / درس</th>
            <th className="px-3 py-2.5 text-right font-bold">نوع کلاس</th>
            <th className="px-3 py-2.5 text-right font-bold">وضعیت</th>
            <th className="px-3 py-2.5 text-right font-bold">پیامک</th>
            <th className="px-3 py-2.5 text-right font-bold">اقدام</th>
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr>
              <td colSpan={columns} className="px-3 py-8 text-center text-slate-400">
                در حال بارگذاری…
              </td>
            </tr>
          ) : rows.length === 0 ? (
            <tr>
              <td colSpan={columns} className="px-3 py-8 text-center text-slate-400">
                موردی با این فیلتر نیست.
              </td>
            </tr>
          ) : (
            rows.map((row) => (
              <tr key={row.id} className="border-t border-slate-100 hover:bg-slate-50/80">
                {picking ? (
                  <td className="px-3 py-2.5">
                    <input
                      type="checkbox"
                      checked={selectedIds.includes(row.id)}
                      onChange={() => onToggle(row.id)}
                      className="h-4 w-4 accent-teal-600"
                    />
                  </td>
                ) : null}
                {showDate ? (
                  <td className="whitespace-nowrap px-3 py-2.5 text-[11px] text-slate-500">
                    {faDate(row.date)}
                  </td>
                ) : null}
                <td className="px-3 py-2.5">
                  <button type="button" onClick={() => onOpen(row)} className="text-right">
                    <span className="block font-bold text-slate-800">{row.student_name}</span>
                    <span className="text-[11px] text-slate-400">{row.student_code ?? "—"}</span>
                  </button>
                </td>
                <td className="px-3 py-2.5">
                  {row.class_name ?? "—"}
                  <span className="block text-[11px] text-slate-400">
                    {row.grade_level_name ?? "—"}
                  </span>
                </td>
                <td className="px-3 py-2.5">{row.branch_name ?? "—"}</td>
                <td className="px-3 py-2.5">
                  <span className="block text-xs font-bold text-slate-700">
                    {row.period_title ?? "—"}
                  </span>
                  <span className="text-[11px] text-slate-400">{row.subject_name ?? "—"}</span>
                </td>
                <td className="px-3 py-2.5">
                  <DeliveryChip mode={row.delivery_mode} label={row.delivery_mode_label} compact />
                </td>
                <td className="px-3 py-2.5">
                  <StatusChip status={row.status} label={row.status_label} />
                  {row.late_minutes ? (
                    <span className="mt-1 block text-[10px] tabular-nums text-amber-700">
                      {fa(row.late_minutes)} دقیقه
                    </span>
                  ) : null}
                  {row.unjustified ? (
                    <span className="mt-1 block text-[10px] font-bold text-rose-700">
                      بدون توجیه
                    </span>
                  ) : null}
                </td>
                <td className="px-3 py-2.5">
                  <SmsChip state={row.sms_state} label={row.sms_state_label} />
                </td>
                <td className="px-3 py-2.5">
                  <div className="flex flex-wrap gap-1.5">
                    <button
                      type="button"
                      onClick={() => onOpen(row)}
                      className="rounded-lg bg-white px-2.5 py-1 text-[11px] font-bold text-slate-600 ring-1 ring-slate-200"
                    >
                      پروفایل
                    </button>
                    {picking ? null : (
                      <SendMsgBtn
                        onClick={() =>
                          onMessage({
                            name: `ولی ${row.student_name}`,
                            role: "parent",
                            hint: [row.class_name, row.delivery_mode_label]
                              .filter(Boolean)
                              .join(" · "),
                          })
                        }
                      />
                    )}
                  </div>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
}

/** تکمیل لیست حضور به تفکیک جلسه (معلم · کلاس · زنگ · نوع کلاس). */
export function ClassesTable({
  rows,
  loading,
  showDate,
  onMessage,
  picking,
  selectedIds,
  onToggle,
  onToggleAll,
}: {
  rows: ClassRow[];
  loading?: boolean;
  showDate?: boolean;
  onMessage: (target: MessageTarget) => void;
  picking: boolean;
  selectedIds: string[];
  onToggle: (id: string) => void;
  onToggleAll: (ids: string[]) => void;
}) {
  const allIds = rows.map((row) => row.id);
  const allOn = allIds.length > 0 && allIds.every((id) => selectedIds.includes(id));
  const columns = 8 + (showDate ? 1 : 0) + (picking ? 1 : 0);

  return (
    <div className="overflow-x-auto rounded-2xl border border-slate-100">
      <table className="min-w-full text-sm">
        <thead className="bg-slate-50 text-xs text-slate-500">
          <tr>
            {picking ? (
              <th className="px-3 py-2.5 text-right font-bold">
                <input
                  type="checkbox"
                  checked={allOn}
                  onChange={() => onToggleAll(allOn ? [] : allIds)}
                  className="h-4 w-4 accent-teal-600"
                />
              </th>
            ) : null}
            {showDate ? <th className="px-3 py-2.5 text-right font-bold">تاریخ</th> : null}
            <th className="px-3 py-2.5 text-right font-bold">معلم</th>
            <th className="px-3 py-2.5 text-right font-bold">کلاس / درس</th>
            <th className="px-3 py-2.5 text-right font-bold">زنگ</th>
            <th className="px-3 py-2.5 text-right font-bold">نوع کلاس</th>
            <th className="px-3 py-2.5 text-right font-bold">ثبت</th>
            <th className="px-3 py-2.5 text-right font-bold">تأخیر ارسال</th>
            <th className="px-3 py-2.5 text-right font-bold">وضعیت</th>
            <th className="px-3 py-2.5 text-right font-bold" />
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr>
              <td colSpan={columns} className="px-3 py-8 text-center text-slate-400">
                در حال بارگذاری…
              </td>
            </tr>
          ) : rows.length === 0 ? (
            <tr>
              <td colSpan={columns} className="px-3 py-8 text-center text-slate-400">
                موردی با این فیلتر نیست.
              </td>
            </tr>
          ) : (
            rows.map((row) => (
              <tr key={row.id} className="border-t border-slate-100">
                {picking ? (
                  <td className="px-3 py-2.5">
                    <input
                      type="checkbox"
                      checked={selectedIds.includes(row.id)}
                      onChange={() => onToggle(row.id)}
                      className="h-4 w-4 accent-teal-600"
                    />
                  </td>
                ) : null}
                {showDate ? (
                  <td className="whitespace-nowrap px-3 py-2.5 text-[11px] text-slate-500">
                    {faDate(row.date)}
                  </td>
                ) : null}
                <td className="px-3 py-2.5 font-bold">{row.teacher_name}</td>
                <td className="px-3 py-2.5">
                  {row.class_name ?? "—"}
                  <span className="block text-[11px] text-slate-400">
                    {row.subject_name ?? "—"}
                  </span>
                </td>
                <td className="px-3 py-2.5">
                  <span className="block text-xs font-bold text-slate-700">
                    {row.period_title ?? "—"}
                  </span>
                  <span className="text-[11px] tabular-nums text-slate-400">
                    {row.starts_at ?? "—"}
                  </span>
                </td>
                <td className="px-3 py-2.5">
                  <DeliveryChip mode={row.delivery_mode} label={row.delivery_mode_label} compact />
                </td>
                <td className="px-3 py-2.5 tabular-nums">
                  {fa(row.recorded)} / {fa(row.total)}
                  {row.unchecked > 0 ? (
                    <span className="block text-[10px] text-slate-400">
                      {fa(row.unchecked)} ثبت‌نشده
                    </span>
                  ) : null}
                </td>
                <td className="px-3 py-2.5 text-xs">
                  {row.is_delayed ? (
                    <span className="font-bold text-amber-800">
                      {row.delay_minutes === null
                        ? "ارسال نشده"
                        : `${fa(row.delay_minutes)} دقیقه دیر`}
                    </span>
                  ) : (
                    <span className="text-emerald-700">به‌موقع</span>
                  )}
                  <span className="block text-[11px] text-slate-400">
                    {row.submitted_at ? timeOf(row.submitted_at) : "فرم ارسال نشده"}
                  </span>
                </td>
                <td className="px-3 py-2.5">
                  <CompletionChip completion={row.completion} label={row.completion_label} />
                </td>
                <td className="px-3 py-2.5">
                  {picking || !row.teacher_id ? null : (
                    <SendMsgBtn
                      onClick={() =>
                        onMessage({
                          name: row.teacher_name,
                          role: "teacher",
                          hint: [row.class_name, row.period_title, row.delivery_mode_label]
                            .filter(Boolean)
                            .join(" · "),
                        })
                      }
                    />
                  )}
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
}

export function AlertsList({
  rows,
  loading,
  onMessage,
  picking,
  selectedIds,
  onToggle,
}: {
  rows: AlertRow[];
  loading?: boolean;
  onMessage: (target: MessageTarget) => void;
  picking: boolean;
  selectedIds: number[];
  onToggle: (id: number) => void;
}) {
  if (loading) {
    return <EmptyState>در حال بارگذاری هشدارها…</EmptyState>;
  }
  if (rows.length === 0) {
    return <EmptyState>هشداری در محدوده انتخابی نیست.</EmptyState>;
  }
  return (
    <ul className="space-y-2">
      {rows.map((alert) => (
        <li key={alert.id} className="rounded-2xl bg-white p-4 ring-1 ring-slate-100">
          <div className="flex flex-wrap items-start justify-between gap-2">
            <div className="flex min-w-0 items-start gap-2">
              {picking ? (
                <input
                  type="checkbox"
                  checked={selectedIds.includes(alert.id)}
                  onChange={() => onToggle(alert.id)}
                  className="mt-1 h-4 w-4 accent-teal-600"
                />
              ) : null}
              <div className="min-w-0">
                <p className="font-bold text-slate-900">{alert.title}</p>
                {alert.detail ? (
                  <p className="mt-1 text-sm text-slate-600">{alert.detail}</p>
                ) : null}
                <div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] text-slate-400">
                  {alert.student_name ? <span>{alert.student_name}</span> : null}
                  {alert.delivery_mode ? (
                    <DeliveryChip mode={alert.delivery_mode} compact />
                  ) : null}
                  {alert.created_at ? <span>{timeOf(alert.created_at)}</span> : null}
                </div>
              </div>
            </div>
            <div className="flex flex-col items-end gap-2">
              <span
                className={`rounded-full px-2.5 py-1 text-[11px] font-bold ring-1 ${severityTone(alert.severity)}`}
              >
                {alert.branch_name ?? "شعبه"}
              </span>
              {picking ? null : (
                <SendMsgBtn
                  onClick={() =>
                    onMessage({
                      name: `مدیر ${alert.branch_name ?? "شعبه"}`,
                      role: "manager",
                      hint: alert.title,
                    })
                  }
                />
              )}
            </div>
          </div>
        </li>
      ))}
    </ul>
  );
}

export function StudentDrawer({
  row,
  absenceCap,
  onClose,
  onMessage,
}: {
  row: StudentRow;
  absenceCap: number;
  onClose: () => void;
  onMessage: (target: MessageTarget) => void;
}) {
  return (
    <Drawer
      kicker="پروفایل انضباطی"
      title={row.student_name}
      subtitle={[row.class_name, row.branch_name, faDate(row.date)].filter(Boolean).join(" · ")}
      onClose={onClose}
      footer={
        <Button
          block
          onClick={() =>
            onMessage({
              name: `ولی ${row.student_name}`,
              role: "parent",
              hint: row.class_name ?? undefined,
            })
          }
        >
          ارسال پیام به ولی
        </Button>
      }
    >
      <div className="mb-4 flex flex-wrap gap-2">
        <StatusChip status={row.status} label={row.status_label} />
        <DeliveryChip mode={row.delivery_mode} label={row.delivery_mode_label} />
        <SmsChip state={row.sms_state} label={`پیامک: ${row.sms_state_label}`} />
      </div>
      <dl className="grid grid-cols-2 gap-2 text-sm">
        <InfoCell label="کد دانش‌آموز" value={row.student_code ?? "—"} />
        <InfoCell label="شماره ولی" value={row.parent_phone ?? "—"} />
        <InfoCell label="زنگ" value={row.period_title ?? "—"} />
        <InfoCell label="درس" value={row.subject_name ?? "—"} />
        <InfoCell label="معلم" value={row.teacher_name ?? "—"} />
        <InfoCell
          label="تأخیر ورود"
          value={row.late_minutes ? `${fa(row.late_minutes)} دقیقه` : "—"}
        />
        <InfoCell
          label="غیبت ترم"
          value={`${fa(row.absence_count)} از ${fa(absenceCap)} روز`}
        />
        <InfoCell label="ثبت معلم" value={row.teacher_recorded ? "ثبت شده" : "ثبت‌نشده"} />
        <InfoCell label="زمان ثبت" value={timeOf(row.recorded_at)} />
        <InfoCell label="ورود از گیت" value={timeOf(row.gate_entry_at)} />
      </dl>
      {row.note ? (
        <p className="mt-3 rounded-2xl bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
          {row.note}
        </p>
      ) : null}
      {row.unjustified ? (
        <p className="mt-3 rounded-2xl bg-rose-50 px-3 py-2 text-sm text-rose-800">
          این مورد توضیح یا گواهی ثبت‌شده‌ای ندارد و در گزارش «بدون توجیه» شمرده می‌شود.
        </p>
      ) : null}
      {row.at_risk ? (
        <p className="mt-3 rounded-2xl bg-orange-50 px-3 py-2 text-sm text-orange-800">
          غیبت‌های این دانش‌آموز به سقف سیاست گزارشگیری رسیده است.
        </p>
      ) : null}
    </Drawer>
  );
}

function InfoCell({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-2xl bg-slate-50 px-3 py-2">
      <p className="text-[11px] text-slate-400">{label}</p>
      <p className="font-bold text-slate-800">{value}</p>
    </div>
  );
}

export function Pager({
  page,
  perPage,
  total,
  loading,
  onPage,
}: {
  page: number;
  perPage: number;
  total: number;
  loading?: boolean;
  onPage: (page: number) => void;
}) {
  const lastPage = Math.max(1, Math.ceil(total / Math.max(perPage, 1)));
  if (total === 0) return null;

  const first = (page - 1) * perPage + 1;
  const last = Math.min(total, page * perPage);

  return (
    <div className="mt-3 flex flex-wrap items-center justify-between gap-2">
      <p className="text-[11px] text-slate-500">
        نمایش {fa(first)} تا {fa(last)} از {fa(total)} ردیف
      </p>
      <div className="flex items-center gap-2">
        <Button
          variant="secondary"
          disabled={page <= 1 || loading}
          onClick={() => onPage(page - 1)}
        >
          قبلی
        </Button>
        <span className="text-xs font-bold tabular-nums text-slate-600">
          {fa(page)} / {fa(lastPage)}
        </span>
        <Button
          variant="secondary"
          disabled={page >= lastPage || loading}
          onClick={() => onPage(page + 1)}
        >
          بعدی
        </Button>
      </div>
    </div>
  );
}

function cannedFallbackTopics(role: MessageRole): CannedTopicRow[] {
  return [
    {
      key: role,
      label: "پیام‌های آماده",
      used_in: "",
      messages: [
        {
          slot: 1,
          title: "پیام آزاد",
          body: "",
        },
      ],
    },
  ];
}

export function MessageModal({
  target,
  onClose,
  onSend,
}: {
  target: MessageTarget;
  onClose: () => void;
  onSend?: (text: string) => void;
}) {
  const [topics, setTopics] = useState<CannedTopicRow[]>([]);
  const [selectedKey, setSelectedKey] = useState("");
  const [text, setText] = useState("");

  useEffect(() => {
    let cancelled = false;
    const branchId = getActiveBranchId();
    const query = new URLSearchParams({ filled_only: "1" });
    if (branchId) query.set("branch_id", String(branchId));
    void apiGet<CannedTopicRow[]>(`/messaging/canned?${query.toString()}`)
      .then((rows) => {
        if (cancelled) return;
        const allowed = ROLE_CANNED_TOPICS[target.role];
        const filtered = rows.filter((row) => allowed.includes(row.key) && row.messages.length > 0);
        setTopics(filtered.length ? filtered : cannedFallbackTopics(target.role));
      })
      .catch(() => {
        if (!cancelled) setTopics(cannedFallbackTopics(target.role));
      });
    return () => {
      cancelled = true;
    };
  }, [target.role]);

  useEffect(() => {
    const first = topics[0]?.messages[0];
    if (!first) {
      setSelectedKey("");
      setText("");
      return;
    }
    setSelectedKey(`${topics[0].key}:${first.slot}`);
    setText(first.body);
  }, [topics]);

  const selected = topics
    .flatMap((topic) => topic.messages.map((item) => ({ topic, item })))
    .find((row) => `${row.topic.key}:${row.item.slot}` === selectedKey);

  return (
    <Overlay onClose={onClose}>
      <div className="relative z-10 w-full max-w-lg rounded-[1.6rem] bg-white p-5 shadow-2xl">
        <div className="mb-3 flex items-start justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold text-teal-700">ارسال پیام</p>
            <h3 className="text-base font-black">{target.name}</h3>
            {target.hint ? <p className="text-xs text-slate-500">{target.hint}</p> : null}
          </div>
          <button type="button" onClick={onClose} className="text-sm text-slate-500">
            بستن
          </button>
        </div>
        {topics.length === 0 ? (
          <p className="mb-3 text-xs text-slate-500">در حال بارگذاری پیام‌های پیش‌فرض…</p>
        ) : (
          topics.map((topic) => (
            <div key={topic.key} className="mb-3">
              <p className="mb-2 text-xs font-bold text-slate-500">{topic.label}</p>
              <ul className="grid max-h-40 grid-cols-2 gap-1.5 overflow-y-auto">
                {topic.messages.map((item) => {
                  const id = `${topic.key}:${item.slot}`;
                  return (
                    <li key={id}>
                      <button
                        type="button"
                        onClick={() => {
                          setSelectedKey(id);
                          setText(item.body);
                        }}
                        className={`h-full w-full rounded-xl px-2.5 py-2 text-right text-[11px] font-bold leading-5 ${
                          selectedKey === id
                            ? "bg-teal-600 text-white"
                            : "bg-slate-50 text-slate-700 hover:bg-teal-50"
                        }`}
                      >
                        {item.title || `پیام ${item.slot}`}
                      </button>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))
        )}
        <label className="block text-xs font-bold text-slate-500">
          متن پیام {selected ? `· ${selected.item.title}` : ""}
          <textarea
            value={text}
            onChange={(event) => setText(event.target.value)}
            rows={4}
            className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm"
          />
        </label>
        <div className="mt-3">
          <Alert tone="info">
            ارسال از صف ماژول اطلاع‌رسانی انجام می‌شود؛ اتصال این دکمه به Intake در گام بعدی فعال
            می‌شود.
          </Alert>
        </div>
        <div className="mt-4 flex gap-2">
          <Button
            disabled={!onSend}
            onClick={() => {
              onSend?.(text);
              onClose();
            }}
          >
            ارسال
          </Button>
          <Button variant="secondary" onClick={onClose}>
            انصراف
          </Button>
        </div>
      </div>
    </Overlay>
  );
}
