"use client";
import { motion, AnimatePresence } from "framer-motion";
import { X, SlidersHorizontal, RotateCcw, MapPin, Loader2 } from "lucide-react";
import { useState, useEffect } from "react";
import { useAppSelector } from "@/store/hooks";

export interface FilterState {
  priceMin: string;
  priceMax: string;
  condition: string; /* "" | "1" | "2" */
  date: string; /* "YYYY-MM-DD" or "" */
  latitude: string;
  longitude: string;
}

export const DEFAULT_FILTERS: FilterState = {
  priceMin: "",
  priceMax: "",
  condition: "",
  date: "",
  latitude: "",
  longitude: "",
};

interface Props {
  open: boolean;
  onClose: () => void;
  filters: FilterState;
  onApply: (f: FilterState) => void;
  resultCount: number;
}

const CONDITIONS = [
  { value: "", label: "All" },
  { value: "1", label: "New" },
  { value: "2", label: "Old / Used" },
];

/* ─── Date preset helper ─────────────────────────────────────────────────────── */

function toYMD(d: Date): string {
  return d.toISOString().slice(0, 10);
}

function daysAgo(n: number): string {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return toYMD(d);
}

const DATE_PRESETS = [
  { label: "Any time", value: () => "" },
  { label: "Today", value: () => toYMD(new Date()) },
  { label: "Last 7 days", value: () => daysAgo(7) },
  { label: "Last 30 days", value: () => daysAgo(30) },
  { label: "Last 3 months", value: () => daysAgo(90) },
  { label: "Custom", value: null },
];

function DatePresetPicker({
  value,
  onChange,
}: {
  value: string;
  onChange: (d: string) => void;
}) {
  /* Custom mode needs its own flag — preset values can coincide (e.g. "Today")
     which would make activePreset flip away from "Custom" after onChange fires */
  const [customMode, setCustomMode] = useState(() => {
    if (!value) return false;
    return !DATE_PRESETS.some((p) => p.value && p.value() === value);
  });

  const activePreset = customMode
    ? "Custom"
    : (() => {
        if (!value) return "Any time";
        for (const p of DATE_PRESETS) {
          if (p.value && p.value() === value) return p.label;
        }
        return "Custom";
      })();

  return (
    <div className="space-y-3">
      {/* Preset chips */}
      <div className="flex flex-wrap gap-2">
        {DATE_PRESETS.map((preset) => {
          const isActive = activePreset === preset.label;
          return (
            <button
              key={preset.label}
              type="button"
              onClick={() => {
                if (preset.label === "Custom") {
                  setCustomMode(true);
                  /* Pre-fill with today if nothing is set yet */
                  if (!value) onChange(toYMD(new Date()));
                } else if (preset.value) {
                  setCustomMode(false);
                  onChange(preset.value());
                }
              }}
              className="px-3 py-1.5 rounded-full text-xs font-semibold border transition-all duration-150"
              style={{
                background: isActive ? "var(--accent)" : "var(--deep)",
                borderColor: isActive ? "var(--accent)" : "var(--border)",
                color: isActive ? "#fff" : "var(--text-muted)",
              }}
            >
              {preset.label}
            </button>
          );
        })}
      </div>

      {/* Custom date input — shown only when customMode is active */}
      {activePreset === "Custom" && (
        <div className="flex items-center gap-2">
          <input
            type="date"
            value={value}
            max={toYMD(new Date())}
            onChange={(e) => onChange(e.target.value)}
            className="flex-1 px-3 py-2.5 rounded-xl text-sm focus:outline-none"
            style={{
              background: "var(--deep)",
              border: "1px solid var(--accent)",
              color: "var(--text-primary)",
              // colorScheme: "dark",
            }}
          />
          <button
            type="button"
            onClick={() => {
              setCustomMode(false);
              onChange("");
            }}
            className="text-xs font-medium px-2 py-1 rounded-lg"
            style={{
              color: "var(--text-muted)",
              background: "var(--deep)",
              border: "1px solid var(--border)",
            }}
          >
            Clear
          </button>
        </div>
      )}

      {/* Active custom date display */}
      {value && activePreset !== "Any time" && activePreset !== "Custom" && (
        <p className="text-xs" style={{ color: "var(--text-muted)" }}>
          Showing listings posted after{" "}
          <span style={{ color: "var(--text-primary)", fontWeight: 600 }}>
            {new Date(value + "T00:00:00").toLocaleDateString("en-IN", {
              day: "numeric",
              month: "short",
              year: "numeric",
            })}
          </span>
        </p>
      )}
    </div>
  );
}

