import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ChevronDown, ChevronUp } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  getReviewStats,
  type DatasetMember,
  type DatasetTask,
} from '@ump/shared';
import { tasksAssignedByStage } from '../domain/taskView';
import { InitialsAvatar } from './InitialsAvatar';

type SidebarUser = { id: string; name: string; role: string };

const DATE_RANGES = [
  { value: '7', label: '7 ngày qua' },
  { value: '30', label: '30 ngày qua' },
  { value: '90', label: '90 ngày qua' },
];

function Section({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(true);
  return (
    <div className="border-t border-border pt-3">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="flex w-full items-center justify-between text-xs font-semibold uppercase tracking-wide text-muted-foreground"
      >
        {title}
        {open ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
      </button>
      {open && <div className="mt-2 space-y-1.5">{children}</div>}
    </div>
  );
}

function MetricRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className="tabular-nums text-foreground">{value}</span>
    </div>
  );
}

/**
 * Region 1 — the per-user productivity panel. The user picker, "Tasks assigned" by stage, and the
 * accept/reject/corrections counts (from the review-events backend, migration 025) are real; the
 * time-based metrics remain placeholders until the backend records per-action labeling/review time.
 */
export function ProductivitySidebar({
  datasetId,
  tasks,
  members,
  currentUser,
}: {
  datasetId: string;
  tasks: DatasetTask[];
  members: DatasetMember[];
  currentUser: SidebarUser | null;
}) {
  const [days, setDays] = useState('7');

  // Whoever the picker is pointed at — defaults to the signed-in user. The option list merges the
  // current user with the dataset members (deduped by id).
  const people = useMemo<SidebarUser[]>(() => {
    const map = new Map<string, SidebarUser>();
    if (currentUser) map.set(currentUser.id, currentUser);
    for (const m of members) {
      if (!map.has(m.userId)) {
        map.set(m.userId, { id: m.userId, name: m.fullName || m.email, role: m.role });
      }
    }
    return Array.from(map.values());
  }, [currentUser, members]);

  const [userId, setUserId] = useState<string>(currentUser?.id ?? '');
  const selected = people.find((p) => p.id === userId) ?? currentUser ?? people[0] ?? null;

  const assigned = useMemo(
    () => tasksAssignedByStage(tasks, selected?.id ?? null),
    [tasks, selected?.id],
  );
  const rangeLabel = DATE_RANGES.find((r) => r.value === days)?.label ?? '7 ngày qua';

  // Real review-decision tallies for the selected reviewer over the chosen window.
  const reviewStatsQ = useQuery({
    queryKey: ['imagehub', 'review-stats', datasetId, selected?.id ?? null, days],
    queryFn: () => getReviewStats(datasetId, { userId: selected?.id, days: Number(days) }),
    enabled: !!datasetId && !!selected,
  });
  const rs = reviewStatsQ.data;
  const reviewTotal = (rs?.accepted ?? 0) + (rs?.acceptWithCorrections ?? 0) + (rs?.rejected ?? 0);

  const metrics: Array<{ label: string; value: string }> = [
    { label: 'Lượt được chấp nhận', value: String(rs?.accepted ?? 0) },
    { label: 'Lượt chỉnh sửa', value: String(rs?.acceptWithCorrections ?? 0) },
    { label: 'Lượt bị từ chối', value: String(rs?.rejected ?? 0) },
    // Time-based metrics need per-action timing events the backend does not record yet.
    { label: 'TG gán nhãn TB', value: '0s' },
    { label: 'Tổng TG gán nhãn', value: '0s' },
    { label: 'TG rà soát TB', value: '0s' },
    { label: 'Tổng TG rà soát', value: '0s' },
  ];

  return (
    <aside className="w-full shrink-0 space-y-4 rounded-xl border border-border bg-card p-4 lg:w-72">
      {/* User header + picker */}
      <div className="space-y-3">
        {selected ? (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                className="flex w-full items-center gap-2 rounded-md p-1 text-left transition-colors hover:bg-muted"
              >
                <InitialsAvatar name={selected.name} seed={selected.id} className="h-9 w-9 text-xs" />
                <span className="flex min-w-0 flex-1 flex-col">
                  <span className="truncate font-medium text-foreground">{selected.name}</span>
                  <span className="truncate text-xs text-muted-foreground">{selected.role || 'Thành viên'}</span>
                </span>
                <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" className="w-56">
              {people.map((p) => (
                <DropdownMenuItem key={p.id} onClick={() => setUserId(p.id)}>
                  <InitialsAvatar name={p.name} seed={p.id} className="mr-2 h-5 w-5" />
                  <span className="truncate">{p.name}</span>
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        ) : (
          <p className="text-sm text-muted-foreground">Không có người dùng.</p>
        )}

        <div className="space-y-1">
          <span className="text-xs font-medium text-muted-foreground">Khoảng thời gian</span>
          <Select value={days} onValueChange={setDays}>
            <SelectTrigger className="h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {DATE_RANGES.map((r) => (
                <SelectItem key={r.value} value={r.value}>
                  {r.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      <Section title="Công việc được giao">
        {assigned.rows.length === 0 ? (
          <p className="text-sm text-muted-foreground">Chưa có công việc nào được giao.</p>
        ) : (
          <>
            {assigned.rows.map((r) => (
              <div key={r.stageId} className="flex items-center justify-between text-sm">
                <span className="text-foreground">{r.stageName}</span>
                <span className="tabular-nums font-medium text-foreground">{r.count}</span>
              </div>
            ))}
            <div className="flex items-center justify-between border-t border-border pt-1.5 text-sm">
              <span className="text-muted-foreground">Tổng</span>
              <span className="tabular-nums font-semibold text-foreground">{assigned.total}</span>
            </div>
          </>
        )}
      </Section>

      <Section title="Năng suất">
        {reviewTotal === 0 && (
          <p className="text-xs italic text-muted-foreground">Không có lượt rà soát trong {rangeLabel}</p>
        )}
        {metrics.map((m) => (
          <MetricRow key={m.label} label={m.label} value={m.value} />
        ))}
      </Section>
    </aside>
  );
}

export default ProductivitySidebar;
