"use client";

import React, { useState } from "react";
import styles from "../commonstyle/dattabale.module.css";
import { FaSearchLocation } from "react-icons/fa";
import { FiRefreshCw, FiBarChart2, FiEyeOff } from "react-icons/fi";
import type { ScheduleStatus } from "@/lib/api/types/audit-schedule.types";

// ─── Filter types ──────────────────────────────────────────────────────────
export type DatePreset =
  | "all"
  | "today"
  | "this_week"
  | "this_month"
  | "next_month"
  | "past"
  | "custom"; // 🆕 custom From/To range, or a specific month/year

export type ClientGroupFilter = "all" | "QRS" | "IICC";

interface Props {
  searchTerm: string;
  setSearchTerm: (v: string) => void;
  statusFilter: ScheduleStatus | "all";
  setStatusFilter: (v: ScheduleStatus | "all") => void;
  clientGroupFilter: ClientGroupFilter;
  setClientGroupFilter: (v: ClientGroupFilter) => void;
  datePreset: DatePreset;
  setDatePreset: (v: DatePreset) => void;
  clearFilters: () => void;
  onRefresh?: () => void;
  showAnalytics?: boolean;
  onAnalyticsToggle?: () => void;
  // 🆕 Custom date range (used when datePreset === "custom")
  customDateFrom?: string;
  setCustomDateFrom?: (v: string) => void;
  customDateTo?: string;
  setCustomDateTo?: (v: string) => void;
}

const STATUS_OPTIONS: { value: ScheduleStatus | "all"; label: string }[] = [
  { value: "all", label: "All Statuses" },
  { value: "DRAFT", label: "Draft" },
  { value: "PUBLISHED", label: "Published" },
  { value: "IN_PROGRESS", label: "In Progress" },
  { value: "COMPLETED", label: "Completed" },
  { value: "CANCELLED", label: "Cancelled" },
];

const CLIENT_GROUP_OPTIONS: { value: ClientGroupFilter; label: string }[] = [
  { value: "all", label: "🌐 All Client Groups" },
  { value: "QRS", label: "🟣 QRS" },
  { value: "IICC", label: "🔵 IICC" },
];

const DATE_OPTIONS: { value: DatePreset; label: string }[] = [
  { value: "all", label: "📅 All Dates" },
  { value: "today", label: "📍 Today" },
  { value: "this_week", label: "🗓️ This Week" },
  { value: "this_month", label: "📆 This Month" },
  { value: "next_month", label: "⏭️ Next Month" },
  { value: "past", label: "🕰️ Past Audits" },
  { value: "custom", label: "🎯 Custom Range / Month" },
];

const MONTH_NAMES = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

