
import { TripStep } from "@/types";
import { ExternalLink } from "lucide-react";
import { getStepTypeById } from "@/types/stepTypes";

interface LinkItem {
  url: string;
  title: string;
}

interface DetailSection {
  title: string;
  items?: { label: string; value: string | number | null }[];
  links?: LinkItem[];
}

interface StepDetailContentProps {
  step: TripStep;
  isPlanner: boolean;
  dayDate?: string | null;
}

export function StepDetailContent({ step, isPlanner, dayDate }: StepDetailContentProps) {
  // Get step type info and colors
  const stepType = step.stepType || 'activity';
  const stepTypeInfo = getStepTypeById(stepType);
  const { accent: accentColor } = stepTypeInfo.colors;

  // Get all links (old and new structure)
  const allLinks: LinkItem[] = [];
  if (step.link) {
    allLinks.push({ url: step.link, title: "Plus d'informations" });
  }
  if (step.links && step.links.length > 0) {
    // Make sure we don't duplicate the main link
    const mainLinkExists = step.link && step.links.some(link => link.url === step.link);
    if (!mainLinkExists && step.link) {
      allLinks.push({ url: step.link, title: "Lien principal" });
    }
    allLinks.push(...step.links);
  }

  // Format data for detailed display
  const getDetailSections = (): DetailSection[] => {
    const sections: DetailSection[] = [];

    // General section
    sections.push({
      title: "Informations générales",
      items: [
        { label: "Type", value: stepTypeInfo.label },
        { label: "Activité", value: step.activity },
        { label: "Lieu", value: step.location },
        { label: "Heure de début", value: step.startTime || step.time },
        { label: "Heure de fin", value: step.endTime },
        { label: "Prix", value: step.price ? `${step.price} €` : null },
        { label: "Distance", value: step.distance },
        { label: "Description", value: step.description }
      ].filter(item => item.value)
    });

    // Type-specific section
    if (stepType === 'transport') {
      sections.push({
        title: "Détails du transport",
        items: [
          { label: "Type de transport", value: step.transportType },
          { label: "Numéro de référence", value: step.referenceNumber },
          { label: "Lieu de départ", value: step.departureName },
          { label: "Lieu d'arrivée", value: step.arrivalName },
          { label: "Durée estimée", value: step.estimatedDuration }
        ].filter(item => item.value)
      });
    } else if (stepType === 'meal') {
      sections.push({
        title: "Détails du repas",
        items: [
          { label: "Restaurant", value: step.restaurantName },
          { label: "Type de cuisine", value: step.cuisineType },
          { label: "Budget", value: step.budget }
        ].filter(item => item.value)
      });
    } else if (stepType === 'accommodation') {
      sections.push({
        title: "Détails de l'hébergement",
        items: [
          { label: "Nom", value: step.accommodationName },
          { label: "Type de chambre", value: step.roomType },
          { label: "Heure d'arrivée", value: step.checkInTime },
          { label: "Heure de départ", value: step.checkOutTime },
          { label: "Numéro de réservation", value: step.reservationNumber }
        ].filter(item => item.value)
      });
    } else if (stepType === 'activity') {
      sections.push({
        title: "Détails de l'activité",
        items: [
          { label: "Type d'activité", value: step.activityType },
          { label: "Guide", value: step.guideName },
          { label: "Niveau de marche", value: step.walkingLevel }
        ].filter(item => item.value)
      });
    } else if (stepType === 'break') {
      sections.push({
        title: "Détails de la pause",
        items: [
          { label: "Type de pause", value: step.breakPurpose }
        ].filter(item => item.value)
      });
    }

    // Links section
    if (allLinks.length > 0) {
      sections.push({
        title: "Liens",
        links: allLinks
      });
    }

    // Internal notes (planner only)
    if (isPlanner && step.internalNotes) {
      sections.push({
        title: "Notes internes",
        items: [
          { label: "Notes", value: step.internalNotes }
        ]
      });
    }

    return sections;
  };

  const detailSections = getDetailSections();

  return (
    <div className="space-y-6 py-4">
      {detailSections.map((section, index) => (
        section.items?.length > 0 || section.links?.length > 0 ? (
          <div key={index} className="space-y-2">
            <h3 className="font-medium text-lg" style={{ color: accentColor }}>{section.title}</h3>
            {section.items && (
              <div className="grid grid-cols-1 gap-2">
                {section.items.map((item, itemIndex) => (
                  <div key={itemIndex} className="grid grid-cols-1 gap-2 sm:grid-cols-3">
                    <span className="text-gray-500">{item.label}:</span>
                    <span className="col-span-2">{item.value}</span>
                  </div>
                ))}
              </div>
            )}
            {section.links && (
              <div className="flex flex-wrap gap-2">
                {section.links.map((link, linkIndex) => (
                  <a
                    key={linkIndex}
                    href={link.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm"
                    style={{ backgroundColor: `${accentColor}20`, color: accentColor }}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <ExternalLink size={14} />
                    {link.title}
                  </a>
                ))}
              </div>
            )}
          </div>
        ) : null
      ))}
    </div>
  );
}
