"use client";

import { useEffect, useState } from "react";

interface Tour {
  id: number;
  city: string;
  start_date: string;
  end_date: string;
  notes: string | null;
  created_at: string;
}

export default function ManageToursPage() {
  const [tours, setTours] = useState<Tour[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState<number | null>(null);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const [city, setCity] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [notes, setNotes] = useState("");

  useEffect(() => {
    loadTours();
  }, []);

  async function loadTours() {
    try {
      const res = await fetch("/api/tours");
      const data = await res.json();
      setTours(data.data || []);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!city.trim() || !startDate || !endDate) {
      setError("City, start date, and end date are required.");
      return;
    }

    if (new Date(endDate) <= new Date(startDate)) {
      setError("End date must be after start date.");
      return;
    }

    setSaving(true);
    setError("");
    setSuccess("");

    try {
      const res = await fetch("/api/tours", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          city: city.trim(),
          start_date: startDate,
          end_date: endDate,
          notes: notes.trim() || null,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Failed to create tour");
        return;
      }

      setSuccess("Tour created successfully!");
      setCity("");
      setStartDate("");
      setEndDate("");
      setNotes("");
      loadTours();
    } catch {
      setError("Failed to create tour. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(tourId: number) {
    setDeleting(tourId);
    try {
      await fetch(`/api/tours?id=${tourId}`, { method: "DELETE" });
      setTours((prev) => prev.filter((t) => t.id !== tourId));
    } catch {
      // ignore
    } finally {
      setDeleting(null);
    }
  }

  const inputClass =
    "w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary";

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <h1 className="text-2xl font-bold">Tour Calendar</h1>
      <p className="text-text-muted">
        Let clients know where you will be travelling. Active tours are shown on your profile.
      </p>

      {/* Create Tour Form */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Add New Tour</h2>
        <form onSubmit={handleCreate} className="space-y-4">
          <div>
            <label className="block text-text-muted text-sm mb-1">City</label>
            <input
              type="text"
              value={city}
              onChange={(e) => setCity(e.target.value)}
              placeholder="e.g. London, Paris, Dubai..."
              className={inputClass}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-text-muted text-sm mb-1">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block text-text-muted text-sm mb-1">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className={inputClass}
              />
            </div>
          </div>

          <div>
            <label className="block text-text-muted text-sm mb-1">Notes (optional)</label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Additional details about your tour..."
              rows={3}
              className={`${inputClass} resize-none`}
            />
          </div>

          {error && <p className="text-red-400 text-sm">{error}</p>}
          {success && <p className="text-green-400 text-sm">{success}</p>}

          <button
            type="submit"
            disabled={saving}
            className="bg-gold hover:bg-gold-light text-black font-semibold px-6 py-2.5 rounded-lg transition-all duration-200 shadow-glow disabled:opacity-50"
          >
            {saving ? "Creating..." : "Add Tour"}
          </button>
        </form>
      </div>

      {/* Existing Tours */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Your Tours</h2>

        {loading ? (
          <p className="text-text-muted text-center py-8">Loading tours...</p>
        ) : tours.length === 0 ? (
          <p className="text-text-muted text-center py-8">
            No tours yet. Add your first tour above.
          </p>
        ) : (
          <div className="space-y-3">
            {tours.map((tour) => {
              const isActive = new Date(tour.end_date) >= new Date();
              return (
                <div
                  key={tour.id}
                  className={`flex items-center justify-between p-4 rounded-lg border ${
                    isActive
                      ? "bg-surface-light border-gold/20"
                      : "bg-surface-light/50 border-surface-light opacity-60"
                  }`}
                >
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold">{tour.city}</h3>
                      {isActive && (
                        <span className="text-xs bg-green-500/20 text-green-400 px-2 py-0.5 rounded-full">
                          Active
                        </span>
                      )}
                    </div>
                    <p className="text-text-muted text-sm">
                      {new Date(tour.start_date).toLocaleDateString()} -{" "}
                      {new Date(tour.end_date).toLocaleDateString()}
                    </p>
                    {tour.notes && (
                      <p className="text-text-muted text-xs">{tour.notes}</p>
                    )}
                  </div>
                  <button
                    onClick={() => handleDelete(tour.id)}
                    disabled={deleting === tour.id}
                    className="text-red-400 hover:text-red-300 text-sm transition-colors disabled:opacity-50"
                  >
                    {deleting === tour.id ? "Deleting..." : "Delete"}
                  </button>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
