import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { Bell, Megaphone, Search, User, Plus, MessageCircle } from "lucide-react";
import { Paperclip, X as XIcon, Wallet, ClipboardList, Gift, Copy, Sparkles } from "lucide-react";

import { SiteLayout } from "@/components/site/SiteLayout";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { services } from "@/lib/services";

export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({ meta: [{ title: "Dashboard — Flexflares Cyber Services" }, { name: "description", content: "Your Flexflares Cyber Services dashboard." }] }),
  component: Dashboard,
});

type Profile = { full_name: string | null; username: string | null; email: string | null; avatar_url: string | null; phone: string | null };

const announcements = [
  { title: "SHA registration now available", body: "We now assist with the new Social Health Authority (SHA) registration.", date: "2 days ago" },
  { title: "Free CV review this week", body: "Get a free 10‑minute CV review with any printing order.", date: "5 days ago" },
  { title: "HELB compliance certificates", body: "HELB compliance certificates processed within 30 minutes.", date: "1 week ago" },
];

function Dashboard() {
  const [profile, setProfile] = useState<Profile | null>(null);
  const [groupUrl, setGroupUrl] = useState<string | null>(null);
  const [balance, setBalance] = useState<number>(0);
  const [points, setPoints] = useState<number>(0);
  const [refCode, setRefCode] = useState<string | null>(null);
  const [refCount, setRefCount] = useState<number>(0);
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({ service_slug: "", contact_name: "", contact_phone: "", contact_email: "", notes: "" });
  const [files, setFiles] = useState<File[]>([]);

  useEffect(() => {
    (async () => {
      const { data: u } = await supabase.auth.getUser();
      if (!u.user) return;
      const { data } = await supabase.from("profiles").select("full_name, username, email, avatar_url, phone, referral_code, loyalty_points").eq("id", u.user.id).maybeSingle();
      setProfile(data ?? { full_name: null, username: null, email: u.user.email ?? null, avatar_url: null, phone: null });
      const p = data as { referral_code: string | null; loyalty_points: number | null } | null;
      setRefCode(p?.referral_code ?? null);
      setPoints(Number(p?.loyalty_points ?? 0));
      const { data: w } = await supabase.from("wallets").select("balance").eq("user_id", u.user.id).maybeSingle();
      setBalance(Number((w as { balance: number | null } | null)?.balance ?? 0));
      const { count } = await supabase.from("referrals").select("*", { count: "exact", head: true }).eq("referrer_id", u.user.id);
      setRefCount(count ?? 0);
    })();
    supabase.from("business_settings").select("whatsapp_group_url").eq("id", 1).maybeSingle().then(({ data }) => {
      setGroupUrl((data as { whatsapp_group_url: string | null } | null)?.whatsapp_group_url ?? null);
    });
  }, []);

  const referralLink = refCode ? `${typeof window !== "undefined" ? window.location.origin : ""}/auth?mode=register&ref=${refCode}` : "";
  const copyRef = async () => {
    if (!referralLink) return;
    await navigator.clipboard.writeText(referralLink);
    toast.success("Referral link copied");
  };

  const displayName = profile?.full_name || profile?.username || profile?.email?.split("@")[0] || "there";
  const initials = (displayName || "?").slice(0, 2).toUpperCase();
  const filtered = q ? services.filter((s) => s.name.toLowerCase().includes(q.toLowerCase())) : services.slice(0, 8);

  useEffect(() => {
    if (open && profile) {
      setForm((f) => ({
        ...f,
        contact_name: f.contact_name || profile.full_name || profile.username || "",
        contact_phone: f.contact_phone || profile.phone || "",
        contact_email: f.contact_email || profile.email || "",
      }));
    }
  }, [open, profile]);

  const submitRequest = async () => {
    const svc = services.find((s) => s.slug === form.service_slug);
    if (!svc) return toast.error("Please choose a service");
    if (!form.contact_name.trim() || !form.contact_phone.trim()) return toast.error("Name and phone are required");
    setSubmitting(true);
    try {
      const { data: u } = await supabase.auth.getUser();
      const userId = u.user?.id ?? null;

      // Upload attachments (optional) to private storage bucket.
      const uploaded: { path: string; name: string; size: number; type: string }[] = [];
      if (files.length && userId) {
        const folder = `${userId}/${crypto.randomUUID()}`;
        for (const f of files) {
          if (f.size > 10 * 1024 * 1024) {
            toast.error(`${f.name} exceeds 10MB limit`);
            continue;
          }
          const safe = f.name.replace(/[^a-zA-Z0-9._-]/g, "_");
          const path = `${folder}/${Date.now()}-${safe}`;
          const up = await supabase.storage.from("request-attachments").upload(path, f, {
            contentType: f.type || "application/octet-stream",
            upsert: false,
          });
          if (up.error) {
            toast.error(`Upload failed: ${f.name}`);
            continue;
          }
          uploaded.push({ path, name: f.name, size: f.size, type: f.type });
        }
      }

      if (!u.user?.id) throw new Error("You must be signed in to submit a request.");
      const { error } = await supabase.from("service_requests").insert({
        user_id: u.user.id,
        service_slug: svc.slug,
        service_name: svc.name,
        contact_name: form.contact_name.trim(),
        contact_phone: form.contact_phone.trim(),
        contact_email: form.contact_email.trim() || null,
        notes: form.notes.trim() || null,
        attachments: uploaded,
      });
      if (error) throw error;

      const lines = [
        `*New Service Request — Flexflares*`,
        `Service: ${svc.name}`,
        `Name: ${form.contact_name}`,
        `Phone: ${form.contact_phone}`,
        form.contact_email ? `Email: ${form.contact_email}` : "",
        form.notes ? `Notes: ${form.notes}` : "",
        uploaded.length ? `Attachments: ${uploaded.length} file(s)` : "",
      ].filter(Boolean).join("\n");

      const waUrl = `https://wa.me/254717576870?text=${encodeURIComponent(lines)}`;
      window.open(waUrl, "_blank", "noopener,noreferrer");

      toast.success("Request submitted! Opening WhatsApp to confirm.");
      setOpen(false);
      setForm({ service_slug: "", contact_name: "", contact_phone: "", contact_email: "", notes: "" });
      setFiles([]);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to submit request");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SiteLayout>
      <section className="mx-auto max-w-7xl px-4 pt-10 pb-16 sm:px-6">
        {/* Welcome */}
        <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-4 sm:flex sm:flex-wrap sm:justify-between">
          <div className="flex min-w-0 items-center gap-4">
            <Avatar className="h-14 w-14 shrink-0 ring-2 ring-primary/30">
              <AvatarImage src={profile?.avatar_url ?? undefined} />
              <AvatarFallback className="gradient-hero text-white">{initials}</AvatarFallback>
            </Avatar>
            <div className="min-w-0">
              <div className="text-sm text-muted-foreground">Welcome back</div>
              <h1 className="truncate text-2xl font-bold sm:text-3xl">Hello, {displayName} 👋</h1>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="secondary" className="gap-1"><Bell className="h-3 w-3" /> 3 new updates</Badge>
            <Dialog open={open} onOpenChange={setOpen}>
              <DialogTrigger asChild>
                <Button size="sm" className="shadow-glow"><Plus className="mr-1 h-4 w-4" /> Request service</Button>
              </DialogTrigger>
              <DialogContent className="max-h-[90vh] overflow-y-auto">
                <DialogHeader><DialogTitle>Request a service</DialogTitle></DialogHeader>
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Service</Label>
                    <Select value={form.service_slug} onValueChange={(v) => setForm({ ...form, service_slug: v })}>
                      <SelectTrigger><SelectValue placeholder="Choose a service" /></SelectTrigger>
                      <SelectContent className="max-h-72">
                        {services.map((s) => (
                          <SelectItem key={s.slug} value={s.slug}>{s.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>Full name</Label>
                    <Input value={form.contact_name} onChange={(e) => setForm({ ...form, contact_name: e.target.value })} />
                  </div>
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label>Phone</Label>
                      <Input value={form.contact_phone} onChange={(e) => setForm({ ...form, contact_phone: e.target.value })} placeholder="+254…" />
                    </div>
                    <div className="space-y-2">
                      <Label>Email (optional)</Label>
                      <Input type="email" value={form.contact_email} onChange={(e) => setForm({ ...form, contact_email: e.target.value })} />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>Details / notes</Label>
                    <Textarea rows={4} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} placeholder="Anything we should know…" />
                  </div>
                  <div className="space-y-2">
                    <Label>Attachments (optional)</Label>
                    <label className="flex cursor-pointer items-center justify-center gap-2 rounded-md border border-dashed px-3 py-4 text-sm text-muted-foreground hover:bg-muted">
                      <Paperclip className="h-4 w-4" />
                      <span>Attach IDs, forms, or screenshots (max 10MB each)</span>
                      <input
                        type="file"
                        multiple
                        className="hidden"
                        accept="image/*,application/pdf,.doc,.docx"
                        onChange={(e) => {
                          const list = Array.from(e.target.files ?? []);
                          setFiles((prev) => [...prev, ...list]);
                          e.target.value = "";
                        }}
                      />
                    </label>
                    {files.length > 0 && (
                      <ul className="space-y-1 text-sm">
                        {files.map((f, i) => (
                          <li key={`${f.name}-${i}`} className="flex items-center justify-between rounded-md bg-muted/50 px-2 py-1">
                            <span className="truncate">{f.name} <span className="text-xs text-muted-foreground">({(f.size / 1024).toFixed(0)} KB)</span></span>
                            <button type="button" onClick={() => setFiles((prev) => prev.filter((_, j) => j !== i))} className="text-muted-foreground hover:text-destructive">
                              <XIcon className="h-4 w-4" />
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
                  <Button onClick={submitRequest} disabled={submitting}>{submitting ? "Submitting…" : "Send request"}</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        {/* Search */}
        <div className="glass mt-8 flex items-center gap-3 rounded-2xl p-3 shadow-elegant">
          <Search className="ml-2 h-5 w-5 text-muted-foreground" />
          <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search services…" className="border-0 bg-transparent shadow-none focus-visible:ring-0" />
        </div>

        <div className="mt-8 grid gap-6 lg:grid-cols-3">
          {/* Quick access */}
          <div className="lg:col-span-2">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold">Quick access</h2>
              <Link to="/services" className="text-sm text-primary hover:underline">View all</Link>
            </div>
            <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
              {filtered.slice(0, 12).map((s) => (
                <Link key={s.slug} to="/services/$slug" params={{ slug: s.slug }}>
                  <Card className="group h-full transition-all hover:-translate-y-1 hover:shadow-glow">
                    <CardContent className="p-4">
                      <div className="grid h-10 w-10 place-items-center rounded-xl bg-primary/10 text-primary transition-colors group-hover:bg-primary group-hover:text-primary-foreground">
                        <s.icon className="h-5 w-5" />
                      </div>
                      <div className="mt-2 text-sm font-semibold leading-tight">{s.name}</div>
                      <div className="text-xs text-muted-foreground">{s.price}</div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            <Card className="border-primary/30 bg-primary/5">
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold"><Wallet className="h-4 w-4 text-primary" /> Account balance</div>
                <div className="mt-2 text-3xl font-bold tracking-tight">KSh {balance.toFixed(2)}</div>
                <p className="mt-1 text-xs text-muted-foreground">Top up to pay for services instantly.</p>
                <div className="mt-3 grid grid-cols-2 gap-2">
                  <Button asChild size="sm"><Link to="/deposits">Deposit</Link></Button>
                  <Button asChild size="sm" variant="outline"><Link to="/my-services"><ClipboardList className="mr-1 h-4 w-4"/>My services</Link></Button>
                </div>
              </CardContent>
            </Card>

            <Card className="border-amber-500/30 bg-amber-500/5">
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold"><Sparkles className="h-4 w-4 text-amber-600" /> Loyalty points</div>
                <div className="mt-2 text-3xl font-bold tracking-tight">{points.toLocaleString()} <span className="text-sm font-medium text-muted-foreground">pts</span></div>
                <p className="mt-1 text-xs text-muted-foreground">1 point = KSh 1 off future services. Earn 5% back on every paid service.</p>
                <Button asChild size="sm" variant="outline" className="mt-3"><Link to="/offers">Browse offers</Link></Button>
              </CardContent>
            </Card>

            <Card className="border-primary/20">
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold"><Gift className="h-4 w-4 text-primary" /> Invite &amp; earn</div>
                <p className="mt-1 text-xs text-muted-foreground">Earn KSh 100 when a friend makes their first paid service.</p>
                {refCode ? (
                  <>
                    <div className="mt-3 flex items-center gap-2 rounded-md border bg-background/50 p-2">
                      <div className="min-w-0 flex-1">
                        <div className="text-[10px] uppercase tracking-wide text-muted-foreground">Your code</div>
                        <div className="truncate font-mono text-sm font-semibold">{refCode}</div>
                      </div>
                      <Button size="sm" variant="ghost" onClick={copyRef} title="Copy invite link"><Copy className="h-4 w-4" /></Button>
                    </div>
                    <p className="mt-2 text-xs text-muted-foreground">{refCount} friend{refCount === 1 ? "" : "s"} invited</p>
                  </>
                ) : (
                  <p className="mt-3 text-xs text-muted-foreground">Referral code generating…</p>
                )}
              </CardContent>
            </Card>

            <Card className="border-emerald-500/30 bg-emerald-500/5">
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold">
                  <MessageCircle className="h-4 w-4 text-emerald-600" /> Join our WhatsApp group
                </div>
                <p className="mt-2 text-xs text-muted-foreground">
                  Get instant updates, offers, and quick support from the Flexflares community.
                </p>
                <Button
                  asChild
                  size="sm"
                  className="mt-3 w-full bg-emerald-600 text-white hover:bg-emerald-700"
                  disabled={!groupUrl}
                >
                  {groupUrl ? (
                    <a href={groupUrl} target="_blank" rel="noopener noreferrer">
                      <MessageCircle className="mr-1 h-4 w-4" /> Join group
                    </a>
                  ) : (
                    <span>Link coming soon</span>
                  )}
                </Button>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold"><User className="h-4 w-4" /> Account details</div>
                <dl className="mt-4 space-y-3 text-sm">
                  <div className="flex justify-between gap-3"><dt className="text-muted-foreground">Name</dt><dd className="truncate">{profile?.full_name ?? "—"}</dd></div>
                  <div className="flex justify-between gap-3"><dt className="text-muted-foreground">Username</dt><dd className="truncate">{profile?.username ?? "—"}</dd></div>
                  <div className="flex justify-between gap-3"><dt className="text-muted-foreground">Email</dt><dd className="truncate">{profile?.email ?? "—"}</dd></div>
                  <div className="flex justify-between gap-3"><dt className="text-muted-foreground">Phone</dt><dd className="truncate">{profile?.phone ?? "—"}</dd></div>
                </dl>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-2 text-sm font-semibold"><Megaphone className="h-4 w-4" /> Announcements</div>
                <ul className="mt-4 space-y-4">
                  {announcements.map((a) => (
                    <li key={a.title}>
                      <div className="text-sm font-medium">{a.title}</div>
                      <div className="text-xs text-muted-foreground">{a.body}</div>
                      <div className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{a.date}</div>
                    </li>
                  ))}
                </ul>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>
    </SiteLayout>
  );
}