export function FilterPanel({
  open,
  onClose,
  filters,
  onApply,
  resultCount,
}: Props) {
  const [local, setLocal] = useState<FilterState>(filters);
  const [isMd, setIsMd] = useState(false);
  const [locating, setLocating] = useState(false);
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  useEffect(() => {
    const check = () => setIsMd(window.innerWidth >= 768);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);

  useEffect(() => {
    if (open) setLocal(filters);
  }, [open, filters]);

  const reset = () => setLocal(DEFAULT_FILTERS);
  const apply = () => {
    onApply(local);
    onClose();
  };

  const useCurrentLocation = () => {
    if (!navigator.geolocation) return;
    setLocating(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setLocal((p) => ({
          ...p,
          latitude: pos.coords.latitude.toFixed(6),
          longitude: pos.coords.longitude.toFixed(6),
        }));
        setLocating(false);
      },
      () => setLocating(false),
      { timeout: 8000 },
    );
  };

  const activeCount = [
    local.priceMin,
    local.priceMax,
    local.condition,
    local.date,
    local.latitude,
    local.longitude,
  ].filter(Boolean).length;

  const panelVariants = isMd
    ? { initial: { x: "100%" }, animate: { x: 0 }, exit: { x: "100%" } }
    : { initial: { y: "100%" }, animate: { y: 0 }, exit: { y: "100%" } };

  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            className="fixed inset-0 z-[90] bg-black/60 backdrop-blur-sm"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
          />

          <motion.div
            className="fixed z-[100] flex flex-col overflow-hidden"
            style={{
              background: "var(--card)",
              borderColor: "var(--border)",
              ...(isMd
                ? {
                    right: 0,
                    top: 0,
                    bottom: 0,
                    width: 380,
                    borderLeft: "1px solid var(--border)",
                    borderRadius: "16px 0 0 16px",
                  }
                : {
                    bottom: 0,
                    left: 0,
                    right: 0,
                    maxHeight: "90vh",
                    borderTop: "1px solid var(--border)",
                    borderRadius: "24px 24px 0 0",
                  }),
            }}
            variants={panelVariants}
            initial="initial"
            animate="animate"
            exit="exit"
            transition={{ type: "spring", stiffness: 320, damping: 32 }}
          >
            {/* Mobile handle */}
            {!isMd && (
              <div className="flex justify-center pt-3 shrink-0">
                <div
                  className="w-10 h-1 rounded-full"
                  style={{ background: "var(--border)" }}
                />
              </div>
            )}

            {/* Header */}
            <div
              className="flex items-center justify-between px-5 py-4 shrink-0 border-b"
              style={{ borderColor: "var(--border)" }}
            >
              <div className="flex items-center gap-2">
                <SlidersHorizontal
                  size={17}
                  style={{ color: "var(--accent)" }}
                />
                <span
                  className="font-bold text-base"
                  style={{ color: "var(--text-primary)" }}
                >
                  Filters
                </span>
                {activeCount > 0 && (
                  <span
                    className="text-[10px] font-black px-1.5 py-0.5 rounded-full text-white"
                    style={{ background: "var(--accent)" }}
                  >
                    {activeCount}
                  </span>
                )}
              </div>
              <div className="flex items-center gap-3">
                <button
                  onClick={reset}
                  className="text-xs font-bold flex items-center gap-1"
                  style={{ color: "var(--accent)" }}
                >
                  <RotateCcw size={11} /> Reset
                </button>
                <button
                  onClick={onClose}
                  className="w-8 h-8 rounded-full flex items-center justify-center"
                  style={{ background: "var(--deep)" }}
                >
                  <X size={15} className="text-[var(--text-muted)]" />
                </button>
              </div>
            </div>

            {/* Scrollable body */}
            <div className="flex-1 overflow-y-auto p-5 space-y-6">
              {/* Price Range */}
              <section>
                <h4
                  className="text-[10px] font-bold uppercase tracking-widest mb-3"
                  style={{ color: "var(--text-muted)" }}
                >
                  Price Range
                </h4>
                <div className="flex gap-3 items-center">
                  <input
                    type="number"
                    placeholder={`Min ${currencyCode}`}
                    value={local.priceMin}
                    onChange={(e) =>
                      setLocal((p) => ({ ...p, priceMin: e.target.value }))
                    }
                    className="flex-1 px-3 py-2.5 rounded-xl text-sm focus:outline-none"
                    style={{
                      background: "var(--deep)",
                      border: "1px solid var(--border)",
                      color: "var(--text-primary)",
                    }}
                  />
                  <span
                    className="text-xs shrink-0"
                    style={{ color: "var(--text-muted)" }}
                  >
                    to
                  </span>
                  <input
                    type="number"
                    placeholder={`Max ${currencyCode}`}
                    value={local.priceMax}
                    onChange={(e) =>
                      setLocal((p) => ({ ...p, priceMax: e.target.value }))
                    }
                    className="flex-1 px-3 py-2.5 rounded-xl text-sm focus:outline-none"
                    style={{
                      background: "var(--deep)",
                      border: "1px solid var(--border)",
                      color: "var(--text-primary)",
                    }}
                  />
                </div>
              </section>

              {/* Condition */}
              <section>
                <h4
                  className="text-[10px] font-bold uppercase tracking-widest mb-3"
                  style={{ color: "var(--text-muted)" }}
                >
                  Condition
                </h4>
                <div className="flex gap-2">
                  {CONDITIONS.map((c) => {
                    const active = local.condition === c.value;
                    return (
                      <button
                        key={c.value}
                        onClick={() =>
                          setLocal((p) => ({ ...p, condition: c.value }))
                        }
                        className="flex-1 py-2.5 rounded-xl text-sm font-semibold border transition-all"
                        style={{
                          borderColor: active
                            ? "var(--accent)"
                            : "var(--border)",
                          background: active
                            ? "rgba(252,0,0,0.08)"
                            : "var(--deep)",
                          color: active
                            ? "var(--accent)"
                            : "var(--text-primary)",
                        }}
                      >
                        {c.label}
                      </button>
                    );
                  })}
                </div>
              </section>

              {/* Date (Posted After) */}
              <section>
                <h4
                  className="text-[10px] font-bold uppercase tracking-widest mb-3"
                  style={{ color: "var(--text-muted)" }}
                >
                  Posted After
                </h4>
                <DatePresetPicker
                  value={local.date}
                  onChange={(d) => setLocal((p) => ({ ...p, date: d }))}
                />
              </section>

              {/* Location */}
              <section>
                <h4
                  className="text-[10px] font-bold uppercase tracking-widest mb-3"
                  style={{ color: "var(--text-muted)" }}
                >
                  Location
                </h4>
                <div className="space-y-2.5">
                  <div className="flex gap-2 items-center">
                    <span
                      className="text-xs w-20 shrink-0"
                      style={{ color: "var(--text-muted)" }}
                    >
                      Latitude
                    </span>
                    <input
                      type="number"
                      step="any"
                      placeholder="e.g. 23.0225"
                      value={local.latitude}
                      onChange={(e) =>
                        setLocal((p) => ({ ...p, latitude: e.target.value }))
                      }
                      className="flex-1 px-3 py-2.5 rounded-xl text-sm focus:outline-none"
                      style={{
                        background: "var(--deep)",
                        border: "1px solid var(--border)",
                        color: "var(--text-primary)",
                      }}
                    />
                  </div>
                  <div className="flex gap-2 items-center">
                    <span
                      className="text-xs w-20 shrink-0"
                      style={{ color: "var(--text-muted)" }}
                    >
                      Longitude
                    </span>
                    <input
                      type="number"
                      step="any"
                      placeholder="e.g. 72.5714"
                      value={local.longitude}
                      onChange={(e) =>
                        setLocal((p) => ({ ...p, longitude: e.target.value }))
                      }
                      className="flex-1 px-3 py-2.5 rounded-xl text-sm focus:outline-none"
                      style={{
                        background: "var(--deep)",
                        border: "1px solid var(--border)",
                        color: "var(--text-primary)",
                      }}
                    />
                  </div>
                  <motion.button
                    whileTap={{ scale: 0.97 }}
                    onClick={useCurrentLocation}
                    disabled={locating}
                    className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-semibold border transition-all"
                    style={{
                      borderColor:
                        local.latitude && local.longitude
                          ? "var(--accent)"
                          : "var(--border)",
                      background:
                        local.latitude && local.longitude
                          ? "rgba(252,0,0,0.06)"
                          : "var(--deep)",
                      color:
                        local.latitude && local.longitude
                          ? "var(--accent)"
                          : "var(--text-muted)",
                      opacity: locating ? 0.7 : 1,
                    }}
                  >
                    {locating ? (
                      <>
                        <Loader2 size={14} className="animate-spin" />{" "}
                        Detecting…
                      </>
                    ) : (
                      <>
                        <MapPin size={14} /> Use Current Location
                      </>
                    )}
                  </motion.button>
                  {(local.latitude || local.longitude) && (
                    <button
                      onClick={() =>
                        setLocal((p) => ({ ...p, latitude: "", longitude: "" }))
                      }
                      className="text-xs"
                      style={{ color: "var(--accent)" }}
                    >
                      Clear location
                    </button>
                  )}
                </div>
              </section>
            </div>

            {/* Footer */}
            <div
              className="shrink-0 p-5 border-t"
              style={{
                borderColor: "var(--border)",
                background: "var(--card)",
              }}
            >
              <p
                className="text-center text-sm mb-3"
                style={{ color: "var(--text-muted)" }}
              >
                <span
                  className="font-bold"
                  style={{ color: "var(--text-primary)" }}
                >
                  {resultCount}
                </span>{" "}
                listings found
              </p>
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={apply}
                className="w-full py-3.5 rounded-xl font-bold text-white text-sm"
                style={{ background: "var(--accent)" }}
              >
                Apply Filters
              </motion.button>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
