"use client";

import { useState } from "react";
import Link from "next/link";
import { useTrips, useDeleteTrip } from "@/lib/hooks";
import type { TripRow } from "@/lib/hooks";
import { CreateTripModal } from "@/components/create-trip-modal";

function fmtDate(d: string | null) {
  if (!d) return null;
  return new Date(d).toLocaleDateString("en-AU", { day: "2-digit", month: "short", year: "numeric" });
}

function TripCard({ trip, onEdit, onDelete }: { trip: TripRow; onEdit: () => void; onDelete: () => void }) {
  const dateRange = trip.start_date && trip.end_date
    ? `${fmtDate(trip.start_date)} – ${fmtDate(trip.end_date)}`
    : trip.start_date
    ? `From ${fmtDate(trip.start_date)}`
    : "No dates set";

  return (
    <div className="relative bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden hover:border-zinc-600 transition-colors group">
      <div className="absolute left-0 top-0 bottom-0 w-1 rounded-l-xl" style={{ backgroundColor: trip.color }} />
      <Link href={`/trips/${trip.id}`} className="block p-5 pl-6">
        <p className="font-semibold text-base truncate">{trip.name}</p>
        {trip.description && (
          <p className="text-xs text-zinc-500 mt-0.5 truncate">{trip.description}</p>
        )}
        <p className="text-xs text-zinc-600 mt-1">{dateRange}</p>
        <div className="mt-4 flex items-baseline gap-3">
          <span className="text-2xl font-semibold tabular-nums">${Number(trip.total_spend).toFixed(2)}</span>
          <span className="text-xs text-zinc-500">{trip.transaction_count} transactions</span>
        </div>
      </Link>
      <div className="px-5 pb-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
        <button
          onClick={onEdit}
          className="text-xs text-zinc-400 hover:text-white px-2 py-1 rounded hover:bg-zinc-800 transition-colors"
        >
          Edit
        </button>
        <button
          onClick={onDelete}
          className="text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-zinc-800 transition-colors"
        >
          Delete
        </button>
      </div>
    </div>
  );
}

export default function TripsPage() {
  const { data: trips = [], isLoading } = useTrips();
  const deleteTrip = useDeleteTrip();
  const [modal, setModal] = useState<{ trip?: TripRow } | null>(null);

  const active = trips.filter((t) => !t.archived);
  const archived = trips.filter((t) => t.archived);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-display">Trips</h2>
          <p className="text-sm text-zinc-500 mt-0.5">Group and analyse expenses by trip</p>
        </div>
        <button
          onClick={() => setModal({})}
          className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-sm font-medium transition-colors"
        >
          + New Trip
        </button>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="bg-zinc-900 border border-zinc-800 rounded-xl p-5 animate-pulse">
              <div className="h-4 bg-zinc-800 rounded w-2/3 mb-3" />
              <div className="h-3 bg-zinc-800 rounded w-1/3 mb-4" />
              <div className="h-7 bg-zinc-800 rounded w-1/2" />
            </div>
          ))}
        </div>
      ) : active.length === 0 ? (
        <div className="text-center py-20 text-zinc-600">
          <svg className="w-12 h-12 mx-auto mb-4 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
          <p className="text-lg font-medium mb-1">No trips yet</p>
          <p className="text-sm">Create a trip to group and analyse expenses — holidays, events, work travel.</p>
          <button
            onClick={() => setModal({})}
            className="mt-4 px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-sm font-medium"
          >
            Create your first trip
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {active.map((trip) => (
            <TripCard
              key={trip.id}
              trip={trip}
              onEdit={() => setModal({ trip })}
              onDelete={() => {
                if (confirm(`Delete "${trip.name}"? This will unlink all transactions from this trip.`)) {
                  deleteTrip.mutate(trip.id);
                }
              }}
            />
          ))}
        </div>
      )}

      {archived.length > 0 && (
        <details className="group/archived">
          <summary className="text-sm text-zinc-500 cursor-pointer hover:text-zinc-300 list-none flex items-center gap-2 select-none">
            <svg className="w-3 h-3 transition-transform group-open/archived:rotate-90" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M7.293 4.707a1 1 0 011.414 0L14 10l-5.293 5.293a1 1 0 01-1.414-1.414L11.586 10 6.586 5a1 1 0 010-1.293z" clipRule="evenodd" />
            </svg>
            Archived ({archived.length})
          </summary>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-3">
            {archived.map((trip) => (
              <div key={trip.id} className="relative bg-zinc-900/50 border border-zinc-800 rounded-xl overflow-hidden opacity-60 hover:opacity-100 transition-opacity group">
                <div className="absolute left-0 top-0 bottom-0 w-1 rounded-l-xl" style={{ backgroundColor: trip.color }} />
                <Link href={`/trips/${trip.id}`} className="block p-5 pl-6">
                  <p className="font-medium truncate">{trip.name}</p>
                  <p className="text-xs text-zinc-600 mt-1">${Number(trip.total_spend).toFixed(2)} · {trip.transaction_count} transactions</p>
                </Link>
                <div className="px-5 pb-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={() => setModal({ trip })}
                    className="text-xs text-zinc-400 hover:text-white px-2 py-1 rounded hover:bg-zinc-800"
                  >
                    Edit
                  </button>
                </div>
              </div>
            ))}
          </div>
        </details>
      )}

      {modal !== null && (
        <CreateTripModal trip={modal.trip} onClose={() => setModal(null)} />
      )}
    </div>
  );
}
