import { useState } from "preact/hooks";
import type { Place } from "../../lib/types";
import type { UserLocation } from "../../lib/use-location";
import { haversineKm, formatDistance } from "../../lib/geo";
import { CategoryBadge } from "./CategoryBadge";
import { isOpenNow } from "../../lib/open-hours";

function copyAddress(address: string, setCopied: (v: boolean) => void) {
  navigator.clipboard.writeText(address).then(() => {
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  });
}

export function PlaceCard({ place, expanded, onToggle, location, passed, next }: {
  place: Place;
  expanded?: boolean;
  onToggle?: () => void;
  location?: UserLocation | null;
  passed?: boolean;
  next?: boolean;
}) {
  const [copied, setCopied] = useState(false);
  const dist = location && place.lat && place.lng
    ? haversineKm({ lat: location.lat, lng: location.lng }, { lat: place.lat, lng: place.lng })
    : null;
  const open = isOpenNow(place);
  const closed = open === false;

  return (
    <div class={`place-card ${expanded ? "expanded" : ""}${closed ? " place-card-closed" : ""}${passed ? " place-card-passed" : ""}${next ? " place-card-next" : ""}`} onClick={onToggle}>
      {next && <div class="place-next-badge">NEXT</div>}
      {place.photo && (
        <div class="place-card-photo">
          <img src={place.photo} alt={place.name} loading="lazy" />
        </div>
      )}
      <div class="place-card-top">
        <div class="place-card-name">{place.name}</div>
        <div class="place-card-badges">
          {closed && <span class="place-badge-closed">CLOSED</span>}
          {dist !== null && (
            <span class="place-dist">{formatDistance(dist)}</span>
          )}
          <CategoryBadge category={place.category} />
        </div>
      </div>

      {place.category === "fuel" && place.cost && (
        <div class="place-fuel-price">{place.cost}</div>
      )}

      {place.description && (
        <div class="place-card-desc">{place.description}</div>
      )}

      {expanded && (
        <div class="place-card-detail">
          {place.address && (
            <div
              class="place-detail-row place-address-copy"
              onClick={e => { e.stopPropagation(); copyAddress(place.address!, setCopied); }}
            >
              <span class="place-detail-label">Address</span>
              <span class="place-detail-val">
                {place.address}
                <span class="place-copy-hint">{copied ? " Copied" : " Tap to copy"}</span>
              </span>
            </div>
          )}
          {place.hours && (
            <div class="place-detail-row">
              <span class="place-detail-label">Hours</span>
              <span class="place-detail-val">{place.hours}</span>
            </div>
          )}
          {place.cost && (
            <div class="place-detail-row">
              <span class="place-detail-label">Cost</span>
              <span class="place-detail-val">{place.cost}</span>
            </div>
          )}
          {place.phone && (
            <div class="place-detail-row">
              <span class="place-detail-label">Phone</span>
              <span class="place-detail-val">
                <a href={`tel:${place.phone}`} class="place-phone-link" onClick={e => e.stopPropagation()}>
                  {place.phone}
                </a>
              </span>
            </div>
          )}
          {place.website && (
            <div class="place-detail-row">
              <span class="place-detail-label">Web</span>
              <span class="place-detail-val">
                <a href={place.website} target="_blank" rel="noopener" class="place-web-link" onClick={e => e.stopPropagation()}>
                  Visit
                </a>
              </span>
            </div>
          )}
          {place.recommendations && place.recommendations.length > 0 && (
            <div class="place-recs">
              <div class="place-recs-label">Recommended</div>
              {place.recommendations.map(rec => (
                <div key={rec.item} class="place-rec-row">
                  <div class="place-rec-item">
                    <span class="place-rec-name">{rec.item}</span>
                    {rec.note && <span class="place-rec-note">{rec.note}</span>}
                  </div>
                  <span class="place-rec-price">{rec.price}</span>
                </div>
              ))}
            </div>
          )}
          {place.action && (
            <a
              href={place.action.href}
              class="place-action-btn"
              onClick={e => e.stopPropagation()}
            >
              {place.action.label}
            </a>
          )}
          {place.tags && place.tags.length > 0 && (
            <div class="place-tags">
              {place.tags.map(tag => (
                <span key={tag} class="place-tag">{tag}</span>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
