'use client';

import { Button } from '@/components/ui/button';
import { Mail, X } from 'lucide-react';
import React, { useEffect } from 'react';
import { useUploadProfileMutation } from '@/store/slice/uploadApi';
import useFormSubmitHandler from '@/hooks/formHandler';
import {
	UpdateAdminAccountInput,
	UpdateAdminAccountSchema,
} from '@/lib/modules/auth/auth.validation';
import RHFTextField from '@/components/forms/RHFTextField';
import RHFUploadImage from '@/components/forms/RHFUploadImage';

import { useForm } from 'react-hook-form';
import FormProvider from '@/components/forms/FormProvider';

import { zodResolver } from '@hookform/resolvers/zod';
import { AuthUserProfile } from '@/types/auth';

interface ProfileInfoProps {
	profile: AuthUserProfile | undefined;
	handleCancel?: () => void;
}

const EditProfile = ({ profile, handleCancel }: ProfileInfoProps) => {
	const [uploadProfile] = useUploadProfileMutation();

	const methods = useForm<UpdateAdminAccountInput>({
		resolver: zodResolver(UpdateAdminAccountSchema),
	});
	const { reset } = methods;
	useEffect(() => {
		if (profile) {
			reset({
				fullName: profile.fullName || '',
				phone: profile.phone || '',
				// email: profile.email || '',
				profileImage: profile.profileImage || '',
			});
		}
	}, [profile, reset]);

	const handleProfileUpdate = useFormSubmitHandler(
		async (data: UpdateAdminAccountInput) => {
			const formData = new FormData();

			// Always append basic fields
			if (data.fullName) {
				formData.append('fullName', data.fullName);
			}

			// Only append phone if it exists
			if (data.phone) {
				formData.append('phone', data.phone);
			}

			// Handle profile image
			if (data.profileImage instanceof File) {
				// New image uploaded
				formData.append('profileImage', data.profileImage);
			} else if (
				typeof data.profileImage === 'string' &&
				data.profileImage.trim().length > 0 &&
				data.profileImage !== profile?.profileImage
			) {
				// Keep existing image (send as string reference)
				formData.append('profileImage', data.profileImage);
			}

			const result = await uploadProfile(formData).unwrap();

			return { data: result };
		},
		() => {},
		'Profile updated successfully!'
	);

	return (
		<FormProvider
			methods={methods}
			onSubmit={methods.handleSubmit(handleProfileUpdate)}
		>
			{/* Profile Image Upload */}
			<div className="flex items-center gap-6">
				<RHFUploadImage
					name="profileImage"
					label=""
					size={100}
					className="w-full h-full object-cover"
					maxSizeMB={5}
				/>
				<p className="text-sm text-[#B8B2A8]">
					Click to change profile picture
				</p>
			</div>

			{/* Form Fields */}
			<div className="space-y-4">
				<RHFTextField
					name="fullName"
					label="Full Name"
					leftIcon="user"
					placeholder="Enter your full name"
				/>

				{/* Email - Read Only */}
				<div>
					<label className="text-sm font-medium text-[#EDEBE6] mb-2 block">
						Email Address
					</label>
					<div className="relative">
						<div className="absolute left-3 top-1/2 -translate-y-1/2 text-[#B8B2A8]">
							<Mail className="w-5 h-5" />
						</div>
						<input
							type="email"
							name="email"
							value={profile?.email || ''}
							disabled
							className="
									w-full h-11 pl-10 pr-4
									bg-[#14110E]/50
									border border-[#3A332C]
									rounded-lg
									text-[#B8B2A8]
									cursor-not-allowed
								"
						/>
					</div>
				</div>

				<RHFTextField
					name="phone"
					label="Phone Number"
					type="tel"
					leftIcon="phone"
					placeholder="Enter phone number"
					isRequired={false}
				/>
			</div>

			{/* Action Buttons */}
			<div className="flex gap-3 pt-4">
				<Button
					type="button"
					onClick={handleCancel}
					className="
							flex-1 px-4 py-2
							bg-transparent
							border border-[#3A332C]
							text-[#EDEBE6]
							rounded-lg
							hover:bg-[#1A1612]
							flex items-center justify-center gap-2
						"
				>
					<X className="w-4 h-4" />
					Cancel
				</Button>

				<Button
					type="submit"
					className="
							flex-1 px-4 py-2
							bg-[#CBB26A] hover:bg-[#B89E55]
							text-[#0A0907] font-medium
							rounded-lg
							disabled:opacity-50 disabled:cursor-not-allowed
							flex items-center justify-center gap-2
						"
				>
					EDIT
				</Button>
			</div>
		</FormProvider>
	);
};

export default EditProfile;
