"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

interface HappyHour {
  id: number;
  day_of_week: number;
  start_time: string;
  end_time: string;
  discount_pct: number;
}

const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

export default function HappyHourPage() {
  const { status } = useSession();
  const router = useRouter();
  const [windows, setWindows] = useState<HappyHour[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Form
  const [dayOfWeek, setDayOfWeek] = useState("1");
  const [startTime, setStartTime] = useState("18:00");
  const [endTime, setEndTime] = useState("20:00");
  const [discountPct, setDiscountPct] = useState("20");

  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
  }, [status, router]);

  useEffect(() => {
    // Defer the GET until session resolution so anonymous visitors don't
    // briefly fire an authenticated request that just returns 401.
    if (status === "authenticated") loadWindows();
  }, [status]);

  async function loadWindows() {
    try {
      const res = await fetch("/api/happy-hour");
      if (res.ok) {
        const data = await res.json();
        setWindows(data.data || []);
      }
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    // Reject impossible windows before round-tripping the API. Time strings
    // are HH:MM, so lexical comparison is correct.
    if (endTime <= startTime) {
      setError("End time must be after the start time.");
      return;
    }
    setSubmitting(true);
    setError(null);

    try {
      const res = await fetch("/api/happy-hour", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          day_of_week: Number(dayOfWeek),
          start_time: startTime,
          end_time: endTime,
          discount_pct: Number(discountPct),
        }),
      });

      if (res.ok) {
        loadWindows();
        setStartTime("18:00");
        setEndTime("20:00");
      } else {
        const data = await res.json();
        setError(data.error || "Failed to create happy hour");
      }
    } catch {
      setError("Network error");
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: number) {
    try {
      await fetch("/api/happy-hour", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      setWindows((prev) => prev.filter((w) => w.id !== id));
    } catch {
      // silently fail
    }
  }

  if (status === "loading" || loading) {
    return (
      <div className="max-w-3xl mx-auto space-y-6">
        <div className="h-8 w-48 bg-surface-light rounded animate-pulse" />
        <div className="bg-surface rounded-xl p-6 animate-pulse space-y-4">
          <div className="h-10 bg-surface-light rounded" />
          <div className="h-10 bg-surface-light rounded" />
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <h1 className="text-2xl font-bold">Happy Hour Pricing</h1>
      <p className="text-text-muted text-sm">
        Set discount windows to attract more clients during specific times. A badge will appear on your profile during active happy hours.
      </p>

      {/* Create form */}
      <form onSubmit={handleSubmit} className="bg-surface rounded-xl p-6 border border-white/5 space-y-4">
        <h2 className="text-lg font-semibold">Add Discount Window</h2>

        {error && (
          <div className="bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-2.5 text-sm text-red-400">
            {error}
          </div>
        )}

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text-muted mb-1">Day of Week</label>
            <select
              value={dayOfWeek}
              onChange={(e) => setDayOfWeek(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
            >
              {DAYS.map((day, i) => (
                <option key={i} value={i}>{day}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-muted mb-1">Discount %</label>
            <select
              value={discountPct}
              onChange={(e) => setDiscountPct(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
            >
              {[10, 15, 20, 25, 30, 35, 40, 45, 50].map((pct) => (
                <option key={pct} value={pct}>{pct}%</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-muted mb-1">Start Time</label>
            <input
              type="time"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              required
              className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-text-muted mb-1">End Time</label>
            <input
              type="time"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              required
              className="w-full rounded-lg border border-white/10 bg-surface-light px-4 py-2.5 text-text focus:border-primary focus:outline-none"
            />
          </div>
        </div>

        <button
          type="submit"
          disabled={submitting}
          className="gradient-gold text-background px-6 py-2.5 rounded-lg font-semibold disabled:opacity-40 hover:opacity-90 transition-opacity"
        >
          {submitting ? "Saving..." : "Add Happy Hour"}
        </button>
      </form>

      {/* Existing windows */}
      <div className="bg-surface rounded-xl p-6 border border-white/5">
        <h2 className="text-lg font-semibold mb-4">Your Happy Hour Windows</h2>

        {windows.length === 0 ? (
          <p className="text-text-muted text-sm">No happy hour windows set.</p>
        ) : (
          <div className="space-y-3">
            {windows.map((w) => (
              <div
                key={w.id}
                className="flex items-center justify-between p-4 bg-surface-light rounded-lg border border-white/5"
              >
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-full bg-orange-500/10 flex items-center justify-center shrink-0">
                    <span className="text-lg">&#x1F525;</span>
                  </div>
                  <div>
                    <p className="font-medium text-text">{DAYS[w.day_of_week]}</p>
                    <p className="text-sm text-text-muted">
                      {w.start_time.slice(0, 5)} - {w.end_time.slice(0, 5)}
                    </p>
                  </div>
                  <span className="bg-orange-500/10 text-orange-400 text-sm font-semibold px-3 py-1 rounded-full">
                    {w.discount_pct}% off
                  </span>
                </div>
                <button
                  onClick={() => handleDelete(w.id)}
                  className="text-red-400 hover:text-red-300 text-sm font-medium transition-colors"
                >
                  Remove
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
