"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import type { CheckIn } from "@/lib/checkins";

export function AdminCheckIns() {
  const [checkins, setCheckins] = useState<CheckIn[]>([]);
  const [loading, setLoading] = useState(true);

  async function loadCheckIns() {
    setLoading(true);
    const response = await fetch("/api/checkins", { cache: "no-store" });
    const data = (await response.json()) as { checkins: CheckIn[] };
    setCheckins(data.checkins);
    setLoading(false);
  }

  useEffect(() => {
    let active = true;

    async function loadInitialCheckIns() {
      const response = await fetch("/api/checkins", { cache: "no-store" });
      const data = (await response.json()) as { checkins: CheckIn[] };

      if (active) {
        setCheckins(data.checkins);
        setLoading(false);
      }
    }

    void loadInitialCheckIns();

    return () => {
      active = false;
    };
  }, []);

  return (
    <div className="mt-8 rounded-lg border border-[#d9d0bf] bg-white p-6 shadow-sm">
      <div className="flex flex-col justify-between gap-3 border-b border-[#d9d0bf] pb-5 sm:flex-row sm:items-center">
        <div>
          <h2 className="text-2xl font-semibold text-[#274739]">Wellness check-ins</h2>
          <p className="mt-1 text-sm text-[#5e675f]">Mood, stress, goals, concerns, and recommended journeys.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link
            href="/api/checkins/export"
            className="rounded-full border border-[#cfc4b2] px-4 py-2 text-sm font-semibold text-[#274739]"
          >
            Export CSV
          </Link>
          <button
            type="button"
            onClick={() => void loadCheckIns()}
            className="rounded-full bg-[#274739] px-4 py-2 text-sm font-semibold text-white"
          >
            {loading ? "Loading..." : "Refresh"}
          </button>
        </div>
      </div>

      {loading ? (
        <p className="py-6 text-sm text-[#5e675f]">Loading check-ins...</p>
      ) : checkins.length === 0 ? (
        <p className="py-6 text-sm text-[#5e675f]">No wellness check-ins submitted yet.</p>
      ) : (
        <div className="admin-table-wrap">
          <div className="admin-table admin-table--checkins" role="table">
            <div className="admin-table-head" role="row">
              <div role="columnheader" className="lg:text-center">
                Name
              </div>
              <div role="columnheader" className="lg:text-center">
                Mood / Stress
              </div>
              <div role="columnheader" className="lg:text-center">
                Goal
              </div>
              <div role="columnheader" className="lg:text-center">
                Concern
              </div>
              <div role="columnheader" className="lg:text-center">
                Recommendation
              </div>
            </div>
            <div className="admin-table-body">
              {checkins.map((checkin, index) => (
                <div
                  key={checkin.id}
                  className={`admin-table-row border-l-[#d9d0bf] ${index % 2 === 1 ? "admin-table-row--zebra" : ""}`}
                  role="row"
                >
                  <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                    <p className="min-w-0 truncate text-sm font-semibold text-[#274739]" title={checkin.name}>
                      {checkin.name}
                    </p>
                    <p className="min-w-0 truncate text-xs text-[#5e675f]" title={checkin.email}>
                      {checkin.email}
                    </p>
                  </div>
                  <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                    <p className="min-w-0 truncate text-sm capitalize text-[#274739]" title={checkin.mood}>
                      <span className="admin-table-mobile-label">Mood</span>
                      {checkin.mood}
                    </p>
                    <p className="text-xs tabular-nums text-[#5e675f]">Stress {checkin.stressLevel}/10</p>
                  </div>
                  <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                    <p className="min-w-0 truncate text-sm text-[#274739]" title={checkin.goal}>
                      <span className="admin-table-mobile-label">Goal</span>
                      {checkin.goal}
                    </p>
                    <p className="min-w-0 truncate text-xs text-[#5e675f]" title={checkin.duration}>
                      {checkin.duration}
                    </p>
                  </div>
                  <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                    <p className="min-w-0 truncate text-sm text-[#5e675f]" title={checkin.concern}>
                      <span className="admin-table-mobile-label">Concern</span>
                      {checkin.concern}
                    </p>
                  </div>
                  <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                    <p className="text-[10px] font-bold uppercase tracking-[0.1em] text-[#9a6b2d]">
                      <span className="admin-table-mobile-label">Rec</span>
                      {checkin.recommendationType}
                    </p>
                    <p
                      className="min-w-0 truncate text-sm font-medium text-[#274739]"
                      title={checkin.recommendationTitle}
                    >
                      {checkin.recommendationTitle}
                    </p>
                    <p
                      className="min-w-0 truncate text-xs text-[#5e675f]"
                      title={checkin.recommendationReason}
                    >
                      {checkin.recommendationReason}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
