"use client";

import { Camera, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateProfile, updateProfileAvatar } from "./profile-api";
import type { Profile, UpdateProfilePayload } from "./profile-types";

interface ProfileEditDialogProps {
  profile: Profile;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function profileFormValues(profile: Profile): UpdateProfilePayload {
  return {
    first_name: profile.first_name ?? "",
    last_name: profile.last_name ?? "",
    language: profile.language === "en" ? "en" : "ar",
    linkedin_url: profile.linkedin_url ?? "",
  };
}

export function ProfileEditDialog({ profile, open, onOpenChange }: ProfileEditDialogProps) {
  const t = useTranslations("dashboard.profile");
  const fileInput = useRef<HTMLInputElement>(null);
  const [avatarFile, setAvatarFile] = useState<File>();
  const [submitError, setSubmitError] = useState("");
  const form = useForm<UpdateProfilePayload>({ defaultValues: profileFormValues(profile) });

  useEffect(() => {
    if (open) form.reset(profileFormValues(profile));
  }, [form, open, profile]);

  const saveProfile = form.handleSubmit(async (fields) => {
    setSubmitError("");
    try {
      await updateProfile(fields);
      if (avatarFile) await updateProfileAvatar(avatarFile);
      setAvatarFile(undefined);
      onOpenChange(false);
    } catch (error) {
      setSubmitError(error instanceof Error ? error.message : t("errors.update"));
    }
  });

  const isSaving = form.formState.isSubmitting;

  return (
    <Dialog open={open} onOpenChange={isSaving ? undefined : onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-[656px] overflow-y-auto rounded-2xl p-0">
        <DialogHeader className="border-b px-6 py-5"><DialogTitle>{t("edit.title")}</DialogTitle><DialogDescription className="sr-only">{t("edit.description")}</DialogDescription></DialogHeader>
        <form onSubmit={saveProfile} className="space-y-5 px-6 pb-6">
          <div className="flex flex-col items-center gap-2">
            <div className="relative">
              <Avatar className="size-28 border-2 border-white shadow">
                <AvatarImage src={profile.avatar_url ?? profile.avatar ?? undefined} />
                <AvatarFallback>{profile.first_name?.[0] ?? "U"}</AvatarFallback>
              </Avatar>
              <Button type="button" size="icon" className="absolute -end-1 bottom-0 rounded-full" aria-label={t("edit.avatar")} disabled={isSaving} onClick={() => fileInput.current?.click()}><Camera /></Button>
              <input ref={fileInput} type="file" accept="image/*" className="sr-only" onChange={(event) => {
                const selectedFile = event.target.files?.[0];
                if (selectedFile?.type.startsWith("image/")) setAvatarFile(selectedFile);
                else if (selectedFile) setSubmitError(t("validation.image"));
              }} />
            </div>
            {avatarFile ? <span className="text-xs text-muted-foreground">{avatarFile.name}</span> : null}
          </div>
          <div className="space-y-5">
            <FormInput label={t("fields.firstName")} error={form.formState.errors.first_name?.message}><Input aria-label={t("fields.firstName")} {...form.register("first_name", { required: t("validation.required") })} /></FormInput>
            <FormInput label={t("fields.lastName")} error={form.formState.errors.last_name?.message}><Input aria-label={t("fields.lastName")} {...form.register("last_name", { required: t("validation.required") })} /></FormInput>
          </div>
          {profile.gender ? <FormInput label={t("fields.gender")}><Input value={profile.gender === "male" ? t("values.male") : profile.gender === "female" ? t("values.female") : profile.gender} readOnly disabled /></FormInput> : null}
          {profile.birth_date ? <FormInput label={t("fields.birthDate")}><Input value={profile.birth_date} readOnly disabled /></FormInput> : null}
          <FormInput label={t("fields.linkedin")}><Input aria-label={t("fields.linkedin")} type="url" placeholder="https://linkedin.com/in/..." {...form.register("linkedin_url")} /></FormInput>
          {profile.x_url ? <FormInput label={t("fields.x")}><Input value={profile.x_url} readOnly disabled /></FormInput> : null}
          {submitError ? <p role="alert" className="text-sm text-destructive">{submitError}</p> : null}
          <DialogFooter className="border-t pt-5 sm:justify-start">
            <Button type="submit" className="h-12 min-w-32 rounded-xl" disabled={isSaving}>{isSaving ? <Loader2 className="animate-spin" /> : null}{t("actions.save")}</Button>
            <Button type="button" variant="outline" className="h-12 min-w-32 rounded-xl" disabled={isSaving} onClick={() => onOpenChange(false)}>{t("actions.cancel")}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function FormInput({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return <div className="space-y-2"><Label>{label}</Label>{children}{error ? <p className="text-sm text-destructive">{error}</p> : null}</div>;
}
