'use client';

import { useState } from 'react';
import { cn } from '@/lib/utils/cn';
import type { Directory } from './directory';
import { Icon } from './icons';

/**
 * The design's Users | Teams segmented checklists (`.ca-notif-segmented-group`), each with a
 * search and "select all" (of the rows shown). Used by install permissions and notification
 * recipients.
 */
export function PeoplePicker({
  directory,
  userIds,
  teamIds,
  onChange,
  idPrefix,
}: {
  directory: Directory;
  userIds: string[];
  teamIds: string[];
  onChange: (next: { userIds: string[]; teamIds: string[] }) => void;
  idPrefix: string;
}) {
  const [tab, setTab] = useState<'users' | 'teams'>('users');
  const [userQ, setUserQ] = useState('');
  const [teamQ, setTeamQ] = useState('');

  const uq = userQ.trim().toLowerCase();
  const tq = teamQ.trim().toLowerCase();
  const users = directory.members.filter(
    (m) => !uq || m.name.toLowerCase().includes(uq) || m.email.toLowerCase().includes(uq),
  );
  const teams = directory.teams.filter((t) => !tq || t.name.toLowerCase().includes(tq));

  const toggle = (list: string[], id: string, on: boolean) =>
    on ? [...new Set([...list, id])] : list.filter((x) => x !== id);
  const allUsers = users.length > 0 && users.every((u) => userIds.includes(u.userId));
  const allTeams = teams.length > 0 && teams.every((t) => teamIds.includes(t.id));

  if (directory.status === 'loading') {
    return <p className="crm-fs-8 crm-text-muted">Loading users and teams…</p>;
  }
  if (directory.status === 'error') {
    return (
      <p className="crm-fs-8 crm-text-danger" role="alert">
        Couldn’t load users and teams. {directory.error}
      </p>
    );
  }

  return (
    <>
      <div className="ca-notif-segmented-group crm-mb-3" role="tablist">
        {(['users', 'teams'] as const).map((k) => (
          <button
            key={k}
            type="button"
            role="tab"
            aria-selected={tab === k}
            className={cn('ca-notif-segment-btn', tab === k && 'active')}
            onClick={() => setTab(k)}
          >
            {k === 'users' ? `Users (${userIds.length})` : `Teams (${teamIds.length})`}
          </button>
        ))}
      </div>

      <div className="ca-notif-subpanel" hidden={tab !== 'users'}>
        <div className="ca-notif-search-wrap crm-mb-3">
          <span className="ca-notif-search-icon">
            <Icon name="search" size={14} />
          </span>
          <input
            type="search"
            className="input ca-notif-search-input"
            placeholder="Search users"
            autoComplete="off"
            aria-label="Search users"
            value={userQ}
            onChange={(e) => setUserQ(e.target.value)}
          />
        </div>
        <div className="ca-notif-header-row crm-d-flex crm-align-items-center crm-gap-2 crm-mb-2">
          <label className="check">
            <input
              type="checkbox"
              aria-label="Select all users shown"
              checked={allUsers}
              onChange={(e) => {
                const ids = users.map((u) => u.userId);
                onChange({
                  userIds: e.target.checked
                    ? [...new Set([...userIds, ...ids])]
                    : userIds.filter((id) => !ids.includes(id)),
                  teamIds,
                });
              }}
            />
            <span className="check__box" />
          </label>
          <span className="crm-fs-8 crm-fw-bold">Name</span>
        </div>
        <div className="ca-notif-checklist">
          {users.map((u) => (
            <label
              key={u.userId}
              className="check ca-notif-check-row crm-d-flex crm-align-items-center crm-gap-2"
              htmlFor={`${idPrefix}-u-${u.userId}`}
            >
              <input
                id={`${idPrefix}-u-${u.userId}`}
                type="checkbox"
                checked={userIds.includes(u.userId)}
                onChange={(e) =>
                  onChange({ userIds: toggle(userIds, u.userId, e.target.checked), teamIds })
                }
              />
              <span className="check__box" />
              <div className="crm-fs-8 ca-notif-user-info">
                <strong className="ca-notif-user-name">{u.name}</strong>
                <span className="ca-notif-user-email crm-text-subtle crm-ml-1">({u.email})</span>
              </div>
            </label>
          ))}
          {users.length === 0 ? <p className="crm-fs-8 crm-text-muted">No users found.</p> : null}
        </div>
      </div>

      <div className="ca-notif-subpanel" hidden={tab !== 'teams'}>
        <div className="ca-notif-search-wrap crm-mb-3">
          <span className="ca-notif-search-icon">
            <Icon name="search" size={14} />
          </span>
          <input
            type="search"
            className="input ca-notif-search-input"
            placeholder="Search teams"
            autoComplete="off"
            aria-label="Search teams"
            value={teamQ}
            onChange={(e) => setTeamQ(e.target.value)}
          />
        </div>
        <div className="ca-notif-header-row crm-d-flex crm-align-items-center crm-gap-2 crm-mb-2">
          <label className="check">
            <input
              type="checkbox"
              aria-label="Select all teams shown"
              checked={allTeams}
              onChange={(e) => {
                const ids = teams.map((t) => t.id);
                onChange({
                  userIds,
                  teamIds: e.target.checked
                    ? [...new Set([...teamIds, ...ids])]
                    : teamIds.filter((id) => !ids.includes(id)),
                });
              }}
            />
            <span className="check__box" />
          </label>
          <span className="crm-fs-8 crm-fw-bold">Name</span>
        </div>
        <div className="ca-notif-checklist">
          {teams.map((t) => (
            <label
              key={t.id}
              className="check ca-notif-check-row crm-d-flex crm-align-items-center crm-gap-2"
              htmlFor={`${idPrefix}-t-${t.id}`}
            >
              <input
                id={`${idPrefix}-t-${t.id}`}
                type="checkbox"
                checked={teamIds.includes(t.id)}
                onChange={(e) =>
                  onChange({ userIds, teamIds: toggle(teamIds, t.id, e.target.checked) })
                }
              />
              <span className="check__box" />
              <div className="crm-fs-8 ca-notif-user-info">
                <strong className="ca-notif-user-name">{t.name}</strong>
                <span className="ca-notif-user-email crm-text-subtle crm-ml-1">
                  ({t.memberCount} {t.memberCount === 1 ? 'member' : 'members'})
                </span>
              </div>
            </label>
          ))}
          {teams.length === 0 ? <p className="crm-fs-8 crm-text-muted">No teams found.</p> : null}
        </div>
      </div>
    </>
  );
}
