"use client";

import { useState } from "react";
import { Button } from "@/components/ui/Button";
import { PersianDatePicker } from "@/components/ui/PersianDatePicker";
import type { BranchOption, DeliveryFilter } from "@/lib/attendance-report";
import { fa } from "./AttendancePrimitives";
import { RANGE_OPTIONS, faDate } from "./dateRange";
import type { AttendanceFilters } from "./useAttendanceFilters";
import { Overlay } from "./AttendanceShared";

/**
 * نوار فیلتر مشترک داشبورد و ریز داده‌ها.
 *
 * همهٔ گزینه‌ها از سرور می‌آید؛ این کامپوننت فقط وضعیت را نمایش و تغییر می‌دهد.
 */
export function AttendanceFilterBar({
  filters,
  showSearch = false,
  searchPlaceholder = "جستجوی نام، کد، کلاس یا شماره ولی",
}: {
  filters: AttendanceFilters;
  showSearch?: boolean;
  searchPlaceholder?: string;
}) {
  const { state, patch, setCustomRange, options, branchLabel, range, today } = filters;
  const [branchModal, setBranchModal] = useState(false);
  const [dateModal, setDateModal] = useState(false);

  // فهرست کلاس‌ها و زنگ‌ها از سرور با همین محدوده آمده؛ فقط اگر چند شعبه در
  // دسترس باشد، گزینه‌های شعبِ انتخاب‌نشده را کنار می‌گذاریم.
  const classRooms = options.class_rooms.filter(
    (room) => state.branchIds.length === 0 || state.branchIds.includes(room.branch_id),
  );

  const periods = options.periods.filter(
    (period) => state.branchIds.length === 0 || state.branchIds.includes(period.branch_id),
  );

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <button
          type="button"
          onClick={() => setBranchModal(true)}
          className="min-w-[12rem] rounded-xl border border-slate-200 bg-white px-3 py-2 text-right text-sm font-bold text-slate-800 transition hover:border-teal-200"
        >
          <span className="block text-[11px] font-bold text-slate-400">فیلتر شعبه</span>
          <span className="block truncate">{branchLabel}</span>
        </button>

        <div className="flex flex-wrap rounded-xl bg-slate-100 p-1">
          {RANGE_OPTIONS.map(([key, label]) => (
            <button
              key={key}
              type="button"
              onClick={() => patch({ preset: key })}
              className={`rounded-lg px-2.5 py-1.5 text-[11px] font-bold ${
                state.preset === key ? "bg-white shadow-sm" : "text-slate-500"
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        <button
          type="button"
          onClick={() => setDateModal(true)}
          className={`flex min-w-[12.5rem] items-center gap-2 rounded-xl border px-3 py-1.5 text-right transition ${
            state.preset === "custom"
              ? "border-teal-300 bg-teal-50 shadow-sm"
              : "border-slate-200 bg-white hover:border-teal-200 hover:bg-teal-50/40"
          }`}
        >
          <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-teal-600 text-white">
            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="currentColor" aria-hidden>
              <path d="M7 2h2v2h6V2h2v2h3v16H4V4h3V2zm13 8H6v8h14v-8zM6 6v2h14V6H6z" />
            </svg>
          </span>
          <span className="min-w-0">
            <span className="block text-[10px] font-bold text-slate-400">بازه دلخواه</span>
            <span
              className={`block truncate text-xs font-bold ${
                state.preset === "custom" ? "text-teal-800" : "text-slate-800"
              }`}
            >
              {state.preset === "custom"
                ? `${faDate(range.from)} تا ${faDate(range.to)}`
                : "انتخاب از / تا"}
            </span>
          </span>
        </button>

        {showSearch ? (
          <input
            value={state.q}
            onChange={(event) => patch({ q: event.target.value })}
            placeholder={searchPlaceholder}
            className="min-w-[12rem] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm"
          />
        ) : null}
      </div>

      <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2">
        <DeliveryModeFilter
          value={state.deliveryMode}
          options={options.delivery_modes}
          onChange={(deliveryMode) => patch({ deliveryMode })}
        />

        <SelectFilter
          label="زنگ"
          value={state.periodId}
          onChange={(periodId) => patch({ periodId })}
          options={periods.map((period) => ({ id: period.id, label: period.label }))}
          allLabel="همه زنگ‌ها"
        />

        <SelectFilter
          label="پایه"
          value={state.gradeLevelId}
          onChange={(gradeLevelId) => patch({ gradeLevelId, classRoomId: null })}
          options={options.grade_levels
            .filter((grade) => grade.name !== null)
            .map((grade) => ({ id: grade.id, label: grade.name as string }))}
          allLabel="همه پایه‌ها"
        />

        <SelectFilter
          label="کلاس"
          value={state.classRoomId}
          onChange={(classRoomId) => patch({ classRoomId })}
          options={classRooms.map((room) => ({
            id: room.id,
            label: room.grade_level_name ? `${room.name} · ${room.grade_level_name}` : room.name,
          }))}
          allLabel="همه کلاس‌ها"
        />
      </div>

      {branchModal ? (
        <BranchFilterModal
          branches={options.branches}
          selectedIds={state.branchIds}
          onApply={(ids) => {
            patch({ branchIds: ids, classRoomId: null, periodId: null });
            setBranchModal(false);
          }}
          onClose={() => setBranchModal(false)}
        />
      ) : null}

      {dateModal ? (
        <DateRangeModal
          from={range.from}
          to={range.to}
          maxDate={today}
          onApply={(from, to) => {
            setCustomRange(from, to);
            setDateModal(false);
          }}
          onClose={() => setDateModal(false)}
        />
      ) : null}
    </>
  );
}

/** فیلتر حضوری / مجازی — هستهٔ تفکیک نوع کلاس در کل گزارش. */
export function DeliveryModeFilter({
  value,
  options,
  onChange,
}: {
  value: DeliveryFilter;
  options: Array<{ key: string; label: string }>;
  onChange: (value: DeliveryFilter) => void;
}) {
  return (
    <div className="flex flex-wrap items-center gap-1.5">
      <span className="text-[11px] font-bold text-slate-400">نوع کلاس</span>
      {options.map((option) => {
        const active = value === option.key;
        const isAll = option.key === "all";
        const isVirtualBucket = option.key === "virtual";
        return (
          <button
            key={option.key}
            type="button"
            onClick={() => onChange(option.key as DeliveryFilter)}
            className={`inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-[11px] font-bold ring-1 transition ${
              active
                ? "bg-teal-600 text-white ring-teal-600"
                : "bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"
            }`}
          >
            {isAll || isVirtualBucket ? null : (
              <span aria-hidden>
                {option.key === "in_person" ? "🏫" : option.key === "offline" ? "🎞" : option.key === "hybrid" ? "🔀" : "💻"}
              </span>
            )}
            {option.label}
          </button>
        );
      })}
    </div>
  );
}

function SelectFilter({
  label,
  value,
  options,
  allLabel,
  onChange,
}: {
  label: string;
  value: number | null;
  options: Array<{ id: number; label: string }>;
  allLabel: string;
  onChange: (value: number | null) => void;
}) {
  if (options.length === 0) return null;

  return (
    <label className="inline-flex items-center gap-1.5 text-[11px] font-bold text-slate-400">
      {label}
      <select
        value={value ?? ""}
        onChange={(event) => onChange(event.target.value ? Number(event.target.value) : null)}
        className="rounded-xl border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-bold text-slate-700"
      >
        <option value="">{allLabel}</option>
        {options.map((option) => (
          <option key={option.id} value={option.id}>
            {option.label}
          </option>
        ))}
      </select>
    </label>
  );
}

export function BranchFilterModal({
  branches,
  selectedIds,
  onApply,
  onClose,
}: {
  branches: BranchOption[];
  selectedIds: number[];
  onApply: (ids: number[]) => void;
  onClose: () => void;
}) {
  // خالی بودن انتخاب یعنی «همه»؛ برای نمایش، همه را تیک‌خورده نشان می‌دهیم.
  const [draft, setDraft] = useState<number[]>(
    selectedIds.length > 0 ? selectedIds : branches.map((branch) => branch.id),
  );
  const allOn = branches.length > 0 && draft.length === branches.length;

  return (
    <Overlay onClose={onClose}>
      <div className="relative z-10 w-full max-w-lg rounded-[1.6rem] bg-white p-5 shadow-2xl">
        <div className="mb-4 flex items-start justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold text-teal-700">فیلتر جامع شعب</p>
            <h3 className="text-lg font-black">شعب موردنظر را انتخاب کنید</h3>
          </div>
          <button type="button" onClick={onClose} className="text-sm text-slate-500">
            بستن
          </button>
        </div>
        {branches.length === 0 ? (
          <p className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-400">
            شعبه‌ای در دسترس شما نیست.
          </p>
        ) : (
          <>
            <div className="mb-3 flex gap-2">
              <Button
                variant="secondary"
                onClick={() => setDraft(branches.map((branch) => branch.id))}
              >
                همه شعب
              </Button>
              <Button variant="secondary" onClick={() => setDraft([])}>
                پاک کردن
              </Button>
            </div>
            <ul className="grid max-h-72 grid-cols-2 gap-2 overflow-y-auto">
              {branches.map((branch) => {
                const on = draft.includes(branch.id);
                return (
                  <li key={branch.id}>
                    <button
                      type="button"
                      onClick={() =>
                        setDraft((prev) =>
                          on ? prev.filter((id) => id !== branch.id) : [...prev, branch.id],
                        )
                      }
                      className={`flex w-full items-center justify-between rounded-xl px-2.5 py-2 text-right ring-1 transition ${
                        on
                          ? "bg-teal-50 text-teal-900 ring-teal-200"
                          : "bg-slate-50 text-slate-700 ring-transparent"
                      }`}
                    >
                      <span className="truncate text-xs font-bold">{branch.name}</span>
                      <span className="text-[10px] text-slate-400">{on ? "✓" : ""}</span>
                    </button>
                  </li>
                );
              })}
            </ul>
          </>
        )}
        <div className="mt-4 flex gap-2">
          <Button
            block
            disabled={draft.length === 0}
            onClick={() => onApply(allOn ? [] : draft)}
          >
            اعمال فیلتر
            {allOn ? " · تمام مجموعه" : ` · ${fa(draft.length)} شعبه`}
          </Button>
          <Button variant="secondary" onClick={onClose}>
            بازگشت
          </Button>
        </div>
      </div>
    </Overlay>
  );
}

export function DateRangeModal({
  from,
  to,
  maxDate,
  onApply,
  onClose,
}: {
  from: string;
  to: string;
  maxDate: string;
  onApply: (from: string, to: string) => void;
  onClose: () => void;
}) {
  const [draftFrom, setDraftFrom] = useState(from);
  const [draftTo, setDraftTo] = useState(to);

  return (
    <Overlay onClose={onClose}>
      <div className="relative z-10 w-full max-w-2xl rounded-[1.6rem] bg-white p-5 shadow-2xl">
        <div className="mb-4 flex items-start justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold text-teal-700">بازه دلخواه</p>
            <h3 className="text-lg font-black">از تاریخ و تا تاریخ</h3>
          </div>
          <button type="button" onClick={onClose} className="text-sm text-slate-500">
            بستن
          </button>
        </div>
        <div className="mb-4 flex items-center justify-center gap-2 rounded-2xl bg-teal-50 px-3 py-2 text-sm font-bold text-teal-900">
          <span>{faDate(draftFrom)}</span>
          <span className="text-teal-400">تا</span>
          <span>{faDate(draftTo)}</span>
        </div>
        <div className="grid gap-4 md:grid-cols-2">
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <p className="mb-2 text-[11px] font-bold text-slate-400">شروع</p>
            <p className="mb-3 text-sm font-black text-slate-800">از تاریخ</p>
            <PersianDatePicker value={draftFrom} maxDate={draftTo} onChange={setDraftFrom} />
          </div>
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <p className="mb-2 text-[11px] font-bold text-slate-400">پایان</p>
            <p className="mb-3 text-sm font-black text-slate-800">تا تاریخ</p>
            <PersianDatePicker value={draftTo} maxDate={maxDate} onChange={setDraftTo} />
          </div>
        </div>
        <p className="mt-3 text-[11px] text-slate-500">
          حداکثر بازهٔ قابل گزارش {fa(92)} روز است؛ بازه‌های بلندتر از سمت سرور کوتاه می‌شود.
        </p>
        <div className="mt-4 flex gap-2">
          <Button block onClick={() => onApply(draftFrom, draftTo)}>
            اعمال بازه
          </Button>
          <Button variant="secondary" onClick={onClose}>
            بازگشت
          </Button>
        </div>
      </div>
    </Overlay>
  );
}
