"use client";

import { useMemo, useState } from "react";
import { Chip, Progress } from "@nextui-org/react";
import {
  FaCalendarDays,
  FaUsers,
  FaCircleInfo,
  FaChevronRight,
  FaBullseye,
  FaFilter,
  FaCalendarWeek,
  FaUserTie,
  FaClipboardList,
} from "react-icons/fa6";
import { useRouter } from "next/navigation";
import { FaBuilding } from "react-icons/fa";

import {
  FieldConfig,
  ProjectOverview,
} from "@/types/participant-list/provisional-types";
import Button from "@/components/common/button";
import CriteriaAccordion from "@/components/pages/client/participant-list/common/criteria-accordion";
import DayColumn from "@/components/pages/client/participant-list/overview/partials/day-column";
import DownloadScreenerButton from "@/components/pages/client/participant-list/overview/partials/download-screener-button";
import ExportSchedulingButton from "@/components/pages/client/participant-list/overview/partials/export-scheduling-button";
import SessionDetailsModal from "@/components/pages/client/participant-list/overview/partials/session-details-modal";
import Section from "@/components/pages/client/participant-list/common/section";
import StatCard from "@/components/pages/client/participant-list/overview/partials/stat-card";
import AddClientContactModal from "@/components/pages/client/participant-list/overview/partials/add-client-contact-modal";
import {
  formatDate,
  groupSlotsByDay,
} from "@/components/pages/client/participant-list/overview/utils";
import { useTimezone } from "@/components/pages/client/participant-list/common/timezone-context";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";

type ProjectOverviewProps = {
  project: ProjectOverview;
  canEdit: boolean;
  visibilityControls: FieldConfig[];
};

