"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
    MessageCircle, FileText, CreditCard,
    Building2, Map, LayoutDashboard, Wallet, Settings,
    ChevronDown, ChevronUp, CheckCircle2, AlertCircle,
    Zap, Shield, Star, ExternalLink, HelpCircle, ArrowLeft, Users
} from "lucide-react";

const WHATSAPP_NUMBER = "+2349164601810";
const WHATSAPP_URL = `https://wa.me/${WHATSAPP_NUMBER.replace(/\D/g, "")}`;

const features = [
    {
        icon: LayoutDashboard, color: "text-indigo-600", bg: "bg-indigo-500/10",
        title: "Dashboard",
        desc: "The main overview. Shows live KPIs: total revenue collected, active contracts, overdue alerts, upcoming installments, and a quick-glance analytics panel.",
        howTo: "Navigate to / from the sidebar. All metrics update in real-time from the backend. Widgets are clickable to drill into each section."
    },
    {
        icon: Building2, color: "text-emerald-600", bg: "bg-emerald-500/10",
        title: "Properties & Assets",
        desc: "Manage your property portfolio — plots, land, commercial estates. Track availability, pricing, location, and link assets to client contracts.",
        howTo: "Go to Assets → click any row to view the full detail page. Use + Add Asset to register a new property. Click the trash icon to delete."
    },
    {
        icon: Users, color: "text-blue-600", bg: "bg-blue-500/10",
        title: "Clients",
        desc: "Full client registry — contact info, KYC documents, payment history, and linked contracts. Each client has a dedicated profile page.",
        howTo: "Go to Clients → search by name/email/phone. Click View Profile to see full history. Phone numbers and emails are clickable to call/email directly."
    },
    {
        icon: FileText, color: "text-violet-600", bg: "bg-violet-500/10",
        title: "Contracts",
        desc: "Create and manage installment sale agreements. Each contract links a client to an asset, auto-generates payment schedules, and tracks vesting progress.",
        howTo: "Go to Contracts → Draft New Contract. Select client + asset, set dates, total price and installment count. The system auto-generates the payment schedule."
    },
    {
        icon: Wallet, color: "text-amber-600", bg: "bg-amber-500/10",
        title: "Payments & Ledger",
        desc: "Record and verify payments from clients. Each payment can be linked to a specific installment and generates a printable receipt.",
        howTo: "Go to Payments → Accept Payment. Select the contract, enter amount, choose payment method. Use the receipt icon (📄) to print a payment slip."
    },
    {
        icon: Map, color: "text-teal-600", bg: "bg-teal-500/10",
        title: "Interactive Map",
        desc: "Geospatial view of all registered properties. Select any asset from the dropdown to fly directly to its address on the map.",
        howTo: "Go to Map. Use the search/select dropdown to pick an asset — the map will fly to its location. Click map markers to see asset details pop-ups."
    },
    {
        icon: Settings, color: "text-slate-600", bg: "bg-slate-500/10",
        title: "System Settings",
        desc: "Configure your organization name, logo, contact details, address, and primary brand color that propagates across receipts and the entire system UI.",
        howTo: "Go to Settings. Update company info. Select one of the 5 brand color swatches — it applies instantly. Click Save System Config to persist."
    },
];

const faqs = [
    {
        q: "A client made a payment but it's not showing on their contract. What do I do?",
        a: "Ensure the payment was recorded under the correct Contract. Go to Payments, find the payment, and verify the Contract ID matches. Also check if the payment has been marked as 'Verified' — unverified payments don't count toward the progress bar."
    },
    {
        q: "How do I print a receipt for a client?",
        a: "Open the Contract detail page (Contracts → click the contract number). In the Verified Payments section on the left, click the document icon (📄) next to any payment. This opens a print-ready receipt in a new tab."
    },
    {
        q: "The page shows 'Unauthorized' or I get kicked to the Login page.",
        a: "Your session has expired (sessions last 48 hours). Simply log in again. If the problem persists, contact the developer via WhatsApp below."
    },
    {
        q: "How do I change the system colour / brand theme?",
        a: "Go to Settings → Identity & Branding → Primary Brand Color. Click one of the 5 color swatches. The color changes instantly. Press Save System Config to save it permanently."
    },
    {
        q: "Can I delete a client that has active contracts?",
        a: "Yes — deleting a client removes the client record but does NOT delete their contracts. The contracts will remain but show 'No client linked'. It is recommended to archive rather than delete active clients."
    },
    {
        q: "How do installments get generated?",
        a: "When you create a contract and specify the number of installments and frequency (monthly, bi-weekly, weekly), the backend automatically generates the full payment schedule starting from the contract start date."
    },
];

