"use client";

import { useState } from "react";
import { apiFetch, getApproToken } from "@/lib/api";
import { APPRO_BASE_URL, MEDITATION_BASE_URL } from "@/lib/config";
import { usePaginated } from "@/lib/useResource";
import { DataTable, type Column } from "@/components/DataTable";
import {
  Badge,
  Button,
  Card,
  Modal,
  PageHeader,
  Pagination,
  Select,
  Spinner,
} from "@/components/ui";
import { EyeIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";

interface MeditationUser {
  id: number;
  full_name?: string;
  first_name?: string;
  last_name?: string;
  age?: number | null;
  gender?: number | null;
  email?: string | null;
  mobile?: string | null;
  identifier?: string | null;
  created_at?: string;
  answers_count?: number;
  questions_answered?: number;
}

interface ApproUser {
  id: number;
  uuid?: string;
  first_name?: string;
  last_name?: string;
  full_name?: string;
  age?: number | null;
  gender?: number | null;
  email?: string | null;
  mobile?: string | null;
  birthday?: string | null;
  created_at?: string;
}

interface SurveyAnswerItem {
  question_id: number;
  question?: string;
  type?: string;
  answers: { option_id: number; label: string }[];
}

interface DetailData {
  appro: ApproUser | null;
  survey_answers: SurveyAnswerItem[];
  answers_count?: number;
  questions_answered?: number;
}

const GENDER_LABELS: Record<number, string> = {
  1: "مرد",
  2: "زن",
};

function faDate(value?: string): string {
  if (!value) return "—";
  try {
    return toFa(new Date(value).toLocaleDateString("fa-IR"));
  } catch {
    return "—";
  }
}

export default function UsersPage() {
  const [answered, setAnswered] = useState<string>("");
  const { data, meta, page, setPage, loading, error, reload } =
    usePaginated<MeditationUser>("/admin/survey-users", {
      perPage: 20,
      query: answered ? { answered } : undefined,
    });

  const [detailUser, setDetailUser] = useState<MeditationUser | null>(null);
  const [detailData, setDetailData] = useState<DetailData | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);

  async function openDetail(user: MeditationUser) {
    setDetailOpen(true);
    setDetailLoading(true);
    setDetailUser(user);
    setDetailData(null);

    const [appro, survey] = await Promise.all([
      user.mobile
        ? apiFetch<{ data: ApproUser[] }>("/admin/users", {
            query: { mobile: user.mobile, per_page: 1 },
            baseUrl: APPRO_BASE_URL,
            headers: { Authorization: `Bearer ${getApproToken()}` },
          }).then((r) => r.data?.[0] ?? null)
        : Promise.resolve(null),
      apiFetch<{ survey_answers: SurveyAnswerItem[]; answers_count?: number; questions_answered?: number }>(
        `/admin/survey-users/${user.identifier || user.id}`,
        { baseUrl: MEDITATION_BASE_URL },
      ).catch(() => ({ survey_answers: [] } as { survey_answers: SurveyAnswerItem[] })),
    ]);

    // Sync approagency data back to meditation DB if user has null fields
    if (appro && user.mobile && (!user.first_name || user.age == null || user.gender == null)) {
      apiFetch(`/admin/survey-users/${user.identifier || user.id}`, {
        method: "PATCH",
        baseUrl: MEDITATION_BASE_URL,
        body: {
          first_name: appro.first_name,
          last_name: appro.last_name,
          age: appro.age,
          gender: appro.gender,
          birthday: appro.birthday,
          identifier: appro.uuid,
          email: appro.email,
        },
      }).catch(() => {}); // fire-and-forget
    }

    setDetailData({
      appro,
      survey_answers: survey.survey_answers ?? [],
      answers_count: survey.answers_count,
      questions_answered: survey.questions_answered,
    });
    setDetailLoading(false);
  }

  const columns: Column<MeditationUser>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    {
      key: "full_name",
      header: "نام",
      render: (r) => r.full_name || [r.first_name, r.last_name].filter(Boolean).join(" ") || "—",
    },
    {
      key: "questions_answered",
      header: "پاسخ به سوالات",
      className: "w-32",
      render: (r) =>
        r.questions_answered != null ? toFa(r.questions_answered) : "—",
    },
    {
      key: "created_at",
      header: "تاریخ ثبت‌نام",
      className: "w-32",
      render: (r) => faDate(r.created_at),
    },
  ];

  const a = detailData?.appro;
  const s = detailData;
  const userName = a
    ? a.full_name || [a.first_name, a.last_name].filter(Boolean).join(" ") || ""
    : detailUser
      ? detailUser.full_name || [detailUser.first_name, detailUser.last_name].filter(Boolean).join(" ") || ""
      : "";

  return (
    <div>
      <PageHeader
        title="کاربران نظرسنجی"
        subtitle="فهرست کاربران و پاسخ‌های نظرسنجی آن‌ها"
      />

      <div className="mb-4 flex items-center gap-3">
        <label className="text-sm text-muted">فیلتر:</label>
        <Select value={answered} onChange={(e) => { setAnswered(e.target.value); setPage(1); }}>
          <option value="">همه کاربران</option>
          <option value="1">پاسخ داده‌اند</option>
          <option value="0">پاسخ نداده‌اند</option>
        </Select>
      </div>

      <DataTable
        columns={columns}
        rows={data}
        loading={loading}
        error={error}
        onRetry={reload}
        emptyTitle="کاربری یافت نشد"
        emptyMessage="هنوز کاربری در نظرسنجی شرکت نکرده است."
        actions={(row) => (
          <Button variant="ghost" onClick={() => openDetail(row)} aria-label="جزئیات">
            <EyeIcon className="h-4 w-4" />
          </Button>
        )}
      />

      {meta && (
        <Pagination
          page={page}
          lastPage={meta.last_page}
          total={meta.total}
          onChange={setPage}
        />
      )}

      <Modal
        open={detailOpen}
        onClose={() => setDetailOpen(false)}
        title={userName ? `جزئیات کاربر — ${userName}` : "جزئیات کاربر"}
        footer={
          <Button variant="secondary" onClick={() => setDetailOpen(false)}>
            بستن
          </Button>
        }
      >
        {detailLoading && (
          <div className="flex justify-center py-8">
            <Spinner className="h-6 w-6" />
          </div>
        )}

        {s && !detailLoading && (
          <div className="flex flex-col gap-4">
            <div className="grid grid-cols-2 gap-3">
              <Card>
                <p className="text-sm text-muted">نام</p>
                <p className="mt-1 font-bold text-foreground">{userName || "—"}</p>
              </Card>
              <Card>
                <p className="text-sm text-muted">سن</p>
                <p className="mt-1 font-bold text-foreground">
                  {(a?.age ?? detailUser?.age) != null ? toFa(a?.age ?? detailUser!.age!) : "—"}
                </p>
              </Card>
              <Card>
                <p className="text-sm text-muted">جنسیت</p>
                <p className="mt-1 font-bold text-foreground">
                  {(a?.gender ?? detailUser?.gender) != null
                    ? GENDER_LABELS[a?.gender ?? detailUser!.gender!] ?? "—"
                    : "—"}
                </p>
              </Card>
              <Card>
                <p className="text-sm text-muted">تاریخ تولد</p>
                <p className="mt-1 font-bold text-foreground">
                  {a?.birthday ? faDate(a.birthday) : "—"}
                </p>
              </Card>
              <Card>
                <p className="text-sm text-muted">ایمیل</p>
                <p className="mt-1 font-bold text-foreground" dir="ltr">
                  {(a?.email ?? detailUser?.email) || "—"}
                </p>
              </Card>
              <Card>
                <p className="text-sm text-muted">موبایل</p>
                <p className="mt-1 font-bold text-foreground" dir="ltr">
                  {detailUser?.mobile || "—"}
                </p>
              </Card>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <Card>
                <p className="text-sm text-muted">تعداد پاسخ‌ها</p>
                <p className="mt-1 font-bold text-foreground">
                  {s.answers_count != null ? toFa(s.answers_count) : "—"}
                </p>
              </Card>
              <Card>
                <p className="text-sm text-muted">سوالات پاسخ داده شده</p>
                <p className="mt-1 font-bold text-foreground">
                  {s.questions_answered != null ? toFa(s.questions_answered) : "—"}
                </p>
              </Card>
            </div>

            {s.survey_answers.length > 0 ? (
              <div>
                <h3 className="mb-3 text-sm font-bold text-foreground">
                  پاسخ‌های نظرسنجی
                </h3>
                <div className="flex flex-col gap-2">
                  {s.survey_answers.map((item) => (
                    <div
                      key={item.question_id}
                      className="rounded-xl border border-border p-3"
                    >
                      <p className="text-sm font-medium text-foreground">
                        {item.question}
                      </p>
                      <div className="mt-1 flex flex-wrap gap-1">
                        {item.answers.map((a) => (
                          <Badge key={a.option_id} tone="primary">
                            {a.label}
                          </Badge>
                        ))}
                        {item.answers.length === 0 && (
                          <span className="text-xs text-muted">بدون پاسخ</span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <p className="text-center text-sm text-muted">
                این کاربر هنوز به هیچ سوالی پاسخ نداده است.
              </p>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
}
