import { useState, useRef } from 'react';
import { useForm, usePage, router } from '@inertiajs/react';
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 { CardHeader, CardTitle, CardDescription, CardContent } from '@/Components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/Components/ui/avatar';
import { toast } from 'sonner';
import { Loader2, Camera, ImageIcon, ExternalLink } from 'lucide-react';
import ImageCropperDialog from '@/Components/ImageCropperDialog';
import useTranslation from '@/hooks/useTranslation';

export default function UpdateProfileInformation({ mustVerifyEmail, status, className = '' }) {
    const { t } = useTranslation();
    const user = usePage().props.auth.user;

    const { data, setData, patch, errors, processing } = useForm({
        name: user.name,
        email: user.email,
        username: user.username || '',
        bio: user.bio || '', 
    });

    const [cropperOpen, setCropperOpen] = useState(false);
    const [selectedImage, setSelectedImage] = useState(null);
    const [imageType, setImageType] = useState('avatar'); 
    const fileInputRef = useRef(null);

    const onFileChange = (e, type) => {
        if (e.target.files && e.target.files.length > 0) {
            const file = e.target.files[0];
            const reader = new FileReader();
            reader.onload = () => {
                setSelectedImage(reader.result);
                setImageType(type);
                setCropperOpen(true);
            };
            reader.readAsDataURL(file);
        }
        e.target.value = ''; 
    };

    const handleCropSave = (blob) => {
        const formData = new FormData();
        const fieldName = imageType === 'avatar' ? 'avatar' : 'cover_image';
        formData.append(fieldName, blob, `${fieldName}.jpg`);

        router.post(route('settings.images'), formData, {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                const successMsg = imageType === 'avatar' 
                    ? t('_profile_pic_updated', 'Profile picture updated')
                    : t('_cover_img_updated', 'Cover image updated');
                toast.success(successMsg);
                setCropperOpen(false);
            },
            onError: () => toast.error(t('_upload_failed', 'Failed to upload image')),
        });
    };

    const submit = (e) => {
        e.preventDefault();
        patch(route('settings.update'), {
            onSuccess: () => toast.success(t('_profile_updated', 'Profile Updated')),
            onError: () => toast.error(t('_update_failed', 'Failed to update profile')),
        });
    };

    return (
        <section className={className}>
            <input 
                type="file" 
                ref={fileInputRef} 
                className="hidden" 
                accept="image/*"
                onChange={(e) => onFileChange(e, fileInputRef.current.imageType)} 
            />

            <ImageCropperDialog 
                open={cropperOpen}
                setOpen={setCropperOpen}
                imageSrc={selectedImage}
                onCropComplete={handleCropSave}
                aspectRatio={imageType === 'avatar' ? 1 : 16/9} 
                title={imageType === 'avatar' ? t('_crop_profile_pic', "Crop Profile Picture") : t('_crop_cover_photo', "Crop Cover Photo")}
            />

            <div className="relative">
                {/* --- COVER IMAGE AREA --- */}
                <div className="group relative w-full h-56 bg-muted border-b overflow-hidden">
                    {user.cover_image ? (
                        <img src={user.cover_image} className="w-full h-full object-cover transition-transform group-hover:scale-105" alt="Cover" />
                    ) : (
                        <div className="w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200 dark:from-zinc-800 dark:to-zinc-900 text-muted-foreground/50">
                            <ImageIcon className="w-10 h-10 mb-2 opacity-50" />
                            <span className="text-sm font-medium">{t('_add_cover_image', 'Add a cover image')}</span>
                        </div>
                    )}
                    
                    <div className="absolute inset-0 bg-black/30 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                        <Button 
                            variant="secondary" 
                            size="sm"
                            className="shadow-lg backdrop-blur-md bg-white/90 dark:bg-black/90 hover:bg-white dark:hover:bg-black"
                            type="button"
                            onClick={() => {
                                fileInputRef.current.imageType = 'cover';
                                fileInputRef.current.click();
                            }}
                        >
                            <Camera className="w-4 h-4 me-2" /> {t('_change_cover', 'Change Cover')}
                        </Button>
                    </div>
                </div>

                {/* --- AVATAR & PROFILE LINK --- */}
                <div className="px-6 pb-6 relative">
                    <div className="flex flex-col sm:flex-row items-center sm:items-end justify-between -mt-12 mb-6 gap-6">
                        
                        {/* Left Side: Avatar */}
                        <div className="relative group/avatar">
                            <Avatar className="w-32 h-32 border-[6px] border-background shadow-xl">
                                <AvatarImage src={user.avatar || `https://ui-avatars.com/api/?name=${user.name}&background=000&color=fff`} className="object-cover" />
                                <AvatarFallback className="text-3xl">{user.name.charAt(0)}</AvatarFallback>
                            </Avatar>
                            
                            <button 
                                type="button"
                                onClick={() => {
                                    fileInputRef.current.imageType = 'avatar';
                                    fileInputRef.current.click();
                                }}
                                className="absolute inset-0 flex items-center justify-center bg-black/60 rounded-full opacity-0 group-hover/avatar:opacity-100 transition-all text-white backdrop-blur-[2px] cursor-pointer"
                            >
                                <Camera className="w-8 h-8" />
                            </button>
                        </div>

                        {/* Right Side: View Profile Button */}
                        <div className="mt-4 sm:mt-0">
                             <Button variant="outline" asChild>
                                <a href={route('author.show', user.username)} target="_blank" rel="noopener noreferrer">
                                    <ExternalLink className="me-2 h-4 w-4"/>
                                    {t('_view_public_profile', 'View Public Profile')}
                                </a>
                            </Button>
                        </div>

                    </div>

                    <CardContent className="p-0">
                        <form onSubmit={submit} className="space-y-5">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                                <div className="space-y-2">
                                    <Label htmlFor="username">{t('_username', 'Username')}</Label>
                                    <div className="relative">
                                        <span className="absolute start-3 top-2.5 text-muted-foreground">@</span>
                                        <Input
                                            id="username"
                                            value={data.username}
                                            onChange={(e) => setData('username', e.target.value)}
                                            required
                                            className="ps-7 bg-muted/30"
                                            placeholder="username"
                                        />
                                    </div>
                                </div>
                                
                                <div className="space-y-2">
                                    <Label htmlFor="name">{t('_full_name', 'Full Name')}</Label>
                                    <Input
                                        id="name"
                                        value={data.name}
                                        onChange={(e) => setData('name', e.target.value)}
                                        required
                                        autoComplete="name"
                                        className="bg-muted/30"
                                    />
                                    {errors.name && <p className="text-sm text-destructive">{errors.name}</p>}
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="email">{t('_email', 'Email Address')}</Label>
                                <Input
                                    id="email"
                                    type="email"
                                    value={data.email}
                                    onChange={(e) => setData('email', e.target.value)}
                                    required
                                    autoComplete="email"
                                    className="bg-muted/30"
                                />
                                {errors.email && <p className="text-sm text-destructive">{errors.email}</p>}
                            </div>

                            <div className="space-y-2">
                                <div className="flex justify-between">
                                    <Label htmlFor="bio">{t('_bio', 'Bio')}</Label>
                                    <span className="text-xs text-muted-foreground">{data.bio.length}/500</span>
                                </div>
                                <Textarea
                                    id="bio"
                                    value={data.bio}
                                    onChange={(e) => setData('bio', e.target.value)}
                                    placeholder={t('_bio_placeholder', 'Tell us a little about yourself...')}
                                    className="bg-muted/30 resize-none h-24"
                                    maxLength={500}
                                />
                                {errors.bio && <p className="text-sm text-destructive">{errors.bio}</p>}
                            </div>

                            <div className="flex justify-end pt-4">
                                <Button disabled={processing} size="lg" className="min-w-[120px]">
                                    {processing && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                                    {t('_save_changes', 'Save Changes')}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </div>
            </div>
        </section>
    );
}