export default function ContactPage() {
    const router = useRouter();
    const [openFaq, setOpenFaq] = useState<number | null>(null);

    return (
        <div className="min-h-screen bg-slate-50">

            {/* ── Top nav bar ── */}
            <header className="sticky top-0 z-50 bg-white/90 backdrop-blur-md border-b border-slate-200/60 shadow-sm">
                <div className="max-w-5xl mx-auto px-6 h-14 flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center">
                            <HelpCircle className="w-4 h-4 text-white" />
                        </div>
                        <span className="font-black text-slate-800 text-sm tracking-tight">Help Center</span>
                    </div>
                    <div className="flex items-center gap-2">
                        <a
                            href={WHATSAPP_URL}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-lg hover:bg-emerald-100 transition-colors"
                        >
                            <MessageCircle className="w-3.5 h-3.5" /> WhatsApp
                        </a>
                        <button
                            onClick={() => router.back()}
                            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-slate-600 bg-slate-100 border border-slate-200 rounded-lg hover:bg-slate-200 transition-colors"
                        >
                            <ArrowLeft className="w-3.5 h-3.5" /> Back
                        </button>
                    </div>
                </div>
            </header>

            <main className="max-w-5xl mx-auto px-6 py-10 space-y-14">

                {/* ── Hero ── */}
                <div className="relative rounded-3xl overflow-hidden bg-gradient-to-br from-indigo-600 via-violet-600 to-indigo-700 p-10 text-white shadow-2xl shadow-indigo-500/20">
                    <div className="absolute inset-0 opacity-10" style={{ backgroundImage: "radial-gradient(white 1px, transparent 1px)", backgroundSize: "32px 32px" }} />
                    <div className="relative z-10 flex flex-col md:flex-row items-start md:items-center gap-6">
                        <div className="w-14 h-14 rounded-2xl bg-white/20 flex items-center justify-center backdrop-blur-sm flex-shrink-0">
                            <HelpCircle className="w-7 h-7 text-white" />
                        </div>
                        <div className="flex-1">
                            <h1 className="text-3xl font-black tracking-tight mb-2">Help Center & Contact</h1>
                            <p className="text-white/80 font-medium max-w-xl">
                                Everything you need to operate the CRM — feature guides, FAQs, and direct access to developer support.
                            </p>
                        </div>
                        <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer" className="flex-shrink-0">
                            <Button className="bg-white text-green-700 hover:bg-green-50 font-black text-sm rounded-xl px-5 h-11 shadow-lg gap-2">
                                <MessageCircle className="w-4 h-4" /> WhatsApp Developer
                            </Button>
                        </a>
                    </div>
                </div>

                {/* ── Feature Guide ── */}
                <section>
                    <h2 className="text-2xl font-black text-slate-900 mb-1">System Feature Guide</h2>
                    <p className="text-slate-500 text-sm font-medium mb-6">A complete walkthrough of every module in the CRM.</p>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {features.map((f) => {
                            const Icon = f.icon;
                            return (
                                <div key={f.title} className="rounded-2xl bg-white border border-slate-100 shadow-sm overflow-hidden hover:shadow-md transition-all">
                                    <div className="flex items-center gap-3 px-5 py-4 border-b border-slate-100 bg-slate-50/60">
                                        <div className={`w-8 h-8 rounded-xl ${f.bg} flex items-center justify-center flex-shrink-0`}>
                                            <Icon className={`w-4 h-4 ${f.color}`} />
                                        </div>
                                        <h3 className="font-black text-slate-800 text-sm">{f.title}</h3>
                                    </div>
                                    <div className="p-5 space-y-3">
                                        <p className="text-sm text-slate-500 font-medium leading-relaxed">{f.desc}</p>
                                        <div className="p-3 bg-emerald-50 border border-emerald-100 rounded-xl">
                                            <p className="text-[10px] font-black uppercase tracking-widest text-emerald-600 mb-1.5 flex items-center gap-1">
                                                <CheckCircle2 className="w-3 h-3" /> How to use
                                            </p>
                                            <p className="text-xs text-slate-700 font-medium leading-relaxed">{f.howTo}</p>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </section>

                {/* ── FAQ ── */}
                <section>
                    <h2 className="text-2xl font-black text-slate-900 mb-1">Frequently Asked Questions</h2>
                    <p className="text-slate-500 text-sm font-medium mb-6">Common issues and how to resolve them quickly.</p>
                    <div className="space-y-2">
                        {faqs.map((faq, i) => (
                            <div
                                key={i}
                                className="rounded-2xl bg-white border border-slate-100 shadow-sm overflow-hidden cursor-pointer hover:border-slate-200 transition-all"
                                onClick={() => setOpenFaq(openFaq === i ? null : i)}
                            >
                                <div className="flex items-center justify-between px-5 py-4 gap-4">
                                    <div className="flex items-center gap-3 min-w-0">
                                        <AlertCircle className="w-4 h-4 text-amber-500 flex-shrink-0" />
                                        <p className="font-bold text-sm text-slate-800 leading-snug">{faq.q}</p>
                                    </div>
                                    {openFaq === i
                                        ? <ChevronUp className="w-4 h-4 text-slate-400 flex-shrink-0" />
                                        : <ChevronDown className="w-4 h-4 text-slate-400 flex-shrink-0" />
                                    }
                                </div>
                                {openFaq === i && (
                                    <div className="px-5 pb-4 pt-0">
                                        <div className="pl-7 border-l-2 border-indigo-200">
                                            <p className="text-sm text-slate-500 font-medium leading-relaxed">{faq.a}</p>
                                        </div>
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                </section>

                {/* ── Contact ── */}
                <section>
                    <h2 className="text-2xl font-black text-slate-900 mb-1">Get Direct Support</h2>
                    <p className="text-slate-500 text-sm font-medium mb-6">Can't find the answer? Reach the developer directly.</p>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">

                        {/* WhatsApp card */}
                        <div className="rounded-3xl overflow-hidden bg-gradient-to-br from-green-500 to-emerald-600 text-white shadow-xl shadow-emerald-500/20 p-8">
                            <div className="w-12 h-12 bg-white/20 rounded-2xl flex items-center justify-center mb-5 backdrop-blur-sm">
                                <MessageCircle className="w-6 h-6 text-white" />
                            </div>
                            <h3 className="text-xl font-black mb-2">WhatsApp Support</h3>
                            <p className="text-white/80 text-sm font-medium mb-4 leading-relaxed">
                                Message the developer directly for bug reports, feature requests, or urgent system issues.
                            </p>
                            <p className="text-white/60 text-[10px] font-black uppercase tracking-widest mb-1">Developer Contact</p>
                            <p className="text-lg font-black font-mono mb-5">{WHATSAPP_NUMBER}</p>
                            <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer" className="block">
                                <button className="flex items-center justify-center gap-2 w-full h-11 bg-white text-green-700 hover:bg-green-50 font-black text-sm rounded-xl shadow-md transition-all active:scale-95">
                                    <ExternalLink className="w-4 h-4" /> Open WhatsApp Chat
                                </button>
                            </a>
                            <div className="mt-4 flex items-center gap-2 text-white/60 text-xs font-bold">
                                <div className="w-2 h-2 rounded-full bg-white/60 animate-pulse" />
                                Typically responds within 24 hours
                            </div>
                        </div>

                        {/* Info stack */}
                        <div className="space-y-4">
                            <div className="rounded-2xl bg-white border border-slate-100 shadow-sm p-5">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="w-8 h-8 rounded-xl bg-indigo-50 flex items-center justify-center">
                                        <Star className="w-4 h-4 text-indigo-600" />
                                    </div>
                                    <h4 className="font-black text-slate-800 text-sm">About the Developer</h4>
                                </div>
                                <p className="text-sm text-slate-500 font-medium leading-relaxed">
                                    This CRM was built by a developer specializing in enterprise real estate management — handling KYC, contracts, installment scheduling, payment collection, and receipt issuance.
                                </p>
                                <div className="mt-4 pt-4 border-t border-slate-100 flex flex-wrap gap-2">
                                    {["Next.js", "Django REST", "PostgreSQL", "Mapbox"].map(t => (
                                        <span key={t} className="px-2.5 py-1 bg-indigo-50 text-indigo-700 rounded-full text-[10px] font-black uppercase tracking-widest">{t}</span>
                                    ))}
                                </div>
                            </div>

                            <div className="rounded-2xl bg-white border border-slate-100 shadow-sm p-5">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="w-8 h-8 rounded-xl bg-amber-50 flex items-center justify-center">
                                        <Zap className="w-4 h-4 text-amber-600" />
                                    </div>
                                    <h4 className="font-black text-slate-800 text-sm">When to Contact</h4>
                                </div>
                                <ul className="space-y-1.5">
                                    {["System errors or crashes", "Data not saving or loading", "Feature request or customization", "Login / authentication issues", "New module requirements"].map(item => (
                                        <li key={item} className="flex items-center gap-2 text-sm text-slate-500 font-medium">
                                            <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 flex-shrink-0" />{item}
                                        </li>
                                    ))}
                                </ul>
                            </div>

                            <div className="rounded-2xl bg-white border border-slate-100 shadow-sm p-5">
                                <div className="flex items-start gap-3">
                                    <Shield className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
                                    <div>
                                        <p className="font-black text-slate-800 text-sm">Security & Data Privacy</p>
                                        <p className="text-xs text-slate-500 font-medium mt-1 leading-relaxed">All data is encrypted in transit. Sessions expire after 48 hours for security. Never share your login credentials.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                {/* Footer */}
                <footer className="text-center text-xs text-slate-400 font-medium pt-4 pb-6 border-t border-slate-200">
                    &copy; {new Date().getFullYear()} Enterprise Real Estate CRM &mdash;
                    {" "}<a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer" className="text-emerald-600 hover:underline font-bold">Contact Developer</a>
                </footer>

            </main>
        </div>
    );
}