function ProjectOverviewHome({
  project,
  canEdit,
  visibilityControls,
}: ProjectOverviewProps) {
  const { mode, routes } = useClientPortalAuth();
  const router = useRouter();
  const { timezone } = useTimezone();
  const [selectedSessionId, setSelectedSessionId] = useState<string | null>(
    null,
  );
  const [isAddContactOpen, setIsAddContactOpen] = useState(false);

  const {
    reference,
    client: company,
    title,
    stats,
    projectManager,
    recruitmentProgress,
    criteria,
    sessionSlots,
  } = project;

  // The BE returns a flat session list; group it into days in the viewer's
  // selected timezone so days/"today" are correct for any zone.
  const slotDays = useMemo(
    () => groupSlotsByDay(sessionSlots, timezone),
    [sessionSlots, timezone],
  );

  const progressPct =
    (recruitmentProgress.filled / recruitmentProgress.total) * 100;

  const initials = projectManager.name
    .split(" ")
    .map((n) => n[0])
    .join("");

  const handleContinueToParticipants = () => {
    router.push(routes.participants);
  };

  return (
    <div className="mx-auto max-w-3xl px-4 py-6 sm:px-6 lg:px-8 font-noto">
      <header className="space-y-2">
        <div className="flex flex-wrap items-center gap-2 text-sm">
          <Chip
            classNames={{
              base: "bg-midnightBlue font-bold text-xs",
            }}
            color="primary"
            size="sm"
          >
            {reference}
          </Chip>
          <span className="flex items-center gap-1.5 text-gray-500 dark:text-neutral-400 text-xs">
            <FaBuilding className="size-3" />
            {company}
          </span>
        </div>

        <h1 className="font-inter text-2xl sm:text-3xl font-black text-gray-900 dark:text-white">
          {title}
        </h1>

        <p className="text-sm text-gray-500 dark:text-neutral-400">
          Shared by {projectManager.name}
        </p>
      </header>

      <div className="mt-6 flex gap-3 rounded-sm bg-midnightBlue dark:bg-midnightBlue/50 p-4">
        <FaCircleInfo className="mt-0.5 h-4 w-4 shrink-0 text-white" />
        <p className="text-sm text-white leading-relaxed">
          Please review the project details below. Once you&apos;re happy with
          the setup, head to the participant list to review and sign off on
          profiles as they come in.
        </p>
      </div>

      <div className="mt-6 grid grid-cols-2 lg:grid-cols-3 gap-1">
        <StatCard
          icon={<FaCalendarDays />}
          label="Start date"
          value={formatDate(stats.startDate)}
        />
        <StatCard
          icon={<FaCalendarDays />}
          label="End date"
          value={formatDate(stats.endDate)}
        />
        <StatCard
          icon={<FaUsers />}
          label="Profiles accepted / target"
          value={
            <span>
              {stats.filledQuota} <span>/</span> <span>{stats.quota}</span>
            </span>
          }
        />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-1">
        <StatCard
          icon={<FaClipboardList />}
          label="Format of research"
          value={
            project.formatOfResearch.length > 0
              ? project.formatOfResearch.join(", ")
              : "Not specified"
          }
        />
        <StatCard
          icon={<FaClipboardList />}
          label="Type of study"
          value={
            project.typeOfStudy.length > 0
              ? project.typeOfStudy.join(", ")
              : "Not specified"
          }
        />
      </div>

      <div className="mt-8">
        <Section
          icon={<FaUserTie className="h-3 w-3" />}
          label="PFR project manager"
        >
          <div className="flex items-start gap-3">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-midnightBlue text-white text-sm font-bold">
              {initials}
            </div>
            <div className="min-w-0 flex-1">
              <p className="[overflow-wrap:anywhere] font-semibold text-gray-900 dark:text-white text-sm">
                {projectManager.name}
              </p>
              <p className="text-xs text-gray-500 dark:text-neutral-400">
                {projectManager.role}
              </p>
              <p className="mt-1 [overflow-wrap:anywhere] text-sm text-gray-700 dark:text-gray-200">
                {projectManager.phone?.trim() || "Phone number not provided."}
              </p>
            </div>
          </div>
        </Section>
      </div>

      <div className="mt-6">
        <Section
          icon={<FaBullseye className="h-3 w-3" />}
          label="Client review progress"
        >
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <p className="font-semibold text-gray-900 dark:text-white text-sm">
                Published profiles
              </p>
              <p className="text-sm font-bold text-gray-900 dark:text-white">
                {recruitmentProgress.filled}{" "}
                <span className="text-gray-400 dark:text-gray-300">/</span>{" "}
                <span>{recruitmentProgress.total}</span>
                <span className="ml-1 text-xs font-normal text-gray-400 dark:text-gray-300">
                  accepted
                </span>
              </p>
            </div>

            <Progress
              aria-label="Published profile acceptance progress"
              classNames={{
                base: "w-full",
                track: "bg-gray-200 dark:bg-neutral-700",
                indicator: "bg-midnightBlue",
              }}
              radius="full"
              value={progressPct}
            />
          </div>
        </Section>
      </div>

      <div className="mt-6">
        <Section
          icon={<FaFilter className="h-3 w-3" />}
          label="Screening criteria"
        >
          <CriteriaAccordion
            groups={criteria}
            topContent={
              mode === "client" ? <DownloadScreenerButton /> : undefined
            }
            variant="overview"
          />
        </Section>
      </div>

      <div className="mt-6">
        <Section
          icon={<FaCalendarWeek className="h-3 w-3" />}
          label="Session slots"
        >
          <div className="flex justify-end pb-2">
            {mode === "client" && <ExportSchedulingButton />}
          </div>
          {slotDays.length === 0 ? (
            <p className="py-6 text-center text-sm text-gray-400 dark:text-gray-300">
              No sessions scheduled yet.
            </p>
          ) : (
            <div className="flex divide-x divide-gray-200 dark:divide-neutral-700 overflow-x-auto -mx-1">
              {slotDays.map((day) => (
                <DayColumn
                  key={day.date}
                  day={day}
                  onSlotClick={setSelectedSessionId}
                />
              ))}
            </div>
          )}
          <SessionDetailsModal
            canEdit={canEdit}
            sessionId={selectedSessionId}
            visibilityControls={visibilityControls}
            onClose={() => setSelectedSessionId(null)}
          />
        </Section>
      </div>

      <div className="mt-8 mb-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 rounded-sm bg-white dark:bg-neutral-800 p-5 shadow-sm border border-gray-200 dark:border-neutral-700">
        <div>
          <p className="font-bold text-gray-900 dark:text-white">
            Ready to review participants?
          </p>
          <p className="text-sm text-gray-500 dark:text-neutral-400">
            {recruitmentProgress.filled} profiles accepted -{" "}
            {recruitmentProgress.toReview} awaiting your decision
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {canEdit && (
            <Button
              btnLabel="Request client contact"
              customVariant="transparent-black"
              onClick={() => setIsAddContactOpen(true)}
            />
          )}
          <Button
            btnLabel="View participants"
            customVariant="client"
            endContent={<FaChevronRight className="h-3 w-3" />}
            onClick={handleContinueToParticipants}
          />
        </div>
      </div>
      {canEdit && (
        <AddClientContactModal
          isOpen={isAddContactOpen}
          onClose={() => setIsAddContactOpen(false)}
        />
      )}
    </div>
  );
}

export default ProjectOverviewHome;
