"use client";

import * as React from "react";
import Link from "next/link";
import {
  BookOpen,
  Rocket,
  Upload,
  FileText,
  Plug,
  BarChart3,
  HelpCircle,
  Wrench,
  Search,
  ArrowRight,
  LifeBuoy,
  type LucideIcon,
} from "lucide-react";
import { Header } from "@/components/layout/header";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { openContactSupport } from "@/components/support/contact-support-dialog";

type Topic = {
  href: string;
  title: string;
  description: string;
  icon: LucideIcon;
  keywords: string[];
};

const TOPICS: Topic[] = [
  {
    href: "/docs/getting-started",
    title: "Getting Started",
    description:
      "Create your account, set up your organization, invite your team, and upload your first response card.",
    icon: Rocket,
    keywords: [
      "signup",
      "onboarding",
      "organization",
      "invite",
      "team",
      "first upload",
      "welcome",
      "setup",
    ],
  },
  {
    href: "/docs/uploading-cards",
    title: "Uploading Cards",
    description:
      "Manual uploads, scanner/email ingestion, FTP watchers, supported file types, and the OCR lifecycle.",
    icon: Upload,
    keywords: [
      "upload",
      "scan",
      "email watch",
      "ftp",
      "pdf",
      "jpg",
      "png",
      "ocr",
      "processing",
      "queue",
    ],
  },
  {
    href: "/docs/forms-templates",
    title: "Forms & Templates",
    description:
      "Build form templates, map fields, test extraction, and handle edge cases.",
    icon: FileText,
    keywords: [
      "form",
      "template",
      "fields",
      "mapping",
      "extraction",
      "ai",
      "testing",
    ],
  },
  {
    href: "/docs/integrations",
    title: "Integrations",
    description:
      "Connect Planning Center, Google Sheets, Monday, webhooks, and more to sync your data automatically.",
    icon: Plug,
    keywords: [
      "integrations",
      "planning center",
      "pco",
      "google sheets",
      "monday",
      "webhook",
      "oauth",
      "sync",
      "export",
    ],
  },
  {
    href: "/docs/reports-exports",
    title: "Reports & Exports",
    description:
      "Generate reports, export CSVs, and push data to connected integrations.",
    icon: BarChart3,
    keywords: [
      "reports",
      "export",
      "csv",
      "download",
      "analytics",
      "charts",
    ],
  },
  {
    href: "/docs/faq",
    title: "FAQ",
    description:
      "Quick answers to the most common questions about billing, accuracy, security, and limits.",
    icon: HelpCircle,
    keywords: [
      "faq",
      "questions",
      "billing",
      "pricing",
      "accuracy",
      "security",
      "privacy",
      "limits",
    ],
  },
  {
    href: "/docs/troubleshooting",
    title: "Troubleshooting",
    description:
      "Fix OCR accuracy issues, email-watch failures, integration auth errors, and stuck jobs.",
    icon: Wrench,
    keywords: [
      "troubleshoot",
      "error",
      "stuck",
      "fail",
      "broken",
      "not working",
      "fix",
      "debug",
    ],
  },
];

export default function DocsHomePage() {
  const [query, setQuery] = React.useState("");

  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return TOPICS;
    return TOPICS.filter((t) => {
      if (t.title.toLowerCase().includes(q)) return true;
      if (t.description.toLowerCase().includes(q)) return true;
      return t.keywords.some((k) => k.includes(q));
    });
  }, [query]);

  return (
    <div className="space-y-6">
      <Header
        title="Help & Docs"
        description="Guides, references, and answers to help you get the most out of Echo."
        icon={BookOpen}
      />

      <Card className="glass-card">
        <CardContent className="p-5">
          <div className="relative">
            <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search the docs…"
              className="pl-9"
              aria-label="Search the documentation"
            />
          </div>
          <p className="mt-2 text-xs text-muted-foreground">
            Try searching for &ldquo;upload&rdquo;, &ldquo;Planning Center&rdquo;,
            or &ldquo;pricing&rdquo;.
          </p>
        </CardContent>
      </Card>

      {filtered.length === 0 ? (
        <Card className="glass-card">
          <CardContent className="p-8 text-center">
            <p className="text-sm text-muted-foreground">
              No matching topics found for &ldquo;{query}&rdquo;.
            </p>
            <Button
              variant="outline"
              size="sm"
              className="mt-3"
              onClick={openContactSupport}
            >
              <LifeBuoy className="size-3.5" />
              Ask support
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {filtered.map((topic) => {
            const Icon = topic.icon;
            return (
              <Link key={topic.href} href={topic.href} className="group">
                <Card className="h-full transition-all hover:border-primary/40 hover:shadow-md">
                  <CardContent className="p-5">
                    <div className="mb-3 flex items-center gap-2.5">
                      <div className="flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
                        <Icon className="size-4" />
                      </div>
                      <h3 className="text-base font-semibold tracking-tight">
                        {topic.title}
                      </h3>
                      <ArrowRight className="ml-auto size-4 text-muted-foreground transition-all group-hover:translate-x-0.5 group-hover:text-primary" />
                    </div>
                    <p className="text-sm leading-relaxed text-muted-foreground">
                      {topic.description}
                    </p>
                  </CardContent>
                </Card>
              </Link>
            );
          })}
        </div>
      )}

      <Card className="border-primary/20 bg-primary/5">
        <CardContent className="flex flex-col items-start gap-3 p-5 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-start gap-3">
            <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
              <LifeBuoy className="size-4" />
            </div>
            <div>
              <p className="text-sm font-semibold">Still have questions?</p>
              <p className="text-xs text-muted-foreground">
                Send us a message and we&rsquo;ll get back to you shortly.
              </p>
            </div>
          </div>
          <Button size="sm" onClick={openContactSupport}>
            Contact support
            <ArrowRight className="size-3.5" />
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
