import { CalendarDays, CheckCircle2, ChevronRight, FileText, MapPin, Users } from "lucide-react";
import { Link, useSearchParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { useTripWorkspace } from "@/hooks/useTripWorkspace";
import { getTripDays } from "@/services/itineraryGuards";
import { workspaceHref } from "@/services/tripWorkspaceState";

export default function TripOverviewPage() {
  const { trip } = useTripWorkspace(); const [search] = useSearchParams();
  const days = getTripDays(trip.startDate, trip.endDate);
  const published = trip.steps.filter((s) => s.isPublished);
  const filled = new Set(trip.steps.map((s) => s.day)).size;
  const empty = Math.max(0, days.length - filled);
  const approved = published.flatMap((s) => s.validations || []).filter((v) => v.status === "approved").length;
  const expected = published.length * (trip.members?.length || 0);
  const rejected = trip.steps.filter((s) => (s.validations || []).some((v) => v.status === "rejected"));
  const pending = (trip.invitations || []).filter((i) => i.status === "pending").length;
  const base = `/dashboard/trips/${trip.id}`;
  const itinerary = workspaceHref(`${base}/itinerary`, search), travelers = workspaceHref(`${base}/travelers`, search);
  const cover = trip.bannerUrl || trip.coverUrl;

  return <div className="page-shell"><div className="mx-auto max-w-[1120px] space-y-12">
    <section className="overflow-hidden rounded-[2rem] bg-secondary text-secondary-foreground"><div className="grid md:h-[280px] md:grid-cols-[1.25fr_.75fr]"><div className="flex flex-col justify-center p-6 sm:p-8"><p className="text-xs font-bold uppercase tracking-[.2em] text-primary">Poste de pilotage</p><h2 className="mt-2 font-serif text-3xl sm:text-4xl">{trip.title}</h2><p className="mt-2 flex items-center gap-2 text-sm text-white/70"><MapPin className="h-4 w-4" />{trip.destination}</p><Button size="sm" className="mt-5 w-fit" asChild><Link to={itinerary}>Continuer l’itinéraire<ChevronRight className="ml-2 h-4 w-4" /></Link></Button></div>{cover && <img src={cover} alt={`Vue de ${trip.destination}`} className="h-40 w-full object-cover sm:h-48 md:h-full" />}</div></section>
    <section><h2 className="section-title">Progression</h2><p className="mt-1 text-sm text-muted-foreground">Les indicateurs utiles pour préparer le départ.</p><div className="mt-5 grid gap-px overflow-hidden rounded-2xl bg-border sm:grid-cols-2 lg:grid-cols-5"><Metric icon={CalendarDays} value={`${filled}/${days.length}`} label="jours renseignés" /><Metric icon={CalendarDays} value={published.length} label="étapes publiées" /><Metric icon={CheckCircle2} value={`${approved}/${expected}`} label="validations" /><Metric icon={Users} value={trip.members?.length || 0} label={pending ? `actif · ${pending} invitation${pending > 1 ? "s" : ""}` : "voyageur(s) actif(s)"} /><Metric icon={FileText} value={trip.documents.length} label={trip.documents.length === 1 ? "document" : "documents"} /></div></section>
    <section><h2 className="section-title">À résoudre</h2>{rejected.length || pending ? <div className="mt-4 divide-y border-y">{rejected.slice(0, 4).map((s) => <ActionRow key={s.id} title="Modification demandée" detail={s.activity} label="Examiner" href={`${itinerary}${itinerary.includes("?") ? "&" : "?"}step=${encodeURIComponent(s.id)}`} />)}{pending > 0 && <ActionRow title="Invitation en attente" detail={`${pending} voyageur${pending > 1 ? "s n’ont" : " n’a"} pas encore rejoint le voyage.`} label="Voir les voyageurs" href={travelers} />}</div> : <p className="mt-4 rounded-2xl bg-muted/50 p-5 text-sm text-muted-foreground">Rien ne demande votre attention pour le moment.</p>}</section>
    <section className="grid gap-10 lg:grid-cols-[.9fr_1.1fr]"><div><h2 className="section-title">Prochaines actions</h2><div className="mt-4 space-y-3"><ActionCard title={empty ? `${empty} journée${empty > 1 ? "s restent" : " reste"} à organiser` : "Programme renseigné"} detail={empty ? `Le programme est renseigné sur ${filled} jour${filled > 1 ? "s" : ""} sur ${days.length}.` : "Toutes les journées comportent au moins une étape."} label={empty ? "Continuer l’itinéraire" : "Relire l’itinéraire"} href={itinerary} />{pending > 0 && <ActionCard title={`${pending} invitation${pending > 1 ? "s" : ""} en attente`} detail="Vérifiez l’accès des voyageurs avant le départ." label="Gérer les voyageurs" href={travelers} />}</div></div><div><div className="flex items-end justify-between"><h2 className="section-title">Programme</h2><Link className="text-sm font-semibold text-primary" to={itinerary}>Voir les {days.length} jours</Link></div><ol className="mt-4 divide-y border-y">{days.slice(0, 3).map(({ day }) => { const first = trip.steps.filter((s) => s.day === day).sort((a, b) => (a.startTime || a.time).localeCompare(b.startTime || b.time))[0]; return <li key={day} className="flex gap-5 py-4"><span className="w-14 text-xs font-bold uppercase tracking-wider text-primary">Jour {day}</span>{first ? <div><p className="font-medium">{first.activity}</p><p className="text-sm text-muted-foreground">{first.startTime || first.time || "Horaire libre"}</p></div> : <p className="text-sm text-muted-foreground">À organiser</p>}</li>; })}</ol></div></section>
  </div></div>;
}

function Metric({ icon: Icon, value, label }: { icon: typeof Users; value: string | number; label: string }) { return <div className="flex min-h-28 items-center gap-3 bg-background p-5"><Icon className="h-5 w-5 text-primary" aria-hidden="true" /><div><p className="text-2xl font-semibold">{value}</p><p className="text-sm text-muted-foreground">{label}</p></div></div>; }
function ActionRow({ title, detail, label, href }: { title: string; detail: string; label: string; href: string }) { return <div className="flex flex-col justify-between gap-4 py-4 sm:flex-row sm:items-center"><div><p className="font-medium">{title}</p><p className="text-sm text-muted-foreground">{detail}</p></div><Button size="sm" variant="ghost" asChild><Link to={href}>{label}<ChevronRight className="ml-1 h-4 w-4" /></Link></Button></div>; }
function ActionCard({ title, detail, label, href }: { title: string; detail: string; label: string; href: string }) { return <article className="rounded-2xl bg-muted/45 p-5"><h3 className="font-semibold">{title}</h3><p className="mt-1 text-sm text-muted-foreground">{detail}</p><Button className="mt-4" size="sm" variant="outline" asChild><Link to={href}>{label}</Link></Button></article>; }
