"use client";

import Link from "next/link";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import { Field, Textarea } from "@/components/ui/Field";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { ToggleSwitch } from "@/components/ui/ToggleSwitch";
import { ApiError, apiDelete, apiGet, apiPatch, apiPost } from "@/lib/api";
import { mediaUrl } from "@/lib/media";
import { getActiveBranchId } from "@/lib/session-context";
import type { CannedTopicRow } from "@/components/messaging/CannedTopicEditor";

export type RelationshipOption = { code: string; label: string; sort_order: number };

export type PersonPayload = {
  id: number;
  first_name?: string | null;
  last_name?: string | null;
  full_name?: string | null;
  national_code?: string | null;
  is_foreign_national?: boolean;
  mobile?: string | null;
  gender?: string | null;
  birth_date?: string | null;
  avatar_path?: string | null;
  email?: string | null;
  personnel_code?: string | null;
  employment_type?: string | null;
  is_active?: boolean;
  is_alive?: boolean;
  landline?: string | null;
  occupation?: string | null;
  workplace?: string | null;
  address?: string | null;
  postal_code?: string | null;
  notes?: string | null;
  roles?: string[];
  student_id?: number | null;
  active_enrollment?: {
    branch_id: number;
    branch_name?: string | null;
    status?: string | null;
  } | null;
};

export type GuardianLinkRow = {
  id: number;
  relationship: string;
  relationship_label: string;
  is_primary: boolean;
  receives_notifications: boolean;
  notes?: string | null;
  person: PersonPayload | null;
};

const PARENT_CANNED_KEYS = ["student_absence", "invite_parent_to_school"];

function GuardianAvatar({ name, path }: { name: string; path?: string | null }) {
  const src = mediaUrl(path);
  const initial = name.trim().charAt(0) || "؟";
  if (src) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img src={src} alt="" className="h-10 w-10 rounded-full object-cover" />
    );
  }
  return (
    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-emerald-50 text-sm font-bold text-emerald-700">
      {initial}
    </div>
  );
}

function RowIconButton({
  title,
  href,
  onClick,
  disabled,
  tone = "default",
  children,
}: {
  title: string;
  href?: string;
  onClick?: () => void;
  disabled?: boolean;
  tone?: "default" | "danger" | "muted";
  children: ReactNode;
}) {
  const className = `inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--border)] bg-white transition disabled:cursor-not-allowed disabled:opacity-40 ${
    tone === "danger"
      ? "text-red-600 hover:bg-red-50"
      : tone === "muted"
        ? "text-slate-400"
        : "text-slate-600 hover:bg-slate-50 hover:text-teal-700"
  }`;
  if (href) {
    return (
      <Link href={href} title={title} className={className} aria-label={title}>
        {children}
      </Link>
    );
  }
  return (
    <button type="button" title={title} aria-label={title} disabled={disabled} onClick={onClick} className={className}>
      {children}
    </button>
  );
}

