"use client";

import * as React from "react";
import { useUpdateProfileMutation } from "@/api/rtk";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "sonner";

interface EditProfileDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  profile?: {
    name?: string;
    profile?: {
      phone?: string | number;
      bio?: string;
    } | any;
  };
}

export function EditProfileDialog({
  isOpen,
  onOpenChange,
  profile,
}: EditProfileDialogProps) {
  const [updateProfile, { isLoading: isSaving }] = useUpdateProfileMutation();
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [bio, setBio] = React.useState("");

  React.useEffect(() => {
    if (isOpen && profile) {
      setName(profile.name ?? "");
      const userProfile = profile.profile as { phone?: string | number; bio?: string } | undefined;
      setPhone(String(userProfile?.phone ?? ""));
      setBio(String(userProfile?.bio ?? ""));
    }
  }, [isOpen, profile]);

  const handleSave = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const trimmedName = name.trim();
    if (!trimmedName) {
      toast.error("Name is required");
      return;
    }

    try {
      await updateProfile({
        name: trimmedName,
        phone: phone.trim() || undefined,
        bio: bio.trim() || undefined,
      }).unwrap();
      toast.success("Profile updated successfully");
      onOpenChange(false);
    } catch (error) {
      const message =
        error && typeof error === "object" && "data" in error
          ? ((error as { data?: { message?: string } }).data?.message ?? "Failed to update profile")
          : "Failed to update profile";
      toast.error(message);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[520px] rounded-2xl">
        <DialogHeader>
          <DialogTitle className="font-['Lexend']">Edit Profile</DialogTitle>
          <DialogDescription>
            Update your personal account details.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSave} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="profile-name">Name</Label>
            <Input
              id="profile-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter your name"
              className="rounded-xl"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="profile-phone">Phone</Label>
            <Input
              id="profile-phone"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="Enter your phone number"
              className="rounded-xl"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="profile-bio">Bio</Label>
            <Textarea
              id="profile-bio"
              value={bio}
              onChange={(e) => setBio(e.target.value)}
              placeholder="Write a short bio"
              className="min-h-24 rounded-xl"
            />
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="ghost"
              className="rounded-xl"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              className="rounded-xl bg-accent"
              disabled={isSaving}
            >
              {isSaving ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
