<script lang="ts">
  import { _ } from "svelte-i18n";
  import { invalidateAll } from "$app/navigation";
  import { untrack } from "svelte";
  import { toast } from "svelte-sonner";
  import { updateProfile } from "$lib/services";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Label } from "$lib/components/ui/label";
  import * as Alert from "$lib/components/ui/alert";
  import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
  } from "$lib/components/ui/card";
  import Meta from "$lib/components/meta/meta.svelte";

  const { data } = $props();

  let email = $state(untrack(() => data.authStatus.user!.email));
  let password = $state("");
  let confirmPassword = $state("");
  let showPassword = $state(false);
  let showConfirmPassword = $state(false);

  let isSecurityLoading = $state(false);
  let isSecurityError = $state(false);
  let securityError = $state("");

  async function handleSecuritySubmit(e: Event) {
    e.preventDefault();
    try {
      if (password !== confirmPassword) {
        throw new Error($_("me.settings.password_error"));
      }
      isSecurityLoading = true;
      isSecurityError = false;
      securityError = "";
      await updateProfile({
        email,
        password,
      });
      toast.success($_("me.settings.toast_update"));
      invalidateAll();
      password = confirmPassword = "";
    } catch (err) {
      const e = err as { response?: { errors?: Array<{ message: string }> }; message?: string };
      securityError = e.response?.errors?.[0]?.message ?? e.message ?? "Unknown error";
      isSecurityError = true;
    } finally {
      isSecurityLoading = false;
    }
  }
</script>

<Meta title={$_("me.settings.privacy_title")} />

<div class="py-3 sm:py-6 lg:pl-6">
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-2xl font-bold">{$_("me.settings.privacy_title")}</h1>
  </div>

  <Card class="bg-card/50 border-primary/20 max-w-2xl">
      <CardHeader>
        <CardTitle>{$_("me.settings.privacy_title")}</CardTitle>
        <CardDescription>{$_("me.settings.privacy_subtitle")}</CardDescription>
      </CardHeader>
      <CardContent class="space-y-4">
        <form onsubmit={handleSecuritySubmit} class="space-y-4">
          <div class="space-y-2">
            <Label for="email">{$_("me.settings.email")}</Label>
            <Input
              id="email"
              type="email"
              placeholder={$_("me.settings.email_placeholder")}
              bind:value={email}
              required
              class="bg-background/50 border-primary/20 focus:border-primary"
            />
          </div>

          <div class="space-y-2">
            <Label for="password">{$_("me.settings.password")}</Label>
            <div class="relative">
              <Input
                id="password"
                type={showPassword ? "text" : "password"}
                placeholder={$_("me.settings.password_placeholder")}
                bind:value={password}
                required
                class="bg-background/50 border-primary/20 focus:border-primary pr-10"
              />
              <button
                type="button"
                onclick={() => (showPassword = !showPassword)}
                class="cursor-pointer absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              >
                {#if showPassword}
                  <span class="icon-[ri--eye-off-line] w-4 h-4"></span>
                {:else}
                  <span class="icon-[ri--eye-line] w-4 h-4"></span>
                {/if}
              </button>
            </div>
          </div>

          <div class="space-y-2">
            <Label for="confirmPassword">{$_("me.settings.confirm_password")}</Label>
            <div class="relative">
              <Input
                id="confirmPassword"
                type={showConfirmPassword ? "text" : "password"}
                placeholder={$_("me.settings.confirm_password_placeholder")}
                bind:value={confirmPassword}
                required
                class="bg-background/50 border-primary/20 focus:border-primary pr-10"
              />
              <button
                type="button"
                onclick={() => (showConfirmPassword = !showConfirmPassword)}
                class="cursor-pointer absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              >
                {#if showConfirmPassword}
                  <span class="icon-[ri--eye-off-line] w-4 h-4"></span>
                {:else}
                  <span class="icon-[ri--eye-line] w-4 h-4"></span>
                {/if}
              </button>
            </div>
          </div>

          {#if isSecurityError}
            <div class="grid w-full items-start gap-4">
              <Alert.Root variant="destructive">
                <Alert.Title class="items-center flex">
                  <span class="icon-[ri--alert-line] inline-block w-4 h-4 mr-1"></span>
                  {$_("me.settings.error")}
                </Alert.Title>
                <Alert.Description>{securityError}</Alert.Description>
              </Alert.Root>
            </div>
          {/if}

          <Button
            type="submit"
            class="cursor-pointer w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
            disabled={isSecurityLoading}
          >
            {#if isSecurityLoading}
              <div
                class="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"
              ></div>
              {$_("me.settings.updating_security")}
            {:else}
              {$_("me.settings.update_security")}
            {/if}
          </Button>
        </form>
      </CardContent>
    </Card>
</div>