export function StudentGuardiansPanel({
  studentId,
  studentName,
}: {
  studentId: number;
  studentName: string;
}) {
  const [rows, setRows] = useState<GuardianLinkRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<GuardianLinkRow | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [togglingId, setTogglingId] = useState<number | null>(null);
  const [messageTarget, setMessageTarget] = useState<GuardianLinkRow | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await apiGet<{
        guardians: GuardianLinkRow[];
        relationships: RelationshipOption[];
      }>(`/students/${studentId}/guardians`);
      setRows(data.guardians ?? []);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری اولیا");
    } finally {
      setLoading(false);
    }
  }, [studentId]);

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

  const toggleNotify = async (row: GuardianLinkRow) => {
    setTogglingId(row.id);
    setError(null);
    setNotice(null);
    try {
      await apiPatch(`/students/${studentId}/guardians/${row.id}`, {
        receives_notifications: !row.receives_notifications,
      });
      setNotice(
        !row.receives_notifications
          ? `دریافت اعلان برای «${row.person?.full_name ?? "ولی"}» فعال شد.`
          : `دریافت اعلان برای «${row.person?.full_name ?? "ولی"}» غیرفعال شد.`,
      );
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "به‌روزرسانی اعلان ناموفق بود");
    } finally {
      setTogglingId(null);
    }
  };

  const confirmDelete = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    setError(null);
    try {
      await apiDelete(`/students/${studentId}/guardians/${deleteTarget.id}`);
      setNotice("ارتباط ولی حذف شد.");
      setDeleteTarget(null);
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "حذف ناموفق بود");
    } finally {
      setDeleting(false);
    }
  };

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

  return (
    <div className="space-y-4">
      {error ? <Alert tone="error">{error}</Alert> : null}
      {notice ? <Alert tone="success">{notice}</Alert> : null}

      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-lg font-bold text-slate-900">اولیای {studentName || "دانش‌آموز"}</h2>
          <p className="mt-1 text-sm text-[var(--muted)]">
            دریافت اعلان را از همین جدول مدیریت کنید یا برای ولی پیام بفرستید.
          </p>
        </div>
        <Link href={`/students/${studentId}/guardians/new`}>
          <Button>افزودن ولی</Button>
        </Link>
      </div>

      <div className="overflow-hidden rounded-[1.25rem] border border-[var(--border)] bg-white shadow-card">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[860px] text-right text-sm">
            <thead className="bg-slate-50/80 text-xs text-slate-500">
              <tr>
                <th className="px-4 py-3 font-medium">نام ولی</th>
                <th className="px-4 py-3 font-medium">نسبت</th>
                <th className="px-4 py-3 font-medium">کد ملی / کد اتباع</th>
                <th className="px-4 py-3 font-medium">موبایل</th>
                <th className="px-4 py-3 font-medium">دریافت اعلان</th>
                <th className="px-4 py-3 font-medium">عملیات</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-10 text-center text-slate-500">
                    هنوز ولی ثبت نشده است.
                  </td>
                </tr>
              ) : (
                rows.map((row) => {
                  const name = row.person?.full_name || "—";
                  return (
                    <tr key={row.id} className="hover:bg-slate-50/60">
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-3">
                          <GuardianAvatar name={name} path={row.person?.avatar_path} />
                          <div className="flex flex-wrap items-center gap-2">
                            <span className="font-semibold text-slate-900">{name}</span>
                            {row.is_primary ? (
                              <span className="rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-bold text-emerald-700">
                                اصلی
                              </span>
                            ) : null}
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-4 text-slate-700">{row.relationship_label}</td>
                      <td className="px-4 py-4">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="font-mono text-xs tabular-nums text-slate-800" dir="ltr">
                            {row.person?.national_code || "—"}
                          </span>
                          {row.person?.is_foreign_national ? (
                            <span className="rounded-full bg-orange-50 px-2 py-0.5 text-[10px] font-bold text-orange-600">
                              اتباع
                            </span>
                          ) : null}
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        {row.person?.mobile ? (
                          <span className="inline-flex items-center gap-1.5 font-mono text-xs text-slate-800" dir="ltr">
                            {row.person.mobile}
                            <svg viewBox="0 0 24 24" className="h-4 w-4 text-emerald-600" fill="currentColor" aria-hidden>
                              <path d="M17 1H7a2 2 0 0 0-2 2v18a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2zm-5 21a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z" />
                            </svg>
                          </span>
                        ) : (
                          <span className="text-slate-400">—</span>
                        )}
                      </td>
                      <td className="px-4 py-4">
                        <ToggleSwitch
                          checked={row.receives_notifications}
                          disabled={togglingId === row.id}
                          onChange={() => void toggleNotify(row)}
                        />
                      </td>
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-1.5">
                          <RowIconButton
                            title={row.person?.mobile ? "ارسال پیام" : "موبایل ثبت نشده"}
                            disabled={!row.person?.mobile}
                            tone={!row.person?.mobile ? "muted" : "default"}
                            onClick={() => {
                              setMessageTarget(row);
                              setNotice(null);
                            }}
                          >
                            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
                              <path d="M4 6h16v10H7l-3 3V6z" strokeLinejoin="round" />
                            </svg>
                          </RowIconButton>
                          <RowIconButton
                            title="ویرایش"
                            href={`/students/${studentId}/guardians/${row.id}/edit`}
                          >
                            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
                              <path d="M4 20h4l10-10-4-4L4 16v4z" strokeLinejoin="round" />
                            </svg>
                          </RowIconButton>
                          <RowIconButton title="حذف ارتباط" tone="danger" onClick={() => setDeleteTarget(row)}>
                            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
                              <path d="M5 7h14M10 11v6M14 11v6M8 7l1-2h6l1 2M7 7l1 13h8l1-13" strokeLinejoin="round" />
                            </svg>
                          </RowIconButton>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      <p className="text-xs text-[var(--muted)]">
        متن‌های پیش‌فرض پیام از{" "}
        <Link href="/messaging?tab=canned" className="font-semibold text-primary hover:underline">
          تنظیمات پیامک / پیام‌های آماده
        </Link>{" "}
        خوانده می‌شوند.
      </p>

      {messageTarget ? (
        <GuardianMessagePanel
          studentId={studentId}
          studentName={studentName}
          target={messageTarget}
          onClose={() => setMessageTarget(null)}
          onSent={(msg) => {
            setMessageTarget(null);
            setNotice(msg);
          }}
        />
      ) : null}

      <ConfirmDialog
        open={Boolean(deleteTarget)}
        title="حذف ارتباط ولی"
        message={
          deleteTarget
            ? `ارتباط «${deleteTarget.person?.full_name ?? "ولی"}» با این دانش‌آموز حذف شود؟ رکورد شخص حذف نمی‌شود.`
            : ""
        }
        confirmLabel="حذف ارتباط"
        loading={deleting}
        onConfirm={() => void confirmDelete()}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}

function GuardianMessagePanel({
  studentId,
  studentName,
  target,
  onClose,
  onSent,
}: {
  studentId: number;
  studentName: string;
  target: GuardianLinkRow;
  onClose: () => void;
  onSent: (message: string) => void;
}) {
  const [topics, setTopics] = useState<CannedTopicRow[]>([]);
  const [selectedKey, setSelectedKey] = useState("");
  const [text, setText] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  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 filtered = rows.filter((row) => PARENT_CANNED_KEYS.includes(row.key) && row.messages.length > 0);
        setTopics(filtered);
      })
      .catch(() => {
        if (!cancelled) setTopics([]);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    const first = topics[0]?.messages[0];
    if (!first) {
      setSelectedKey("");
      setText("");
      return;
    }
    setSelectedKey(`${topics[0].key}:${first.slot}`);
    setText(first.body.split("{student_name}").join(studentName || "فرزند شما"));
  }, [topics, studentName]);

  const send = async () => {
    if (!text.trim()) {
      setError("متن پیام خالی است.");
      return;
    }
    setSending(true);
    setError(null);
    try {
      await apiPost(`/students/${studentId}/guardians/${target.id}/send-message`, {
        body: text.trim(),
      });
      onSent(`پیام برای «${target.person?.full_name ?? "ولی"}» ارسال شد.`);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "ارسال ناموفق بود");
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center bg-slate-900/40 p-4 sm:items-center">
      <div className="max-h-[92vh] w-full max-w-lg overflow-y-auto rounded-2xl bg-white p-5 shadow-xl">
        <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.person?.full_name ?? "ولی"}</h3>
            <p className="text-xs text-slate-500" dir="ltr">
              {target.person?.mobile}
            </p>
          </div>
          <button type="button" onClick={onClose} className="text-sm text-slate-500">
            بستن
          </button>
        </div>

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

        {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.split("{student_name}").join(studentName || "فرزند شما"));
                        }}
                        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>
          ))
        )}

        <Field label="متن پیام">
          <Textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} />
        </Field>

        <div className="mt-4 flex gap-2">
          <Button onClick={() => void send()} disabled={sending || !text.trim()}>
            {sending ? "در حال ارسال…" : "ارسال"}
          </Button>
          <Button variant="secondary" onClick={onClose}>
            انصراف
          </Button>
        </div>
      </div>
    </div>
  );
}
