import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { getLoginUrl } from "@/const";
import heroIllustrationUrl from "@/assets/hero-ccds-illustration.svg";
import { useTheme } from "@/contexts/ThemeContext";
import { buildRoutePrefetchHandlers } from "@/lib/routePrefetch";
import { Link } from "wouter";
import { 
  FileText, 
  Building2, 
  ClipboardList, 
  Shield, 
  ArrowRight,
  CheckCircle,
  Users,
  FolderOpen,
  Menu
} from "lucide-react";

export default function Home() {
  const { user, isAuthenticated } = useAuth();
  const { appearance } = useTheme();
  const portalTitle = appearance.portalTitle?.trim() || "Portail Associations 973";
  const portalTagline = appearance.portalTagline?.trim() || "Démarches, annuaire et services du tissu associatif guyanais";

  const heroImageUrl = appearance.heroImageUrl || heroIllustrationUrl;
  const heroImagePositionX = typeof appearance.heroImagePositionX === "number" ? appearance.heroImagePositionX : 50;
  const heroImagePositionY = typeof appearance.heroImagePositionY === "number" ? appearance.heroImagePositionY : 50;
  const heroTaglinePositionX = typeof appearance.heroTaglinePositionX === "number" ? appearance.heroTaglinePositionX : 0;
  const heroTaglinePositionY = typeof appearance.heroTaglinePositionY === "number" ? appearance.heroTaglinePositionY : 0;
  const heroTaglineWidthPercent = typeof appearance.heroTaglineWidthPercent === "number" ? appearance.heroTaglineWidthPercent : 80;
  const publicLinks = [
    { href: "/associations", label: "Annuaire" },
    { href: "/associations/carte", label: "Carte" },
    { href: "/faq", label: "Aide & FAQ" },
  ] as const;

  return (
    <div className="min-h-screen flex flex-col">
      {/* Header DSFR style */}
      <header className="border-b border-border bg-white">
        <div className="container py-3 sm:py-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex min-w-0 items-center gap-3 sm:gap-4">
              {appearance.logoUrl ? (
                <img
                  src={appearance.logoUrl}
                  alt={portalTitle}
                  className="h-8 w-8 shrink-0 rounded-md object-contain sm:h-12 sm:w-12"
                />
              ) : null}
              <div className="flex min-w-0 flex-col leading-tight">
                <span className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground sm:text-xs sm:tracking-wider">
                  République Française
                </span>
                <span className="truncate text-base font-bold text-primary sm:text-lg">{portalTitle}</span>
                <span className="line-clamp-2 text-xs text-muted-foreground sm:text-sm">{portalTagline}</span>
              </div>
            </div>
            <div className="flex items-center justify-between gap-3 sm:justify-end">
              <nav className="hidden min-w-0 items-center gap-2 overflow-x-auto pb-1 sm:flex sm:flex-wrap sm:justify-end sm:gap-3 sm:overflow-visible sm:pb-0">
                {publicLinks.map((item) => (
                  <Link
                    key={item.href}
                    href={item.href}
                    className="shrink-0 rounded-full px-2 py-1 text-xs text-foreground transition-colors hover:bg-muted hover:text-primary sm:px-0 sm:py-0 sm:text-sm"
                    {...buildRoutePrefetchHandlers(item.href)}
                  >
                    {item.label}
                  </Link>
                ))}
                {isAuthenticated ? (
                  <Link href="/dashboard" {...buildRoutePrefetchHandlers("/dashboard")}>
                    <Button size="sm" className="min-h-10 shrink-0 px-3 sm:px-4">Mon espace</Button>
                  </Link>
                ) : (
                  <a href={getLoginUrl()}>
                    <Button size="sm" className="min-h-10 shrink-0 px-3 sm:px-4">Connexion</Button>
                  </a>
                )}
              </nav>

              <div className="sm:hidden">
                <Sheet>
                  <SheetTrigger asChild>
                    <Button variant="outline" size="icon" className="h-10 w-10 shrink-0 rounded-xl">
                      <Menu className="h-5 w-5" />
                    </Button>
                  </SheetTrigger>
                  <SheetContent side="left" className="w-[min(22rem,calc(100vw-1rem))] p-0">
                    <SheetHeader className="border-b px-5 py-4 text-left">
                      <SheetTitle>Navigation</SheetTitle>
                      <SheetDescription>Accès rapide aux pages publiques et à votre espace.</SheetDescription>
                    </SheetHeader>
                    <div className="flex flex-col gap-2 p-4">
                      {publicLinks.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className="rounded-xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-900 transition hover:bg-slate-50"
                          {...buildRoutePrefetchHandlers(item.href)}
                        >
                          {item.label}
                        </Link>
                      ))}
                      {isAuthenticated ? (
                        <Link
                          href="/dashboard"
                          className="mt-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground"
                          {...buildRoutePrefetchHandlers("/dashboard")}
                        >
                          Mon espace
                        </Link>
                      ) : (
                        <a href={getLoginUrl()} className="mt-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground">
                          Connexion
                        </a>
                      )}
                    </div>
                  </SheetContent>
                </Sheet>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section className="relative overflow-hidden text-primary-foreground">
        <div
          className="absolute inset-0 bg-cover bg-no-repeat"
          style={{
            backgroundImage: `url(${heroImageUrl})`,
            backgroundPosition: `${heroImagePositionX}% ${heroImagePositionY}%`,
          }}
          aria-hidden="true"
        />
        <div
          className="absolute inset-y-0 right-0 hidden lg:block w-[46%]"
          style={{
            background: "linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.08) 100%)",
          }}
          aria-hidden="true"
        />
        <div className="container relative z-10 min-h-[66vh] pt-8 sm:min-h-[calc(100vh-5rem)] sm:pt-28">
          <div className="absolute inset-x-0 bottom-32 z-20 flex justify-center px-4 sm:bottom-24 lg:bottom-32 xl:bottom-36">
            <div className="flex w-full max-w-5xl flex-col items-center gap-3 sm:flex-row sm:flex-wrap sm:justify-center sm:gap-4">
              {isAuthenticated ? (
                <Link href="/dashboard" {...buildRoutePrefetchHandlers("/dashboard")}>
                  <Button size="lg" variant="secondary" className="min-h-12 w-full bg-white text-primary hover:bg-white/90 sm:w-auto">
                    Accéder à mon espace
                    <ArrowRight className="ml-2 h-5 w-5" />
                  </Button>
                </Link>
              ) : (
                <a href={getLoginUrl()}>
                  <Button size="lg" variant="secondary" className="min-h-12 w-full bg-white text-primary hover:bg-white/90 sm:w-auto">
                    Créer mon compte
                    <ArrowRight className="ml-2 h-5 w-5" />
                  </Button>
                </a>
              )}
              <Link href="/faq" {...buildRoutePrefetchHandlers("/faq")}>
                <Button
                  size="lg"
                  variant="secondary"
                  className="min-h-12 w-full bg-white text-primary hover:bg-white/90 sm:w-auto"
                >
                  En savoir plus
                </Button>
              </Link>
              <Link href="/associations/carte" {...buildRoutePrefetchHandlers("/associations/carte")}>
                <Button
                  size="lg"
                  variant="secondary"
                  className="min-h-12 w-full bg-white text-primary hover:bg-white/90 sm:w-auto"
                >
                  Voir la carte
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-16 bg-muted/30">
        <div className="container">
          <div className="text-center mb-12">
            <h2 className="text-2xl md:text-3xl font-bold mb-4">
              Tout ce dont votre association a besoin
            </h2>
            <p className="text-muted-foreground max-w-2xl mx-auto">
              Une plateforme complète pour centraliser vos documents et simplifier vos demandes administratives.
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <Building2 className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Profil Association</CardTitle>
                <CardDescription>
                  Centralisez toutes les informations de votre association : SIRET, adresse, représentants légaux.
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <FolderOpen className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Gestion des Documents</CardTitle>
                <CardDescription>
                  Stockez et organisez vos documents administratifs : statuts, récépissé, RIB, rapports.
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <FileText className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Formulaires Intelligents</CardTitle>
                <CardDescription>
                  Des formulaires pré-remplis avec vos informations pour gagner du temps sur vos demandes.
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <ClipboardList className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Suivi des Demandes</CardTitle>
                <CardDescription>
                  Suivez en temps réel l'avancement de vos demandes de subventions et agréments.
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <Shield className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Données Sécurisées</CardTitle>
                <CardDescription>
                  Vos documents et informations sont stockés de manière sécurisée et confidentielle.
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                  <Users className="h-6 w-6 text-primary" />
                </div>
                <CardTitle className="text-lg">Support Dédié</CardTitle>
                <CardDescription>
                  Une équipe à votre écoute pour vous accompagner dans vos démarches administratives.
                </CardDescription>
              </CardHeader>
            </Card>
          </div>
        </div>
      </section>

      {/* How it works */}
      <section className="py-16">
        <div className="container">
          <div className="text-center mb-12">
            <h2 className="text-2xl md:text-3xl font-bold mb-4">
              Comment ça marche ?
            </h2>
          </div>

          <div className="grid md:grid-cols-4 gap-8">
            {[
              { step: 1, title: "Créez votre compte", desc: "Inscrivez-vous et complétez le profil de votre association" },
              { step: 2, title: "Déposez vos documents", desc: "Téléversez vos documents administratifs une seule fois" },
              { step: 3, title: "Remplissez vos demandes", desc: "Les formulaires sont pré-remplis avec vos informations" },
              { step: 4, title: "Suivez vos dossiers", desc: "Consultez l'état d'avancement de vos demandes" },
            ].map((item) => (
              <div key={item.step} className="text-center">
                <div className="w-12 h-12 rounded-full bg-primary text-primary-foreground flex items-center justify-center mx-auto mb-4 text-lg font-bold">
                  {item.step}
                </div>
                <h3 className="font-semibold mb-2">{item.title}</h3>
                <p className="text-sm text-muted-foreground">{item.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Types of requests */}
      <section className="py-16 bg-muted/30">
        <div className="container">
          <div className="text-center mb-12">
            <h2 className="text-2xl md:text-3xl font-bold mb-4">
              Types de demandes disponibles
            </h2>
            <p className="text-muted-foreground">
              Accédez à une bibliothèque complète de formulaires administratifs
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            {[
              "Subvention de fonctionnement",
              "Subvention de projet",
              "Agrément Jeunesse et Éducation Populaire",
              "Agrément Sport",
              "Autorisation d'occupation",
              "Demande de salle",
            ].map((type) => (
              <div key={type} className="flex items-center gap-3 p-4 bg-white rounded-lg border border-border">
                <CheckCircle className="h-5 w-5 text-green-600 flex-shrink-0" />
                <span className="text-sm font-medium">{type}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-16 bg-primary text-primary-foreground">
        <div className="container text-center">
          <h2 className="text-2xl md:text-3xl font-bold mb-4">
            Prêt à simplifier vos démarches ?
          </h2>
          <p className="text-lg opacity-90 mb-8 max-w-2xl mx-auto">
            Rejoignez les associations qui ont déjà adopté notre plateforme pour gérer leurs documents et demandes.
          </p>
          {isAuthenticated ? (
            <Link href="/dashboard" {...buildRoutePrefetchHandlers("/dashboard")}>
              <Button size="lg" variant="secondary" className="bg-white text-primary hover:bg-white/90">
                Accéder à mon espace
                <ArrowRight className="ml-2 h-5 w-5" />
              </Button>
            </Link>
          ) : (
            <a href={getLoginUrl()}>
              <Button size="lg" variant="secondary" className="bg-white text-primary hover:bg-white/90">
                Commencer maintenant
                <ArrowRight className="ml-2 h-5 w-5" />
              </Button>
            </a>
          )}
        </div>
      </section>

      {/* Footer */}
      <footer className="border-t border-border py-8 bg-white">
        <div className="container">
          <div className="grid md:grid-cols-4 gap-8">
            <div>
              <div className="font-bold text-primary mb-4">Portail Associations</div>
              <p className="text-sm text-muted-foreground">
                Simplifiez vos démarches administratives en quelques clics.
              </p>
            </div>
            <div>
              <h4 className="font-semibold mb-4">Navigation</h4>
              <ul className="space-y-2 text-sm">
                <li><Link href="/" className="text-muted-foreground hover:text-primary">Accueil</Link></li>
                <li><Link href="/associations" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/associations")}>Annuaire des associations</Link></li>
                <li><Link href="/faq" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/faq")}>Aide & FAQ</Link></li>
                <li><Link href="/dashboard" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/dashboard")}>Mon espace</Link></li>
              </ul>
            </div>
            <div>
              <h4 className="font-semibold mb-4">Ressources</h4>
              <ul className="space-y-2 text-sm">
                <li><Link href="/mentions-legales" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/mentions-legales")}>Mentions legales</Link></li>
                <li><Link href="/confidentialite" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/confidentialite")}>Politique de confidentialité</Link></li>
                <li><Link href="/cookies" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/cookies")}>Politique de cookies</Link></li>
                <li><Link href="/cgu" className="text-muted-foreground hover:text-primary" {...buildRoutePrefetchHandlers("/cgu")}>CGU</Link></li>
              </ul>
            </div>
            <div>
              <h4 className="font-semibold mb-4">Contact</h4>
              <ul className="space-y-2 text-sm text-muted-foreground">
                <li>Service des associations</li>
                <li>contact@portail-associations.fr</li>
              </ul>
            </div>
          </div>
          <div className="border-t border-border mt-8 pt-8 text-center text-sm text-muted-foreground">
            © {new Date().getFullYear()} Portail Associations. Tous droits réservés.
          </div>
        </div>
      </footer>
    </div>
  );
}
