"use client";

import { schedule, rajbariStations, allStationsList, trainData } from "@/data";
import Link from "next/link";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { useState, useEffect, useRef } from "react";
import { SectionHeader } from "@/components/ui/SectionHeader";
import { ShareButton } from "@/components/ui/ShareButton";
import { ChevronRight, ArrowRightLeft, Search, X } from "lucide-react";

export function Schedule({
  initialStation = null,
  initialToStation = null,
  showShareButton = false,
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // From Station
  const [fromStation, setFromStation] = useState(initialStation || "rajbari");

  // To Station
  const [toStation, setToStation] = useState(initialToStation || "");

  // Departure search
  const [fromSearch, setFromSearch] = useState("");
  const [fromDropdownOpen, setFromDropdownOpen] = useState(false);
  const fromRef = useRef(null);

  // Destination search
  const [destSearch, setDestSearch] = useState("");
  const [destDropdownOpen, setDestDropdownOpen] = useState(false);
  const destRef = useRef(null);

  // Close dropdowns on outside click
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (fromRef.current && !fromRef.current.contains(e.target)) {
        setFromDropdownOpen(false);
      }
      if (destRef.current && !destRef.current.contains(e.target)) {
        setDestDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Update state when props change
  useEffect(() => {
    if (initialStation) {
      setFromStation(initialStation);
    }
    if (initialToStation) {
      setToStation(initialToStation);
    }
  }, [initialStation, initialToStation]);

  // Rajbari district stations for quick-access buttons
  const rajbariButtons = rajbariStations.map((station) => ({
    id: station.toLowerCase().replace(/_/g, ""),
    label: station.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
  }));

  // Helper function to convert time string to minutes for sorting
  const timeToMinutes = (timeStr) => {
    if (!timeStr || timeStr === "Start") return -1;
    if (timeStr === "Terminates") return 24 * 60;
    const [time, period] = timeStr.split(" ");
    if (!time || !period) return 0;
    const [hours, minutes] = time.split(":").map(Number);
    let totalMinutes = hours * 60 + minutes;
    if (period === "PM" && hours !== 12) totalMinutes += 12 * 60;
    if (period === "AM" && hours === 12) totalMinutes -= 12 * 60;
    return totalMinutes;
  };

  const filteredSchedule = schedule
    .filter((item) => {
      // Filter by departure station
      if (item.station !== fromStation) return false;

      // If destination is selected, check if the train goes there
      if (toStation && toStation !== fromStation) {
        const train = trainData.find((t) => {
          const trainSlug = t.data.train_name
            .replace(/\s+/g, "-")
            .toLowerCase()
            .replace(/[()]/g, "");
          return trainSlug === item.slug;
        });

        if (!train) return false;

        const routes = train.data.routes;
        const sourceIndex = routes.findIndex(
          (r) => r.city.toLowerCase().replace(/_/g, "") === item.station,
        );
        const destIndex = routes.findIndex(
          (r) => r.city.toLowerCase().replace(/_/g, "") === toStation,
        );

        return destIndex !== -1 && destIndex > sourceIndex;
      }

      return true;
    })
    .sort((a, b) => timeToMinutes(a.departure) - timeToMinutes(b.departure));

  const updateUrl = (newFrom, newTo) => {
    if (pathname === "/schedules") {
      const params = new URLSearchParams();
      if (newFrom) params.set("station", newFrom);
      if (newTo) params.set("to", newTo);
      router.replace(`/schedules?${params.toString()}`);
    }
  };

  const handleFromStationChange = (stationId) => {
    setFromStation(stationId);
    setFromSearch("");
    setFromDropdownOpen(false);
    if (stationId === toStation) {
      setToStation("");
      updateUrl(stationId, "");
    } else {
      updateUrl(stationId, toStation);
    }
  };

  const handleToStationChange = (stationId) => {
    setToStation(stationId);
    setDestSearch("");
    setDestDropdownOpen(false);
    updateUrl(fromStation, stationId);
  };

  const swapStations = () => {
    if (toStation) {
      const newFrom = toStation;
      const newTo = fromStation;
      setFromStation(newFrom);
      setToStation(newTo);
      updateUrl(newFrom, newTo);
    }
  };

  // Get station display names
  const fromStationName =
    allStationsList.find((s) => s.id === fromStation)?.label || fromStation;
  const toStationName = allStationsList.find((s) => s.id === toStation)?.label;

  const currentStationName = toStationName
    ? `${fromStationName} to ${toStationName}`
    : `${fromStationName} Station`;

  // Check if current fromStation is a Rajbari district station
  const isRajbariStation = rajbariButtons.some((s) => s.id === fromStation);

  return (
    <section id="schedule" className="py-20 bg-secondary/20">
      <div className="container px-4">
        <div className="mb-8">
          <SectionHeader
            title="Train Schedule"
            subtitle="Check departure times and plan your journey."
          />
          {showShareButton && (
            <div className="flex justify-center mt-4">
              <ShareButton
                url={
                  typeof window !== "undefined"
                    ? `${window.location.origin}/schedules?station=${fromStation}${toStation ? `&to=${toStation}` : ""}`
                    : ""
                }
                title={`${currentStationName} Schedule - Trains of Rajbari`}
                text={`Check train schedules for ${currentStationName}`}
              />
            </div>
          )}
        </div>

        {/* Filter Controls */}
        <div className="max-w-4xl mx-auto mb-8 space-y-6">
          {/* From Station Section */}
          <div className="flex flex-col items-center gap-3">
            <span className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Departing From
            </span>

            {/* Search input for ALL stations */}
            <div className="relative w-full max-w-sm" ref={fromRef}>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="text"
                  value={fromSearch}
                  onChange={(e) => {
                    setFromSearch(e.target.value);
                    setFromDropdownOpen(true);
                  }}
                  onFocus={() => setFromDropdownOpen(true)}
                  placeholder="Search any station (Khulna, Rajshahi, Jashore...)"
                  className="w-full pl-10 pr-8 py-2.5 text-sm bg-background border rounded-full focus:outline-none focus:ring-2 focus:ring-primary/50 placeholder:text-muted-foreground/60"
                />
                {fromSearch && (
                  <button
                    onClick={() => {
                      setFromSearch("");
                      setFromDropdownOpen(false);
                    }}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              {fromDropdownOpen && fromSearch && (
                <div className="absolute z-50 top-full mt-1 w-full max-h-60 overflow-y-auto bg-background border rounded-lg shadow-lg">
                  {allStationsList
                    .filter((s) =>
                      s.label.toLowerCase().includes(fromSearch.toLowerCase()),
                    )
                    .slice(0, 20)
                    .map((station) => (
                      <button
                        key={station.id}
                        onClick={() => handleFromStationChange(station.id)}
                        className={`w-full text-left px-4 py-2.5 text-sm hover:bg-muted transition-colors ${
                          station.id === fromStation
                            ? "bg-primary/10 text-primary font-medium"
                            : "text-foreground"
                        }`}
                      >
                        {station.label}
                      </button>
                    ))}
                  {allStationsList.filter((s) =>
                    s.label.toLowerCase().includes(fromSearch.toLowerCase()),
                  ).length === 0 && (
                    <div className="px-4 py-3 text-sm text-muted-foreground text-center">
                      No stations found
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Quick-access Rajbari district station buttons */}
            <div className="flex flex-wrap justify-center gap-2">
              {rajbariButtons.map((station) => (
                <button
                  key={station.id}
                  onClick={() => handleFromStationChange(station.id)}
                  className={`px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
                    fromStation === station.id
                      ? "bg-primary text-primary-foreground shadow-md scale-105"
                      : "bg-background hover:bg-muted text-muted-foreground border hover:border-primary/20"
                  }`}
                >
                  {station.label}
                </button>
              ))}
            </div>

            {/* Show selected non-Rajbari station as active badge */}
            {!isRajbariStation && (
              <div className="flex items-center gap-2 bg-primary/10 text-primary px-4 py-2 rounded-full text-sm font-medium">
                <span>{fromStationName}</span>
                <button
                  onClick={() => handleFromStationChange("rajbari")}
                  className="hover:bg-primary/20 rounded-full p-0.5"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              </div>
            )}
          </div>

          {/* Destination Filter */}
          <div className="flex flex-col items-center gap-4 pt-6 border-t border-dashed border-primary/20">
            <span className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Going To (Optional)
            </span>

            <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
              <div className="flex items-center gap-2 text-primary/80 bg-primary/5 px-4 py-2 rounded-lg">
                <span className="font-semibold text-sm">{fromStationName}</span>
                <ChevronRight className="w-4 h-4" />
                {toStation ? (
                  <span className="font-semibold text-sm">{toStationName}</span>
                ) : (
                  <span className="text-muted-foreground italic text-sm">
                    Any Destination
                  </span>
                )}
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={swapStations}
                  disabled={!toStation}
                  className="p-2 rounded-full hover:bg-muted text-muted-foreground disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                  title="Swap Stations"
                >
                  <ArrowRightLeft className="w-4 h-4" />
                </button>

                {/* Searchable destination input */}
                <div className="relative" ref={destRef}>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
                    <input
                      type="text"
                      value={destSearch || (toStation ? toStationName : "")}
                      onChange={(e) => {
                        setDestSearch(e.target.value);
                        setDestDropdownOpen(true);
                        if (!e.target.value) {
                          setToStation("");
                          updateUrl(fromStation, "");
                        }
                      }}
                      onFocus={() => setDestDropdownOpen(true)}
                      placeholder="Search destination..."
                      className="w-full pl-9 pr-8 py-2 text-sm bg-background border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 placeholder:text-muted-foreground/60 min-w-[220px]"
                    />
                    {(destSearch || toStation) && (
                      <button
                        onClick={() => {
                          setDestSearch("");
                          setToStation("");
                          setDestDropdownOpen(false);
                          updateUrl(fromStation, "");
                        }}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                      >
                        <X className="w-3.5 h-3.5" />
                      </button>
                    )}
                  </div>
                  {destDropdownOpen && (
                    <div className="absolute z-50 top-full mt-1 w-full max-h-60 overflow-y-auto bg-background border rounded-lg shadow-lg">
                      {allStationsList
                        .filter((s) => {
                          if (s.id === fromStation) return false;
                          if (!destSearch) return true;
                          return s.label
                            .toLowerCase()
                            .includes(destSearch.toLowerCase());
                        })
                        .slice(0, 20)
                        .map((station) => (
                          <button
                            key={station.id}
                            onClick={() => handleToStationChange(station.id)}
                            className={`w-full text-left px-4 py-2 text-sm hover:bg-muted transition-colors ${
                              station.id === toStation
                                ? "bg-primary/10 text-primary font-medium"
                                : "text-foreground"
                            }`}
                          >
                            {station.label}
                          </button>
                        ))}
                      {allStationsList.filter((s) => {
                        if (s.id === fromStation) return false;
                        if (!destSearch) return true;
                        return s.label
                          .toLowerCase()
                          .includes(destSearch.toLowerCase());
                      }).length === 0 && (
                        <div className="px-4 py-3 text-sm text-muted-foreground text-center">
                          No stations found
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Results */}
        <motion.div
          layout
          className="overflow-hidden rounded-lg border bg-background shadow-sm"
        >
          <div className="overflow-x-auto">
            <table className="w-full text-sm text-left">
              <thead className="text-xs uppercase bg-primary text-secondary-foreground">
                <tr>
                  <th className="px-6 py-4 font-bold">Train Name</th>
                  <th className="px-6 py-4 font-bold">Route</th>
                  <th className="px-6 py-4 font-bold">Arrival</th>
                  <th className="px-6 py-4 font-bold">Departure</th>
                  <th className="px-6 py-4 font-bold">Off Day</th>
                  <th className="px-6 py-4 font-bold w-10">Action</th>
                </tr>
              </thead>
              <tbody>
                <AnimatePresence mode="popLayout">
                  {filteredSchedule.map((train) => (
                    <motion.tr
                      key={train.id}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      exit={{ opacity: 0 }}
                      transition={{ duration: 0.15 }}
                      className="border-b last:border-0 hover:bg-muted/50 transition-colors"
                    >
                      <td className="px-6 py-4 font-medium">
                        {train.name}
                        {train.trainNumber && (
                          <span className="ml-2 text-xs text-muted-foreground">
                            ({train.trainNumber})
                          </span>
                        )}
                      </td>
                      <td className="px-6 py-4 text-muted-foreground">
                        {train.route}
                      </td>
                      <td className="px-6 py-4 text-muted-foreground">
                        {train.arrival}
                      </td>
                      <td
                        className={`px-6 py-4 font-medium ${train.departure === "Terminates" ? "text-muted-foreground italic" : "text-primary"}`}
                      >
                        {train.departure}
                      </td>
                      <td className="px-6 py-4">
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-destructive/10 text-destructive">
                          {train.offDay}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <Link
                          href={`/train/${train.slug}`}
                          className="inline-flex items-center justify-center h-8 px-3 text-xs font-medium transition-colors border rounded-full hover:bg-primary hover:text-primary-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        >
                          View Details
                        </Link>
                      </td>
                    </motion.tr>
                  ))}
                </AnimatePresence>
                {filteredSchedule.length === 0 && (
                  <tr>
                    <td
                      colSpan="6"
                      className="px-6 py-12 text-center text-muted-foreground"
                    >
                      <div className="flex flex-col items-center justify-center gap-2">
                        <span className="text-lg font-medium">
                          No trains found
                        </span>
                        <span>
                          No direct trains available from {fromStationName}{" "}
                          {toStation ? `to ${toStationName}` : ""}.
                        </span>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </motion.div>
      </div>
    </section>
  );
}
