"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  HelpCircle,
  Wifi,
  Smartphone,
  Lock,
  Building2,
  CreditCard,
  Wrench,
  Download,
  ChevronDown,
  Send,
} from "lucide-react";
import { ContactForm } from "@/features/support/components";
import { supportDownloads } from "@/features/landing-page/data";
import { cn } from "@/shared/utils";

// =============================================================================
// DATA
// =============================================================================

const KNOWLEDGE_BASE_CATEGORIES = [
  {
    title: "Internet & Wi-Fi",
    description: "Router setup, connection issues, speed troubleshooting",
    icon: Wifi,
    color: "text-blue-500",
    bgColor: "bg-blue-500/10",
  },
  {
    title: "Phone & SIM",
    description: "SIM activation, plan changes, number porting",
    icon: Smartphone,
    color: "text-green-500",
    bgColor: "bg-green-500/10",
  },
  {
    title: "VPN & Streaming",
    description: "VPN router setup, streaming access, configuration",
    icon: Lock,
    color: "text-purple-500",
    bgColor: "bg-purple-500/10",
  },
  {
    title: "Business Solutions",
    description: "Office networks, dedicated lines, enterprise support",
    icon: Building2,
    color: "text-orange-500",
    bgColor: "bg-orange-500/10",
  },
  {
    title: "Billing & Account",
    description: "Invoices, payments, account changes, contracts",
    icon: CreditCard,
    color: "text-pink-500",
    bgColor: "bg-pink-500/10",
  },
  {
    title: "General Tech Support",
    description: "Device help, software issues, general troubleshooting",
    icon: Wrench,
    color: "text-amber-500",
    bgColor: "bg-amber-500/10",
  },
];

const FAQ_ITEMS = [
  {
    question: "How do I set up my internet router?",
    answer:
      "After your installation appointment, connect the provided router to the NTT ONU device using the included LAN cable. Power on the router and connect to the Wi-Fi network using the credentials on the router label. If you need help, contact our support team or use our remote support tools.",
  },
  {
    question: "How do I activate my SIM card?",
    answer:
      "Insert the SIM card into your unlocked phone. You should receive a confirmation email with APN settings. Go to Settings > Mobile Data > APN and enter the provided settings. Restart your phone and you should be connected within a few minutes.",
  },
  {
    question: "What payment methods do you accept?",
    answer:
      "We accept major credit cards (Visa, Mastercard, American Express), bank transfers, and convenience store payments. Foreign credit cards are accepted for all our services.",
  },
  {
    question: "How do I contact support outside business hours?",
    answer:
      "You can send us an email or submit a contact form at any time — we'll respond within 24 hours on the next business day. For urgent issues, our live chat may have extended availability.",
  },
  {
    question: "Can I change my plan after signing up?",
    answer:
      "Yes, you can change your plan at any time. Contact our support team and we'll help you switch to a plan that better fits your needs. Changes typically take effect from the next billing cycle.",
  },
];

// =============================================================================
// COMPONENT
// =============================================================================

/**
 * PublicSupportView - Self-service support hub
 */
function SupportHeader() {
  return (
    <>
      <div className="text-center mb-12 pt-8">
        <div className="inline-flex items-center justify-center w-16 h-16 bg-primary/10 rounded-2xl mb-4 text-primary">
          <HelpCircle className="h-8 w-8" />
        </div>
        <h1 className="text-4xl sm:text-5xl font-extrabold text-foreground mb-4 tracking-tight">
          How Can We Help?
        </h1>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto leading-relaxed">
          Find answers, download remote support tools, or send us a message. Our English-speaking
          team is ready to assist.
        </p>
      </div>
      <div className="mb-12 max-w-2xl mx-auto">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4 rounded-2xl border border-primary/20 bg-primary/5 px-6 py-5">
          <div className="text-center sm:text-left">
            <p className="font-semibold text-foreground">Already have an account?</p>
            <p className="text-sm text-muted-foreground">
              Sign in to view your tickets and get faster support.
            </p>
          </div>
          <Link
            href="/auth/login"
            className="inline-flex items-center justify-center rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow hover:bg-primary/90 transition-colors whitespace-nowrap"
          >
            Sign in
          </Link>
        </div>
      </div>
    </>
  );
}

