"use client";

import type React from "react";

import type { User } from "@/src/models/users/users.model";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Loader2, ImageIcon } from "lucide-react";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/app/_components/ui/form";
import { Input } from "@/app/_components/ui/input";
import { Button } from "@/app/_components/ui/button";
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "@/app/_components/ui/avatar";
import { Label } from "@/app/_components/ui/label";
import { Separator } from "@/app/_components/ui/separator";
import { Switch } from "@/app/_components/ui/switch";
import { useRef, useState } from "react";
import { ScrollArea } from "@/app/_components/ui/scroll-area";
import {
  updateUser,
  uploadAvatar,
} from "@/app/(protected)/(admin)/dashboard/user-management/action";

const profileFormSchema = z.object({
  username: z.string().nullable().optional(),
  avatar: z.string().nullable().optional(),
});

type ProfileFormValues = z.infer<typeof profileFormSchema>;

interface ProfileSettingsProps {
  user: User | null;
}

export function ProfileSettings({ user }: ProfileSettingsProps) {
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Use profile data with fallbacks
  const username = user?.profile?.username || "";
  const userEmail = user?.email || "";
  const userAvatar = user?.profile?.avatar || "";

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues: {
      username: username || "",
      avatar: userAvatar || "",
    },
  });

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    if (!file || !user?.id || !user?.email) return;

    try {
      setIsUploading(true);

      // Upload avatar to storage
      const publicUrl = await uploadAvatar(user.id, user.email, file);

      console.log("publicUrl", publicUrl);

      // Update the form value
      form.setValue("avatar", publicUrl);
    } catch (error) {
      console.error("Error uploading avatar:", error);
    } finally {
      setIsUploading(false);
    }
  };

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  async function onSubmit(data: ProfileFormValues) {
    try {
      if (!user?.id) return;

      // Update profile in database
      const { error } = await updateUser(user.id, {
        profile: {
          avatar: data.avatar || undefined,
          username: data.username || undefined,
        },
      });

      if (error) throw error;
    } catch (error) {
      console.error("Error updating profile:", error);
    }
  }

  return (
    <ScrollArea className="h-[calc(100vh-140px)] w-full ">
      <div className="space-y-16 px-20 py-10">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Account</h3>
              <Separator className="" />
              <div className="flex items-start gap-4">
                <div
                  className="relative cursor-pointer group"
                  onClick={handleAvatarClick}
                >
                  <Avatar className="h-16 w-16">
                    <AvatarImage
                      src={form.watch("avatar") || ""}
                      alt={username}
                    />
                    <AvatarFallback>
                      {username?.[0]?.toUpperCase() ||
                        userEmail?.[0]?.toUpperCase()}
                    </AvatarFallback>
                    <div className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
                      {isUploading ? (
                        <Loader2 className="h-5 w-5 text-white animate-spin" />
                      ) : (
                        <ImageIcon className="h-5 w-5 text-white" />
                      )}
                    </div>
                  </Avatar>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleFileChange}
                    disabled={isUploading}
                  />
                </div>
                <div className="flex-1 space-y-1">
                  <Label>Preferred name</Label>
                  <FormField
                    control={form.control}
                    name="username"
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input
                            placeholder={userEmail.split("@")[0]}
                            className="bg-muted/50 w-80"
                            {...field}
                            value={field.value || userEmail.split("@")[0]}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>
            {/* <Button
              type="submit"
              variant="outline"
              size="sm"
              className="text-xs"
              disabled={isUploading || form.formState.isSubmitting}
            >
              {form.formState.isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-3 w-3 animate-spin" />
                  Saving...
                </>
              ) : (
                "Save changes"
              )}
            </Button> */}
          </form>
        </Form>

        <div className="">
          <h3 className="text-base font-medium">Account security</h3>
          <Separator className="my-2" />
          <div className="space-y-8">
            <div className="flex items-center justify-between">
              <div>
                <Label>Email</Label>
                <p className="text-sm text-muted-foreground">{userEmail}</p>
              </div>
              <Button variant="outline" size="sm">
                Change email
              </Button>
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label>Password</Label>
                <p className="text-sm text-muted-foreground">
                  Set a permanent password to login to your account.
                </p>
              </div>
              <Button variant="outline" size="sm">
                Change password
              </Button>
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label>2-step verification</Label>
                <p className="text-sm text-muted-foreground">
                  Add an additional layer of security to your account during
                  login.
                </p>
              </div>
              <Button variant="outline" size="sm">
                Add verification method
              </Button>
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label>Passkeys</Label>
                <p className="text-sm text-muted-foreground">
                  Securely sign-in with on-device biometric authentication.
                </p>
              </div>
              <Button variant="outline" size="sm">
                Add passkey
              </Button>
            </div>
          </div>
        </div>

        <div>
          <h3 className="text-base font-medium">Support</h3>
          <Separator className="my-2" />
          <div className="space-y-8">
            <div className="flex items-center justify-between">
              <div>
                <Label>Support access</Label>
                <p className="text-sm text-muted-foreground">
                  Grant temporary access to your account for support purposes.
                </p>
              </div>
              <Switch />
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label className="text-destructive">Delete account</Label>
                <p className="text-sm text-muted-foreground">
                  Permanently delete the account and remove access from all
                  workspaces.
                </p>
              </div>
              <Button variant="outline" size="sm" className="text-destructive">
                Delete account
              </Button>
            </div>
          </div>
        </div>
      </div>
    </ScrollArea>
  );
}
