import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { SupportAttachment } from "@/components/bkash/SupportAttachment";
import { supabase } from "@/integrations/supabase/client";
import { Headphones, Send, Loader2, Paperclip, X } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/support")({
  component: SupportPage,
});

type Msg = {
  id: string;
  user_id: string;
  sender: "user" | "admin";
  body: string | null;
  attachment_url: string | null;
  attachment_type: string | null;
  attachment_name: string | null;
  created_at: string;
};

function SupportPage() {
  const qc = useQueryClient();
  const [me, setMe] = useState<string | null>(null);
  const [text, setText] = useState("");
  const [sending, setSending] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => setMe(data.user?.id ?? null));
  }, []);

  const q = useQuery({
    queryKey: ["support", me],
    enabled: !!me,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("support_messages")
        .select("id, user_id, sender, body, attachment_url, attachment_type, attachment_name, created_at")
        .eq("user_id", me!)
        .order("created_at", { ascending: true })
        .limit(500);
      if (error) throw new Error(error.message);
      return (data ?? []) as Msg[];
    },
  });

  useEffect(() => {
    if (!me) return;
    const channel = supabase
      .channel(`support-${me}`)
      .on(
        "postgres_changes",
        { event: "INSERT", schema: "public", table: "support_messages", filter: `user_id=eq.${me}` },
        () => qc.invalidateQueries({ queryKey: ["support", me] }),
      )
      .subscribe();
    return () => {
      supabase.removeChannel(channel);
    };
  }, [me, qc]);

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [q.data?.length]);

  async function send() {
    if (!me || sending) return;
    const body = text.trim();
    if (!body && !file) return;
    setSending(true);
    try {
      let attachment_url: string | null = null;
      let attachment_type: string | null = null;
      let attachment_name: string | null = null;
      if (file) {
        if (file.size > 10 * 1024 * 1024) throw new Error("ফাইল ১০MB এর বেশি হতে পারবে না");
        const safe = file.name.replace(/[^a-zA-Z0-9._-]/g, "_");
        const path = `${me}/${Date.now()}-${safe}`;
        const up = await supabase.storage.from("support-attachments").upload(path, file, {
          contentType: file.type || "application/octet-stream",
          upsert: false,
        });
        if (up.error) throw new Error(up.error.message);
        attachment_url = path;
        attachment_type = file.type || "application/octet-stream";
        attachment_name = file.name;
      }
      const { error } = await supabase.from("support_messages").insert({
        user_id: me,
        sender: "user",
        body: body || null,
        attachment_url,
        attachment_type,
        attachment_name,
      });
      if (error) throw new Error(error.message);
      setText("");
      setFile(null);
      if (fileRef.current) fileRef.current.value = "";
      qc.invalidateQueries({ queryKey: ["support", me] });
    } catch (e: any) {
      toast.error(e.message ?? "পাঠানো যায়নি");
    } finally {
      setSending(false);
    }
  }

  const items = q.data ?? [];

  return (
    <ActionScreen title="লাইভ সাপোর্ট" subtitle="আমাদের সাপোর্ট টিমের সাথে চ্যাট করুন">
      <div className="bg-card rounded-2xl shadow-[var(--shadow-card)] flex flex-col h-[60vh] min-h-[400px] overflow-hidden">
        <div className="flex-1 overflow-y-auto p-4 space-y-2">
          {items.length === 0 && !q.isLoading && (
            <div className="h-full grid place-items-center text-center px-6">
              <div>
                <Headphones className="h-10 w-10 mx-auto text-muted-foreground/40" />
                <p className="mt-3 text-sm text-muted-foreground">
                  আপনার সমস্যা লিখুন বা ছবি/ফাইল পাঠান
                </p>
              </div>
            </div>
          )}
          {items.map((m) => {
            const mine = m.sender === "user";
            return (
              <div key={m.id} className={`flex ${mine ? "justify-end" : "justify-start"}`}>
                <div
                  className={`max-w-[80%] px-3 py-2 rounded-2xl text-sm whitespace-pre-wrap break-words ${
                    mine
                      ? "bg-primary text-primary-foreground rounded-br-sm"
                      : "bg-muted text-foreground rounded-bl-sm"
                  }`}
                >
                  {!mine && (
                    <p className="text-[10px] font-bold opacity-70 mb-0.5">সাপোর্ট</p>
                  )}
                  {m.attachment_url && (
                    <div className="mb-1">
                      <SupportAttachment
                        path={m.attachment_url}
                        type={m.attachment_type}
                        name={m.attachment_name}
                      />
                    </div>
                  )}
                  {m.body && <p>{m.body}</p>}
                  <p className={`text-[9px] mt-1 ${mine ? "opacity-70" : "text-muted-foreground"}`}>
                    {new Date(m.created_at).toLocaleTimeString("en-GB", {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </div>
              </div>
            );
          })}
          <div ref={endRef} />
        </div>
        {file && (
          <div className="px-3 py-2 border-t flex items-center gap-2 text-xs bg-muted/40">
            <Paperclip className="h-3 w-3" />
            <span className="flex-1 truncate">{file.name}</span>
            <button onClick={() => { setFile(null); if (fileRef.current) fileRef.current.value = ""; }} className="h-6 w-6 grid place-items-center rounded hover:bg-muted">
              <X className="h-3 w-3" />
            </button>
          </div>
        )}
        <div className="border-t p-2 flex items-center gap-2 bg-card">
          <input
            ref={fileRef}
            type="file"
            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"
            className="hidden"
            onChange={(e) => setFile(e.target.files?.[0] ?? null)}
          />
          <button
            onClick={() => fileRef.current?.click()}
            className="h-11 w-11 rounded-full bg-muted grid place-items-center shrink-0"
            aria-label="Attach"
          >
            <Paperclip className="h-4 w-4" />
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                send();
              }
            }}
            placeholder="মেসেজ লিখুন..."
            className="flex-1 h-11 px-4 rounded-full bg-muted text-sm outline-none focus:ring-2 focus:ring-primary min-w-0"
          />
          <button
            onClick={send}
            disabled={sending || (!text.trim() && !file)}
            className="h-11 w-11 rounded-full text-primary-foreground grid place-items-center disabled:opacity-50 shrink-0"
            style={{ background: "var(--gradient-primary)" }}
            aria-label="Send"
          >
            {sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
          </button>
        </div>
      </div>
    </ActionScreen>
  );
}