function KnowledgeBaseSection() {
  return (
    <section className="mb-16" aria-labelledby="kb-heading">
      <h2 id="kb-heading" className="text-2xl font-bold text-foreground mb-6 text-center">
        Browse by Topic
      </h2>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {KNOWLEDGE_BASE_CATEGORIES.map(category => {
          const Icon = category.icon;
          return (
            <div key={category.title} className="bg-card rounded-2xl border border-border/60 p-6">
              <div className="flex items-start gap-4">
                <div
                  className={cn(
                    "h-11 w-11 rounded-xl flex items-center justify-center shrink-0",
                    category.bgColor,
                    category.color
                  )}
                >
                  <Icon className="h-5 w-5" />
                </div>
                <div>
                  <h3 className="font-bold text-foreground text-sm mb-1">{category.title}</h3>
                  <p className="text-sm text-muted-foreground leading-relaxed">
                    {category.description}
                  </p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function RemoteToolsSection() {
  return (
    <section className="mb-16" aria-labelledby="remote-tools-heading">
      <h2 id="remote-tools-heading" className="text-2xl font-bold text-foreground mb-2 text-center">
        Remote Support Tools
      </h2>
      <p className="text-muted-foreground text-center mb-6">
        Download one of these tools so our technicians can assist you remotely.
      </p>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {supportDownloads.map(tool => (
          <a
            key={tool.title}
            href={tool.href}
            target="_blank"
            rel="noopener noreferrer"
            className="group bg-card rounded-2xl border border-border/60 p-6 hover:border-primary/40 hover:shadow-md transition-all duration-200"
          >
            <div className="flex items-start gap-5">
              <div className="w-16 h-16 rounded-xl bg-muted/30 flex items-center justify-center shrink-0 overflow-hidden">
                <Image
                  src={tool.image}
                  alt={tool.title}
                  width={48}
                  height={48}
                  className="object-contain"
                />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="font-bold text-foreground group-hover:text-primary transition-colors">
                    {tool.title}
                  </h3>
                  <Download className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
                </div>
                <p className="text-sm text-muted-foreground leading-relaxed mb-2">
                  {tool.description}
                </p>
                <p className="text-xs font-medium text-primary">{tool.useCase}</p>
              </div>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

function FaqSection({
  expandedFaq,
  setExpandedFaq,
}: {
  expandedFaq: number | null;
  setExpandedFaq: (value: number | null) => void;
}) {
  return (
    <section className="mb-16" aria-labelledby="faq-heading">
      <h2
        id="faq-heading"
        className="text-2xl font-bold text-foreground mb-6 text-center flex items-center justify-center gap-2"
      >
        Frequently Asked Questions
      </h2>
      <div className="max-w-3xl mx-auto space-y-3">
        {FAQ_ITEMS.map((item, index) => {
          const isExpanded = expandedFaq === index;
          return (
            <div key={index} className="bg-card rounded-xl border border-border/60 overflow-hidden">
              <button
                type="button"
                aria-expanded={isExpanded}
                aria-controls={`faq-answer-${index}`}
                onClick={() => setExpandedFaq(isExpanded ? null : index)}
                className="w-full flex items-center justify-between p-4 text-left hover:bg-muted/30 transition-colors"
              >
                <span className="font-medium text-foreground text-sm pr-4">{item.question}</span>
                <ChevronDown
                  className={cn(
                    "h-4 w-4 text-muted-foreground flex-shrink-0 transition-transform",
                    isExpanded && "rotate-180"
                  )}
                />
              </button>
              {isExpanded && (
                <div id={`faq-answer-${index}`} role="region" className="px-4 pb-4">
                  <p className="text-sm text-muted-foreground leading-relaxed">{item.answer}</p>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}

function ContactFormSection() {
  return (
    <section className="mb-12" aria-labelledby="contact-heading">
      <div className="text-center mb-5">
        <div className="inline-flex items-center justify-center w-11 h-11 bg-primary/10 rounded-xl mb-2.5 text-primary">
          <Send className="h-5 w-5" />
        </div>
        <h2 id="contact-heading" className="text-2xl font-bold text-foreground">
          Still Need Help?
        </h2>
        <p className="text-sm text-muted-foreground mt-1">
          Send us a message and we&apos;ll get back to you within 24 hours.
        </p>
      </div>
      <div className="max-w-2xl mx-auto">
        <ContactForm />
      </div>
    </section>
  );
}

export function PublicSupportView() {
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);

  return (
    <div className="max-w-6xl mx-auto px-4 pb-0">
      <SupportHeader />
      <KnowledgeBaseSection />
      <RemoteToolsSection />
      <FaqSection expandedFaq={expandedFaq} setExpandedFaq={setExpandedFaq} />
      <ContactFormSection />
    </div>
  );
}