export const AuditScheduleFilters = ({
  searchTerm,
  setSearchTerm,
  statusFilter,
  setStatusFilter,
  clientGroupFilter,
  setClientGroupFilter,
  datePreset,
  setDatePreset,
  clearFilters,
  onRefresh,
  showAnalytics = false,
  onAnalyticsToggle,
  customDateFrom = "",
  setCustomDateFrom,
  customDateTo = "",
  setCustomDateTo,
}: Props) => {
  const activeFilterCount = [
    statusFilter !== "all",
    clientGroupFilter !== "all",
    datePreset !== "all",
  ].filter(Boolean).length;

  // 🆕 Year for the month picker — defaults to this year, ±2 years selectable.
  const nowYear = new Date().getFullYear();
  const [currentYearForPicker, setCurrentYearForPicker] = useState(nowYear);
  const yearOptions = [nowYear - 2, nowYear - 1, nowYear, nowYear + 1, nowYear + 2];

  // 🆕 Month/Year quick-pick — fills the From/To custom range for you.
  const handleMonthYearPick = (monthIdx: number, year: number) => {
    if (!setCustomDateFrom || !setCustomDateTo) return;
    const from = new Date(year, monthIdx, 1);
    const to = new Date(year, monthIdx + 1, 0); // last day of month
    const iso = (d: Date) =>
      `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    setCustomDateFrom(iso(from));
    setCustomDateTo(iso(to));
  };

  return (
    <div className={styles.toolbar}>
      {/* ─── Top Row: Search + Actions ─── */}
      <div className={styles.toolbarTop}>
        <div className={styles.searchBox}>
          <span className={styles.searchIcon}>
            <FaSearchLocation />
          </span>
          <input
            type="text"
            aria-label="Search Audit Schedules"
            placeholder="Search by title, audit code, company..."
            className={styles.searchInput}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        <div className={styles.toolbarActions}>
          {/* Stats toggle */}
          {onAnalyticsToggle && (
            <button
              title={showAnalytics ? "Hide analytics" : "Show analytics"}
              onClick={onAnalyticsToggle}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                padding: "8px 16px",
                background: showAnalytics
                  ? "linear-gradient(135deg, #475569 0%, #64748b 100%)"
                  : "linear-gradient(135deg, #6d28d9 0%, #8b5cf6 100%)",
                color: "white",
                border: "none",
                borderRadius: 8,
                fontSize: "0.875rem",
                fontWeight: 600,
                cursor: "pointer",
                boxShadow: "0 2px 8px rgba(109,40,217,0.3)",
                whiteSpace: "nowrap",
              }}
            >
              {showAnalytics ? <FiEyeOff size={14} /> : <FiBarChart2 size={14} />}
              {showAnalytics ? "Hide Stats" : "Stats"}
            </button>
          )}

          {/* Refresh */}
          {onRefresh && (
            <button
              className={styles.btnIcon}
              title="Refresh"
              onClick={onRefresh}
            >
              <FiRefreshCw size={14} />
            </button>
          )}
        </div>
      </div>

      {/* ─── Bottom Row: Filters ─── */}
      <div
        className={styles.toolbarFilters}
        style={{ flexWrap: "wrap", gap: 8 }}
      >
        {/* Status */}
        <div className={styles.filterGroup}>
          <select
            className={styles.filterSelect}
            value={statusFilter}
            onChange={(e) =>
              setStatusFilter(e.target.value as ScheduleStatus | "all")
            }
            style={{
              borderColor: statusFilter !== "all" ? "#8b14d4" : undefined,
              fontWeight: statusFilter !== "all" ? 600 : undefined,
            }}
          >
            {STATUS_OPTIONS.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>

        {/* Client group */}
        <div className={styles.filterGroup}>
          <select
            className={styles.filterSelect}
            value={clientGroupFilter}
            onChange={(e) =>
              setClientGroupFilter(e.target.value as ClientGroupFilter)
            }
            style={{
              borderColor:
                clientGroupFilter !== "all" ? "#0ea5e9" : undefined,
              fontWeight: clientGroupFilter !== "all" ? 600 : undefined,
            }}
          >
            {CLIENT_GROUP_OPTIONS.map((c) => (
              <option key={c.value} value={c.value}>
                {c.label}
              </option>
            ))}
          </select>
        </div>

        {/* Date preset */}
        <div className={styles.filterGroup}>
          <select
            className={styles.filterSelect}
            value={datePreset}
            onChange={(e) => setDatePreset(e.target.value as DatePreset)}
            style={{
              borderColor: datePreset !== "all" ? "#f59e0b" : undefined,
              fontWeight: datePreset !== "all" ? 600 : undefined,
            }}
          >
            {DATE_OPTIONS.map((d) => (
              <option key={d.value} value={d.value}>
                {d.label}
              </option>
            ))}
          </select>
        </div>

        {/* Clear button */}
        {activeFilterCount > 0 && (
          <button
            className={styles.clearFiltersBtn}
            onClick={clearFilters}
            title="Clear all filters"
          >
            ✕ Clear ({activeFilterCount})
          </button>
        )}
      </div>

      {/* ─── Custom Range / Month row — only when "Custom Range / Month" is picked ─── */}
      {datePreset === "custom" && setCustomDateFrom && setCustomDateTo && (
        <div
          style={{
            display: "flex",
            flexWrap: "wrap",
            alignItems: "center",
            gap: 10,
            marginTop: 8,
            padding: "10px 12px",
            background: "#fffbeb",
            border: "1px solid #fde68a",
            borderRadius: 8,
          }}
        >
          <span style={{ fontSize: 12, fontWeight: 700, color: "#92400e" }}>
            From:
          </span>
          <input
            type="date"
            value={customDateFrom}
            onChange={(e) => setCustomDateFrom(e.target.value)}
            style={{
              padding: "6px 10px",
              borderRadius: 6,
              border: "1px solid #fbbf24",
              fontSize: 13,
            }}
          />
          <span style={{ fontSize: 12, fontWeight: 700, color: "#92400e" }}>
            To:
          </span>
          <input
            type="date"
            value={customDateTo}
            onChange={(e) => setCustomDateTo(e.target.value)}
            style={{
              padding: "6px 10px",
              borderRadius: 6,
              border: "1px solid #fbbf24",
              fontSize: 13,
            }}
          />

          <span
            style={{
              width: 1,
              height: 22,
              background: "#fbbf24",
              margin: "0 4px",
            }}
          />

          <span style={{ fontSize: 12, fontWeight: 700, color: "#92400e" }}>
            Or pick a month:
          </span>
          <select
            defaultValue=""
            onChange={(e) => {
              const monthIdx = Number(e.target.value);
              if (Number.isNaN(monthIdx)) return;
              handleMonthYearPick(monthIdx, currentYearForPicker);
            }}
            style={{
              padding: "6px 10px",
              borderRadius: 6,
              border: "1px solid #fbbf24",
              fontSize: 13,
            }}
          >
            <option value="" disabled>
              Month...
            </option>
            {MONTH_NAMES.map((m, i) => (
              <option key={m} value={i}>
                {m}
              </option>
            ))}
          </select>
          <select
            value={currentYearForPicker}
            onChange={(e) => setCurrentYearForPicker(Number(e.target.value))}
            style={{
              padding: "6px 10px",
              borderRadius: 6,
              border: "1px solid #fbbf24",
              fontSize: 13,
            }}
          >
            {yearOptions.map((y) => (
              <option key={y} value={y}>
                {y}
              </option>
            ))}
          </select>
        </div>
      )}
    </div>
  );
};