"use client";

import { useState } from "react";
import { useCreateTrip, useUpdateTrip } from "@/lib/hooks";
import type { TripRow } from "@/lib/hooks";

export function CreateTripModal({
  trip,
  onClose,
}: {
  trip?: TripRow;
  onClose: () => void;
}) {
  const isEdit = !!trip;
  const [name, setName] = useState(trip?.name ?? "");
  const [description, setDescription] = useState(trip?.description ?? "");
  const [startDate, setStartDate] = useState(trip?.start_date?.slice(0, 10) ?? "");
  const [endDate, setEndDate] = useState(trip?.end_date?.slice(0, 10) ?? "");
  const [color, setColor] = useState(trip?.color ?? "#6366f1");
  const [archived, setArchived] = useState(trip?.archived ?? false);
  const [error, setError] = useState("");

  const createTrip = useCreateTrip();
  const updateTrip = useUpdateTrip();
  const isPending = createTrip.isPending || updateTrip.isPending;

  async function handleSave() {
    setError("");
    if (!name.trim()) { setError("Name is required"); return; }
    try {
      if (isEdit) {
        await updateTrip.mutateAsync({
          id: trip!.id,
          name: name.trim(),
          description: description || null,
          start_date: startDate || null,
          end_date: endDate || null,
          color,
          archived,
        });
      } else {
        await createTrip.mutateAsync({
          name: name.trim(),
          description: description || null,
          start_date: startDate || null,
          end_date: endDate || null,
          color,
          archived,
        });
      }
      onClose();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to save");
    }
  }

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60" onClick={onClose}>
      <div
        className="bg-zinc-900 border border-zinc-700 rounded-xl w-full max-w-md mx-4 shadow-2xl flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="px-6 pt-5 pb-4 border-b border-zinc-800">
          <h3 className="font-semibold text-sm text-zinc-300">{isEdit ? "Edit Trip" : "New Trip"}</h3>
        </div>

        <div className="px-6 py-4 space-y-4">
          <div>
            <label className="block text-xs text-zinc-500 mb-1">Name *</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Europe 2026"
              className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
            />
          </div>

          <div>
            <label className="block text-xs text-zinc-500 mb-1">Description</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={2}
              placeholder="Optional notes about this trip"
              className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm resize-none focus:outline-none focus:border-zinc-500"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs text-zinc-500 mb-1">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
              />
            </div>
            <div>
              <label className="block text-xs text-zinc-500 mb-1">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
              />
            </div>
          </div>

          <div className="flex items-center gap-4">
            <div>
              <label className="block text-xs text-zinc-500 mb-1">Color</label>
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="h-9 w-16 rounded border border-zinc-700 bg-zinc-800 cursor-pointer"
              />
            </div>
            {isEdit && (
              <label className="flex items-center gap-2 text-sm text-zinc-400 mt-4 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={archived}
                  onChange={(e) => setArchived(e.target.checked)}
                  className="accent-indigo-500"
                />
                Archived
              </label>
            )}
          </div>
        </div>

        <div className="px-6 py-4 border-t border-zinc-800 flex gap-2 items-center">
          {error && <p className="text-red-400 text-xs mr-auto">{error}</p>}
          <div className="flex gap-2 ml-auto">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg text-sm"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleSave}
              disabled={isPending}
              className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
            >
              {isPending ? "Saving…" : isEdit ? "Save Changes" : "Create Trip"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
