import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Flame, Trophy, BookOpen, Clock, Save } from "lucide-react";
import { PageHeader } from "@/components/common/PageBits";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { userService } from "@/services";
import { toast } from "sonner";

const profileSchema = z.object({
  name: z.string().min(2, "Name too short").max(60),
  email: z.string().email("Invalid email"),
  role: z.string().min(2).max(80),
  weeklyGoalMin: z.coerce.number().int().min(30).max(3000),
});

type ProfileForm = z.infer<typeof profileSchema>;

export const Route = createFileRoute("/_app/profile")({
  head: () => ({ meta: [{ title: "Profile — Study Unique" }] }),
  component: ProfilePage,
});

function ProfilePage() {
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: ["me"], queryFn: userService.me });

  const form = useForm<ProfileForm>({
    resolver: zodResolver(profileSchema),
    values: data
      ? {
          name: data.name,
          email: data.email,
          role: data.role,
          weeklyGoalMin: data.weeklyGoalMin,
        }
      : undefined,
  });

  const update = useMutation({
    mutationFn: (v: ProfileForm) => userService.update(v),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["me"] });
      toast.success("Profile updated");
    },
  });

  if (isLoading || !data) return <Skeleton className="m-6 h-96" />;

  return (
    <div className="mx-auto w-full max-w-4xl space-y-6 p-4 md:p-6">
      <PageHeader title="Profile" description="Manage your account and learning preferences." />

      <div className="relative overflow-hidden rounded-2xl border border-border bg-card p-6">
        <div className="absolute inset-0 -z-10 gradient-mesh opacity-30" aria-hidden />
        <div className="flex flex-wrap items-center gap-5">
          <Avatar className="h-20 w-20 ring-2 ring-primary/30 ring-offset-4 ring-offset-background">
            <AvatarImage src={data.avatar} alt={data.name} />
            <AvatarFallback>{data.name.slice(0, 2)}</AvatarFallback>
          </Avatar>
          <div>
            <h2 className="text-xl font-semibold">{data.name}</h2>
            <p className="text-sm text-muted-foreground">{data.email}</p>
            <div className="mt-2 flex flex-wrap items-center gap-2">
              <Badge className="gradient-brand text-primary-foreground">{data.plan} plan</Badge>
              <Badge variant="outline">{data.role}</Badge>
            </div>
          </div>
        </div>

        <div className="mt-6 grid grid-cols-2 gap-3 md:grid-cols-4">
          <Stat icon={Flame} label="Streak" value={`${data.studyStreak} days`} />
          <Stat icon={Trophy} label="Avg quiz" value="87%" />
          <Stat icon={BookOpen} label="Documents" value="24" />
          <Stat icon={Clock} label="Weekly goal" value={`${data.weeklyGoalMin}m`} />
        </div>
      </div>

      <form
        onSubmit={form.handleSubmit((v) => update.mutate(v))}
        className="grid gap-4 rounded-2xl border border-border bg-card p-6 md:grid-cols-2"
      >
        <Field label="Full name" error={form.formState.errors.name?.message}>
          <Input {...form.register("name")} />
        </Field>
        <Field label="Email" error={form.formState.errors.email?.message}>
          <Input type="email" {...form.register("email")} />
        </Field>
        <Field label="Role / focus" error={form.formState.errors.role?.message}>
          <Input {...form.register("role")} />
        </Field>
        <Field label="Weekly study goal (minutes)" error={form.formState.errors.weeklyGoalMin?.message}>
          <Input type="number" min={30} max={3000} {...form.register("weeklyGoalMin")} />
        </Field>
        <div className="md:col-span-2 flex justify-end">
          <Button type="submit" className="gradient-brand text-primary-foreground" disabled={update.isPending}>
            <Save className="mr-1.5 h-4 w-4" /> Save changes
          </Button>
        </div>
      </form>
    </div>
  );
}

function Field({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs">{label}</Label>
      {children}
      {error && <p className="text-[11px] text-destructive">{error}</p>}
    </div>
  );
}

function Stat({ icon: Icon, label, value }: { icon: React.ComponentType<{ className?: string }>; label: string; value: string }) {
  return (
    <div className="rounded-xl border border-border bg-card/60 p-3">
      <div className="flex items-center justify-between">
        <p className="text-xs text-muted-foreground">{label}</p>
        <Icon className="h-3.5 w-3.5 text-primary" />
      </div>
      <p className="mt-1 text-lg font-semibold">{value}</p>
    </div>
  );
}
