"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import Link from "next/link";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { createTripAction } from "@/features/trip/actions";
import { ImageUrlInput } from "@/features/trip/components/image-url-input";
import { formatLocalCalendarYmd } from "@/lib/trip-dates";

const SAMPLE_MOUNTAINS = [
  { name: "Gunung Papandayan", location: "Garut, Jawa Barat" },
  { name: "Gunung Ciremai", location: "Kuningan, Jawa Barat" },
  { name: "Gunung Pangrango", location: "Bogor/Cianjur, Jawa Barat" },
  { name: "Gunung Gede", location: "Bogor/Cianjur, Jawa Barat" },
  { name: "Gunung Tangkuban Parahu", location: "Bandung, Jawa Barat" },
  { name: "Gunung Bukit Tunggul", location: "Bandung, Jawa Barat" },
  { name: "Gunung Malabar", location: "Bandung, Jawa Barat" },
  { name: "Gunung Guntur", location: "Garut, Jawa Barat" },
];

function formatRupiahInput(value: string): string {
  const num = value.replace(/\D/g, "");
  return num.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

function parseRupiahInput(value: string): string {
  return value.replace(/\./g, "");
}

export default function CreateTripPage() {
  const { data: session } = useSession();
  const router = useRouter();
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const [startDate, setStartDate] = useState<Date | null>(null);
  const [endDate, setEndDate] = useState<Date | null>(null);
  const [priceDisplay, setPriceDisplay] = useState("");

  if (!session?.user) {
    return (
      <div className="flex min-h-[calc(100vh-3.5rem)] items-center justify-center px-4">
        <div className="text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary-50 text-3xl">
            🔒
          </div>
          <p className="mb-4 text-neutral-500">
            Kamu harus login untuk membuat trip.
          </p>
          <Link
            href="/login"
            className="inline-block rounded-xl bg-primary-600 px-6 py-2.5 text-sm font-semibold text-white hover:bg-primary-700"
          >
            Login
          </Link>
        </div>
      </div>
    );
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");

    if (!startDate) {
      setError("Tanggal berangkat harus diisi");
      return;
    }

    setLoading(true);

    const formData = new FormData(e.currentTarget);
    // Hari kalender lokal → YYYY-MM-DD (bukan toISOString, supaya tidak geser ke UTC)
    formData.set("date", formatLocalCalendarYmd(startDate));
    if (endDate) {
      const startYmd = formatLocalCalendarYmd(startDate);
      const endYmd = formatLocalCalendarYmd(endDate);
      // Satu hari: tanggal pulang sama dengan berangkat → jangan kirim endDate (trip 1 hari)
      if (endYmd !== startYmd) {
        formData.set("endDate", endYmd);
      }
    }
    // Set raw price number
    formData.set("price", parseRupiahInput(priceDisplay));

    const result = await createTripAction(formData);

    setLoading(false);

    if (result.error) {
      setError(result.error);
    } else if (result.tripId) {
      router.push(`/trips/${result.tripId}`);
    }
  }

  function handleMountainSelect(e: React.ChangeEvent<HTMLSelectElement>) {
    const selected = SAMPLE_MOUNTAINS.find((m) => m.name === e.target.value);
    if (selected) {
      const form = e.target.form;
      if (form) {
        const mountainInput = form.elements.namedItem(
          "mountain"
        ) as HTMLInputElement;
        const locationInput = form.elements.namedItem(
          "location"
        ) as HTMLInputElement;
        mountainInput.value = selected.name;
        locationInput.value = selected.location;
      }
    }
  }

  function handleDateChange(dates: [Date | null, Date | null]) {
    const [start, end] = dates;
    setStartDate(start);
    setEndDate(end);
  }

  function handlePriceChange(e: React.ChangeEvent<HTMLInputElement>) {
    const raw = e.target.value.replace(/\D/g, "");
    setPriceDisplay(raw ? formatRupiahInput(raw) : "");
  }

  return (
    <div className="mx-auto max-w-2xl px-4 py-6 sm:py-8">
      <div className="mb-4 sm:mb-6">
        <h1 className="text-2xl font-bold text-neutral-800">Buat Trip Baru</h1>
        <p className="mt-1 text-sm text-neutral-500">
          Ajak teman baru naik gunung bareng!
        </p>
      </div>

      <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-sm">
        {error && (
          <div className="mb-4 rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Mountain Quick Picker */}
          <div className="rounded-xl bg-primary-50 p-4">
            <label className="mb-2 flex items-center gap-1.5 text-sm font-bold text-primary-800">
              <span>🏔️</span> Pilih Gunung Jawa Barat
            </label>
            <select
              onChange={handleMountainSelect}
              className="w-full rounded-lg border border-primary-200 bg-white px-4 py-2.5 text-sm text-neutral-800"
              defaultValue=""
            >
              <option value="" disabled>
                Pilih gunung...
              </option>
              {SAMPLE_MOUNTAINS.map((m) => (
                <option key={m.name} value={m.name}>
                  {m.name} — {m.location}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label htmlFor="title" className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Judul Trip
            </label>
            <input
              id="title"
              name="title"
              type="text"
              required
              className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
              placeholder="contoh: Open Trip Papandayan Weekend"
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label htmlFor="mountain" className="mb-1.5 block text-sm font-semibold text-neutral-700">
                Nama Gunung
              </label>
              <input
                id="mountain"
                name="mountain"
                type="text"
                required
                className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
                placeholder="Gunung Papandayan"
              />
            </div>
            <div>
              <label htmlFor="location" className="mb-1.5 block text-sm font-semibold text-neutral-700">
                Lokasi
              </label>
              <input
                id="location"
                name="location"
                type="text"
                required
                className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
                placeholder="Garut, Jawa Barat"
              />
            </div>
          </div>

          <div>
            <label htmlFor="description" className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Deskripsi
            </label>
            <textarea
              id="description"
              name="description"
              rows={4}
              className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
              placeholder="Detail trip, itinerary, meeting point, fasilitas..."
            />
          </div>

          <ImageUrlInput />

          {/* Date Range & Participants & Price */}
          <div className="grid gap-4 sm:grid-cols-2">
            {/* Date Range Picker */}
            <div>
              <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
                Tanggal Berangkat — Pulang
              </label>
              <p className="mb-1.5 text-[11px] leading-snug text-neutral-500 sm:text-xs">
                Pilih satu tanggal untuk trip <span className="font-medium">satu hari</span>
                . Pilih rentang untuk trip <span className="font-medium">lebih dari satu hari</span>
                . Tanggal disimpan sebagai hari kalender yang kamu klik; filter Open Trip memakai{" "}
                <span className="font-medium">UTC</span> yang sama.
              </p>
              <div className="relative">
                <span className="absolute left-3 top-1/2 z-10 -translate-y-1/2 text-neutral-400">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 20 20"
                    fill="currentColor"
                    className="h-4 w-4"
                  >
                    <path
                      fillRule="evenodd"
                      d="M5.75 2a.75.75 0 01.75.75V4h7V2.75a.75.75 0 011.5 0V4h.25A2.75 2.75 0 0118 6.75v8.5A2.75 2.75 0 0115.25 18H4.75A2.75 2.75 0 012 15.25v-8.5A2.75 2.75 0 014.75 4H5V2.75A.75.75 0 015.75 2zm-1 5.5c-.69 0-1.25.56-1.25 1.25v6.5c0 .69.56 1.25 1.25 1.25h10.5c.69 0 1.25-.56 1.25-1.25v-6.5c0-.69-.56-1.25-1.25-1.25H4.75z"
                      clipRule="evenodd"
                    />
                  </svg>
                </span>
                <DatePicker
                  selectsRange
                  startDate={startDate}
                  endDate={endDate}
                  onChange={handleDateChange}
                  minDate={new Date()}
                  placeholderText="Pilih tanggal..."
                  dateFormat="dd MMM yyyy"
                  isClearable
                  className="w-full rounded-xl border border-neutral-200 bg-neutral-50 py-2.5 pl-9 pr-3 text-sm text-neutral-800 placeholder:text-neutral-400 focus:border-primary-500 focus:bg-white"
                />
              </div>
            </div>

            {/* Max Participants */}
            <div>
              <label htmlFor="maxParticipants" className="mb-1.5 block text-sm font-semibold text-neutral-700">
                Maks Peserta
              </label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 20 20"
                    fill="currentColor"
                    className="h-4 w-4"
                  >
                    <path d="M7 8a3 3 0 100-6 3 3 0 000 6zM14.5 9a2.5 2.5 0 100-5 2.5 2.5 0 000 5zM1.615 16.428a1.224 1.224 0 01-.569-1.175 6.002 6.002 0 0111.908 0c.058.467-.172.92-.57 1.174A9.953 9.953 0 017 18a9.953 9.953 0 01-5.385-1.572zM14.5 16h-.106c.07-.297.088-.611.048-.933a7.47 7.47 0 00-1.588-3.755 4.502 4.502 0 015.874 2.636.818.818 0 01-.36.98A7.465 7.465 0 0114.5 16z" />
                  </svg>
                </span>
                <input
                  id="maxParticipants"
                  name="maxParticipants"
                  type="number"
                  required
                  min={1}
                  className="w-full rounded-xl border border-neutral-200 bg-neutral-50 py-2.5 pl-9 pr-4 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
                  placeholder="10"
                />
              </div>
            </div>
          </div>

          {/* Price with Rp format */}
          <div>
            <label htmlFor="priceDisplay" className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Harga per Orang
            </label>
            <div className="relative">
              <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-neutral-500">
                Rp
              </span>
              <input
                id="priceDisplay"
                type="text"
                inputMode="numeric"
                required
                value={priceDisplay}
                onChange={handlePriceChange}
                className="w-full rounded-xl border border-neutral-200 bg-neutral-50 py-2.5 pl-10 pr-4 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
                placeholder="150.000"
              />
              {/* Hidden input for form submission */}
              <input type="hidden" name="price" value={parseRupiahInput(priceDisplay)} />
            </div>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-xl bg-primary-600 py-3 text-sm font-bold text-white shadow-lg shadow-primary-600/20 transition-colors hover:bg-primary-700 disabled:opacity-50"
          >
            {loading ? "Membuat Trip..." : "Buat Trip"}
          </button>
        </form>
      </div>
    </div>
  );
}
