<script setup>
import { ref } from "vue";
import { Link, router, useForm } from "@inertiajs/vue3";
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";
import AppCard from "@/Components/app/ui/card/AppCard.vue";
import { CardTitle } from "@/Components/ui/card";

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>
  <AppCard
    title=""
    padding="none"
    class="p-0! gap-0"
    header-class="py-3! px-4 gap-0 text-muted-foreground"
    body-class="p-4 border-t"
  >
    <template #header>
      <div class="flex items-center gap-2">
        <User size="18" />
        <CardTitle>Informacije profila</CardTitle>
      </div>
      <p class="text-sm">Posodobite informacije vašega profila in e-poštni naslov.</p>
    </template>

    <form @submit.prevent="updateProfileInformation" 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">Fotografija</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" />
              Izberi fotografijo
            </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" />
              Odstrani
            </Button>
          </div>
        </div>

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

      <!-- Name -->
      <div class="space-y-2">
        <Label for="name">Ime</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">E-pošta</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">
                Vaš e-poštni naslov ni potrjen.
                <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"
                >
                  Kliknite tukaj za ponovno pošiljanje potrditvenega e-sporočila.
                </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
                  >Nova povezava za potrditev je bila poslana na vaš e-poštni
                  naslov.</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>

    <template #footer>
      <div class="flex items-center justify-between w-full">
        <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">Shranjeno.</span>
        </div>
        <Button type="submit" :disabled="form.processing"> Shrani </Button>
      </div>
    </template>
  </AppCard>
</template>
