import { redirect, Form } from "react-router";
import { auth } from "~/lib/auth.server";
import { findUserById, updateUser } from "~/models/user";
import type { Route } from "./+types/user-profile";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";

export function meta(): Route.MetaDescriptors {
  return [{ title: "Profile - Brackt" }];
}

export async function loader(args: Route.LoaderArgs) {
  const session = await auth.api.getSession({ headers: args.request.headers });
  if (!session) {
    return redirect("/login?redirectTo=/user-profile");
  }
  const user = await findUserById(session.user.id);
  if (!user) {
    return redirect("/");
  }
  return { user };
}

export async function action(args: Route.ActionArgs) {
  const session = await auth.api.getSession({ headers: args.request.headers });
  if (!session) {
    return redirect("/login?redirectTo=/user-profile");
  }

  const formData = await args.request.formData();
  const displayName = formData.get("displayName") as string;
  const username = formData.get("username") as string | null;
  const firstName = formData.get("firstName") as string | null;
  const lastName = formData.get("lastName") as string | null;

  await updateUser(session.user.id, {
    displayName: displayName || undefined,
    username: username || undefined,
    firstName: firstName || undefined,
    lastName: lastName || undefined,
  });

  return { success: true };
}

export default function UserProfilePage({ loaderData, actionData }: Route.ComponentProps) {
  const { user } = loaderData;

  return (
    <div className="container mx-auto py-8 px-4 max-w-lg">
      <Card>
        <CardHeader>
          <CardTitle>Your Profile</CardTitle>
        </CardHeader>
        <CardContent>
          {actionData?.success && (
            <p className="text-sm text-green-500 mb-4">Profile updated successfully.</p>
          )}
          <Form method="post" className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="displayName">Display Name</Label>
              <Input
                id="displayName"
                name="displayName"
                defaultValue={user.displayName ?? ""}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="username">Username</Label>
              <Input
                id="username"
                name="username"
                defaultValue={user.username ?? ""}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="firstName">First Name</Label>
                <Input
                  id="firstName"
                  name="firstName"
                  defaultValue={user.firstName ?? ""}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lastName">Last Name</Label>
                <Input
                  id="lastName"
                  name="lastName"
                  defaultValue={user.lastName ?? ""}
                />
              </div>
            </div>
            <div className="space-y-1">
              <Label>Email</Label>
              <p className="text-sm text-muted-foreground">{user.email}</p>
            </div>
            <Button type="submit" className="w-full">Save Changes</Button>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}
