<script setup>
import { ref } from 'vue';
import { Link, router, useForm } from '@inertiajs/vue3';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/Components/ui/card';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Avatar, AvatarImage, AvatarFallback } from '@/Components/ui/avatar';
import InputError from '@/Components/InputError.vue';
import { User, Mail, Camera, Trash2, CheckCircle, AlertCircle } from 'lucide-vue-next';

const props = defineProps({
    user: Object,
});

const form = useForm({
    _method: 'PUT',
    name: props.user.name,
    email: props.user.email,
    photo: null,
});

const verificationLinkSent = ref(null);
const photoPreview = ref(null);
const photoInput = ref(null);

const updateProfileInformation = () => {
    if (photoInput.value) {
        form.photo = photoInput.value.files[0];
    }

    form.post(route('user-profile-information.update'), {
        errorBag: 'updateProfileInformation',
        preserveScroll: true,
        onSuccess: () => clearPhotoFileInput(),
    });
};

const sendEmailVerification = () => {
    verificationLinkSent.value = true;
};

const selectNewPhoto = () => {
    photoInput.value.click();
};

const updatePhotoPreview = () => {
    const photo = photoInput.value.files[0];

    if (! photo) return;

    const reader = new FileReader();

    reader.onload = (e) => {
        photoPreview.value = e.target.result;
    };

    reader.readAsDataURL(photo);
};

const deletePhoto = () => {
    router.delete(route('current-user-photo.destroy'), {
        preserveScroll: true,
        onSuccess: () => {
            photoPreview.value = null;
            clearPhotoFileInput();
        },
    });
};

const clearPhotoFileInput = () => {
    if (photoInput.value?.value) {
        photoInput.value.value = null;
    }
};
</script>

<template>
    <Card>
        <form @submit.prevent="updateProfileInformation">
            <CardHeader>
                <div class="flex items-center gap-2">
                    <User class="h-5 w-5 text-muted-foreground" />
                    <CardTitle>Profile Information</CardTitle>
                </div>
                <CardDescription>
                    Update your account's profile information and email address.
                </CardDescription>
            </CardHeader>

            <CardContent class="space-y-6">
                <!-- Profile Photo -->
                <div v-if="$page.props.jetstream.managesProfilePhotos" class="space-y-4">
                    <input
                        id="photo"
                        ref="photoInput"
                        type="file"
                        class="hidden"
                        accept="image/*"
                        @change="updatePhotoPreview"
                    >

                    <Label for="photo">Photo</Label>

                    <div class="flex items-center gap-4">
                        <!-- Current/Preview Photo -->
                        <Avatar class="h-20 w-20">
                            <AvatarImage
                                v-if="photoPreview"
                                :src="photoPreview"
                                :alt="user.name"
                            />
                            <AvatarImage
                                v-else
                                :src="user.profile_photo_url"
                                :alt="user.name"
                            />
                            <AvatarFallback>
                                <User class="h-8 w-8" />
                            </AvatarFallback>
                        </Avatar>

                        <div class="flex gap-2">
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                @click.prevent="selectNewPhoto"
                            >
                                <Camera class="h-4 w-4 mr-2" />
                                Select Photo
                            </Button>

                            <Button
                                v-if="user.profile_photo_path"
                                type="button"
                                variant="outline"
                                size="sm"
                                @click.prevent="deletePhoto"
                            >
                                <Trash2 class="h-4 w-4 mr-2" />
                                Remove
                            </Button>
                        </div>
                    </div>

                    <InputError :message="form.errors.photo" class="mt-2" />
                </div>

                <!-- Name -->
                <div class="space-y-2">
                    <Label for="name">Name</Label>
                    <Input
                        id="name"
                        v-model="form.name"
                        type="text"
                        required
                        autocomplete="name"
                    />
                    <InputError :message="form.errors.name" class="mt-2" />
                </div>

                <!-- Email -->
                <div class="space-y-2">
                    <Label for="email">Email</Label>
                    <Input
                        id="email"
                        v-model="form.email"
                        type="email"
                        required
                        autocomplete="username"
                    />
                    <InputError :message="form.errors.email" class="mt-2" />

                    <!-- Email Verification -->
                    <div v-if="$page.props.jetstream.hasEmailVerification && user.email_verified_at === null" class="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-800 dark:bg-amber-950">
                        <div class="flex items-start gap-2">
                            <AlertCircle class="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5" />
                            <div class="flex-1 text-sm">
                                <p class="text-amber-800 dark:text-amber-200">
                                    Your email address is unverified.
                                    <Link
                                        :href="route('verification.send')"
                                        method="post"
                                        as="button"
                                        class="underline text-amber-900 hover:text-amber-700 dark:text-amber-100 dark:hover:text-amber-300 font-medium"
                                        @click.prevent="sendEmailVerification"
                                    >
                                        Click here to re-send the verification email.
                                    </Link>
                                </p>
                                <div v-show="verificationLinkSent" class="mt-2 flex items-center gap-1.5 text-green-700 dark:text-green-400">
                                    <CheckCircle class="h-4 w-4" />
                                    <span>A new verification link has been sent to your email address.</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </CardContent>

            <CardFooter class="flex items-center justify-between">
                <div class="flex items-center gap-2 text-sm text-muted-foreground">
                    <CheckCircle v-if="form.recentlySuccessful" class="h-4 w-4 text-green-600" />
                    <span v-if="form.recentlySuccessful">Saved.</span>
                </div>
                <Button type="submit" :disabled="form.processing">
                    Save
                </Button>
            </CardFooter>
        </form>
    </Card>
</template>
