import { Search, CalendarIcon } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { cn } from "@/lib/utils";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { destinations, classOptions } from "@/data/routes";
import omLogo from "@/assets/orange-money-logo.webp";
import momoLogo from "@/assets/mtn-momo-logo.webp";

const SearchSection = () => {
  const navigate = useNavigate();
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [travelClass, setTravelClass] = useState("Business Class");
  const [tripType, setTripType] = useState("aller-simple");
  const [seats, setSeats] = useState(1);
  const [travelDate, setTravelDate] = useState<Date>(new Date());
  const [returnDate, setReturnDate] = useState<Date | undefined>();

  const toLocalDateStr = (d: Date) => {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  };

  const handleSearch = () => {
    if (!from || !to || from === to) return;
    const params = new URLSearchParams({
      from,
      to,
      class: travelClass,
      type: tripType,
      date: toLocalDateStr(travelDate),
      seats: String(seats),
    });
    if (tripType === "aller-retour" && returnDate) {
      params.set("returnDate", toLocalDateStr(returnDate));
    }
    navigate(`/resultats?${params.toString()}`);
  };

  return (
    <section id="search" className="relative -mt-24 md:-mt-28 z-20 container mx-auto px-4">
      <div className="glass-card rounded-2xl p-6 md:p-8 border border-border">
        <h2 className="text-xl font-bold text-foreground mb-6 flex items-center gap-2">
          <Search className="h-5 w-5 text-primary" />
          Rechercher un trajet
        </h2>
        <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Ville de départ</label>
            <select value={from} onChange={e => setFrom(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm">
              <option value="">D'où partez-vous ?</option>
              {destinations.map(d => <option key={d} value={d}>{d}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Ville d'arrivée</label>
            <select value={to} onChange={e => setTo(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm">
              <option value="">Où allez-vous ?</option>
              {destinations.map(d => <option key={d} value={d}>{d}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Date de départ</label>
            <Popover>
              <PopoverTrigger asChild>
                <button className={cn("w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm flex items-center gap-2 text-left", !travelDate && "text-muted-foreground")}>
                  <CalendarIcon className="h-4 w-4 text-muted-foreground" />
                  {travelDate ? format(travelDate, "dd MMM yyyy", { locale: fr }) : "Choisir une date"}
                </button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={travelDate}
                  onSelect={(d) => { if (d) setTravelDate(d); }}
                  disabled={(date) => date < new Date(new Date().setHours(0, 0, 0, 0))}
                  initialFocus
                  className={cn("p-3 pointer-events-auto")}
                />
              </PopoverContent>
            </Popover>
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Classe</label>
            <select value={travelClass} onChange={e => setTravelClass(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm">
              {classOptions.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Type</label>
            <select value={tripType} onChange={e => setTripType(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm">
              <option value="aller-simple">Aller simple</option>
              <option value="aller-retour">Aller-retour</option>
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Nombre de places</label>
            <select value={seats} onChange={e => setSeats(Number(e.target.value))} className="w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm">
              {Array.from({ length: 10 }, (_, i) => i + 1).map(n => (
                <option key={n} value={n}>{n} {n > 1 ? "places" : "place"}</option>
              ))}
            </select>
          </div>
          {tripType === "aller-retour" && (
            <div>
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Date de retour</label>
              <Popover>
                <PopoverTrigger asChild>
                  <button className={cn("w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm flex items-center gap-2 text-left", !returnDate && "text-muted-foreground")}>
                    <CalendarIcon className="h-4 w-4 text-muted-foreground" />
                    {returnDate ? format(returnDate, "dd MMM yyyy", { locale: fr }) : "Choisir une date"}
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={returnDate}
                    onSelect={(d) => setReturnDate(d)}
                    disabled={(date) => date < travelDate}
                    initialFocus
                    className={cn("p-3 pointer-events-auto")}
                  />
                </PopoverContent>
              </Popover>
            </div>
          )}
        </div>
        <div className="mt-4 flex flex-col-reverse sm:flex-row sm:items-center sm:justify-between gap-3">
          <div className="flex items-center gap-2">
            <span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">Paiement</span>
            <img src={omLogo} alt="Orange Money" className="h-6 w-auto rounded" />
            <img src={momoLogo} alt="MTN MoMo" className="h-6 w-auto rounded" />
          </div>
          <button onClick={handleSearch} className="w-full sm:w-auto hero-gradient text-primary-foreground font-semibold py-2.5 px-8 rounded-lg hover:brightness-110 transition text-sm">
            Rechercher
          </button>
        </div>
      </div>
    </section>
  );
};

export default SearchSection;
