import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { ExternalLink, PlayCircle, Upload, CheckCircle2, Download, HelpCircle, Sparkles } from "lucide-react";
import { toast } from "sonner";
import { AppShell } from "@/components/app/AppShell";
import { StatusBadge } from "@/components/app/StatusBadge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { supabase } from "@/integrations/supabase/client";
import { errMsg, inr, youtubeEmbed } from "@/lib/app";
import { TaskLogo } from "@/components/app/TaskLogo";

export const Route = createFileRoute("/_authenticated/tasks")({
  head: () => ({ meta: [{ title: "Tasks – RozTask" }, { name: "description", content: "Complete app tasks and earn rewards." }, { property: "og:title", content: "Tasks – RozTask" }, { property: "og:description", content: "Complete app tasks and earn rewards." }, { property: "og:type", content: "website" }, { name: "twitter:card", content: "summary" }] }),
  component: Tasks,
});

function Tasks() {
  const qc = useQueryClient();
  const [video, setVideo] = useState<string | null>(null);
  const [howTo, setHowTo] = useState<{ name: string; text: string; video: string } | null>(null);
  const [uploading, setUploading] = useState<string | null>(null);
  const { data } = useQuery({
    queryKey: ["tasks-user"],
    queryFn: async () => {
      const [{ data: tasks }, { data: subs }] = await Promise.all([
        supabase.from("tasks").select("*").eq("is_active", true).order("sort_order").order("task_number"),
        supabase.from("submissions").select("task_id,status,reason"),
      ]);
      return { tasks: tasks ?? [], submissions: subs ?? [], subs: new Map((subs ?? []).map((s) => [s.task_id, s])) };
    },
  });

  async function upload(taskId: string, file?: File) {
    if (!file) return;
    if (!file.type.startsWith("image/")) return void toast.error("Please upload an image");
    setUploading(taskId);
    try {
      const { data: u } = await supabase.auth.getUser();
      const path = `${u.user!.id}/${taskId}-${Date.now()}.${file.name.split(".").pop() || "jpg"}`;
      const { error: upErr } = await supabase.storage.from("screenshots").upload(path, file);
      if (upErr) throw upErr;
      const { error } = await supabase.rpc("submit_task", { _task_id: taskId, _path: path });
      if (error) throw error;
      toast.success("Submitted! Waiting for admin approval.");
      qc.invalidateQueries();
    } catch (e) {
      toast.error(errMsg(e));
    } finally {
      setUploading(null);
    }
  }

  const embed = youtubeEmbed(video);
  const counts = [
    { label: "Available", value: data?.tasks.filter((t) => !data.subs.has(t.id) || data.subs.get(t.id)?.status === "rejected").length, tone: "text-primary" },
    { label: "Pending", value: data?.submissions.filter((s) => s.status === "pending").length, tone: "text-accent" },
    { label: "Completed", value: data?.submissions.filter((s) => s.status === "approved").length, tone: "text-primary" },
  ];

  return (
    <AppShell>
      <h1 className="mb-1 text-3xl font-extrabold">Today's <span className="relative inline-block text-gradient">earning tasks<span className="absolute -bottom-1 left-0 h-1.5 w-full rounded-full bg-gradient-primary opacity-70" /></span></h1>
      <p className="mb-5 flex items-center gap-1.5 text-sm text-muted-foreground"><Sparkles className="h-4 w-4 text-accent" /> Start task → complete steps → upload screenshot → get paid</p>
      <dl aria-label="Task summary" className="mb-5 grid grid-cols-3 divide-x divide-border border-y border-border py-3">
        {counts.map((item) => (
          <div key={item.label} className="px-2 text-center">
            <dt className="text-xs text-muted-foreground">{item.label}</dt>
            <dd className={`mt-1 text-lg font-bold ${item.tone}`}>{item.value ?? "—"}</dd>
          </div>
        ))}
      </dl>
      <div className="grid gap-5 md:grid-cols-2">
        {data?.tasks.map((t) => {
          const sub = data.subs.get(t.id);
          const locked = sub && sub.status !== "rejected";
          return (
            <div key={t.id} className="glass-card animate-rise flex flex-col gap-3 rounded-3xl border-2 border-primary/25 p-5 shadow-glow">
              <div className="flex items-center gap-4">
                <div className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-gradient-primary text-3xl font-black text-primary-foreground ring-2 ring-primary/40">
                  <TaskLogo source={t.icon_url} name={t.app_name} className="h-full w-full object-cover" />
                </div>
                <div className="min-w-0 flex-1">
                  <span className="rounded-full bg-accent/15 px-2 py-0.5 text-[11px] font-bold text-accent">TASK #{t.task_number}</span>
                  <h3 className="mt-1 truncate text-xl font-extrabold">{t.app_name}</h3>
                  <p className="text-3xl font-black text-primary drop-shadow-[0_0_12px_var(--primary)]">{inr(t.reward)}</p>
                </div>
                {sub && <StatusBadge status={sub.status} />}
              </div>
              {t.description && <p className="text-sm text-muted-foreground">{t.description}</p>}
              {sub?.status === "rejected" && sub.reason && <p className="rounded-lg bg-destructive/15 px-3 py-2 text-xs text-destructive">Rejected: {sub.reason}</p>}
              <Button asChild variant="hero" className="h-14 rounded-2xl text-base font-extrabold" disabled={!t.link}>
                <a href={t.link || "#"} target="_blank" rel="noreferrer"><ExternalLink /> Start Task</a>
              </Button>
              <div className="grid grid-cols-2 gap-3">
                <Button asChild variant="secondary" className="h-12 rounded-2xl">
                  <a href={t.download_url || t.link || "#"} target="_blank" rel="noreferrer"><Download /> Download App</a>
                </Button>
                <Button variant="secondary" className="h-12 rounded-2xl" disabled={!t.watch_video_url && !t.video_url} onClick={() => setVideo(t.watch_video_url || t.video_url || "")}><PlayCircle /> Watch Video</Button>
              </div>
              <Button variant="outline" className="h-12 rounded-2xl border-accent/50 text-accent hover:bg-accent/10" onClick={() => setHowTo({ name: t.app_name, text: t.how_to_text, video: t.video_url ?? "" })}><HelpCircle /> How To Use</Button>
              {locked ? (
                <div className="flex items-center justify-center gap-2 rounded-2xl bg-primary/10 py-3 text-sm font-semibold text-primary"><CheckCircle2 className="h-4 w-4" /> Screenshot submitted</div>
              ) : (
                <label className="border-t border-border pt-3">
                  <input type="file" accept="image/*" className="hidden" onChange={(e) => upload(t.id, e.target.files?.[0])} />
                  <span className="flex h-14 w-full cursor-pointer items-center justify-center gap-2 rounded-2xl border-2 border-dashed border-accent/60 bg-accent/5 text-sm font-bold text-accent">
                    <Upload className="h-5 w-5" /> {uploading === t.id ? "Uploading..." : "Upload screenshot & Submit"}
                  </span>
                </label>
              )}
            </div>
          );
        })}
        {data && data.tasks.length === 0 && <p className="text-muted-foreground">No tasks right now. Check back soon!</p>}
      </div>
      <Dialog open={howTo !== null} onOpenChange={(o) => !o && setHowTo(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader><DialogTitle>How to use – {howTo?.name}</DialogTitle></DialogHeader>
          {howTo?.text && <p className="whitespace-pre-line text-sm">{howTo.text}</p>}
          {youtubeEmbed(howTo?.video ?? null) ? (
            <div className="aspect-video overflow-hidden rounded-lg"><iframe src={youtubeEmbed(howTo!.video)!} title="How to" className="h-full w-full" allow="autoplay; encrypted-media" allowFullScreen /></div>
          ) : howTo?.video ? <a href={howTo.video} target="_blank" rel="noreferrer" className="text-primary underline">Open video</a> : null}
          {!howTo?.text && !howTo?.video && <ol className="list-decimal space-y-1 pl-5 text-sm text-muted-foreground"><li>Start Task दबाएँ और app खोलें।</li><li>बताए गए steps पूरे करें।</li><li>Screenshot upload करके Submit करें।</li></ol>}
        </DialogContent>
      </Dialog>
      <Dialog open={video !== null} onOpenChange={(o) => !o && setVideo(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader><DialogTitle>Watch Video</DialogTitle></DialogHeader>
          {embed ? (
            <div className="aspect-video overflow-hidden rounded-lg"><iframe src={embed} title="How to" className="h-full w-full" allow="autoplay; encrypted-media" allowFullScreen /></div>
          ) : video ? (
            <a href={video} target="_blank" rel="noreferrer" className="text-primary underline">Open video</a>
          ) : null}
        </DialogContent>
      </Dialog>
    </AppShell>
  );
}
