<template>
  <ConfirmationProvider>
    <ToastProvider>
      <div class="w-full flex justify-center py-8">
        <form
          @submit.prevent="handleSubmit"
          class="w-full max-w-[538px] p-4 md:p-6 xl:p-8 space-y-6 bg-background-primary rounded-lg border border-stroke-primary shadow-sm"
        >
          <!-- Header -->
          <div class="mb-8">
            <h1 class="text-2xl font-bold text-content-primary mb-2">
              Buat akun Anda
            </h1>
            <p class="text-sm text-content-secondary">
              Masukkan informasi berikut untuk membuat akun.
            </p>
          </div>

          <!-- Name -->
          <TextField
            v-model="name"
            :label="nameLabel"
            placeholder="Dwi Anjasmara"
            :required="true"
            :status="fieldStatus.name || 'neutral'"
            :status-message="fieldErrors.name"
          />

          <!-- Phone with Country Code -->
          <PhoneInput
            v-model="phone"
            :label="phoneLabel"
            :required="true"
            placeholder="878-8668-3355"
            :status="fieldStatus.phone || 'neutral'"
            :status-message="fieldErrors.phone"
            helper-text="Informasi ini digunakan untuk menghubungi Anda dan tidak akan dibagikan kepada pihak lain."
            @update:model-value="handlePhoneChange"
          />

          <!-- Email -->
          <TextField
            v-model="email"
            :label="emailLabel"
            type="email"
            placeholder="example@email.com"
            :required="true"
            :status="fieldStatus.email || 'neutral'"
            :status-message="fieldErrors.email"
            @update:model-value="handleEmailChange"
          />

          <!-- Password -->
          <PasswordInput
            v-model="password"
            label="Kata Sandi"
            placeholder="Isi kata sandi Anda"
            :required="true"
            :status="fieldStatus.password || 'neutral'"
            helper-text="Minimal 8 karakter."
            :status-message="fieldErrors.password"
            @update:model-value="handlePasswordChange"
          />

          <!-- Confirm Password -->
          <PasswordInput
            v-model="confirmPassword"
            :label="confirmPasswordLabel"
            placeholder="Ulangi kata sandi Anda"
            :required="true"
            :status="fieldStatus.confirmPassword || 'neutral'"
            :status-message="fieldErrors.confirmPassword"
            @update:model-value="handleConfirmPasswordChange"
          />

          <!-- Submit Button -->
          <Button type="submit" hierarchy="primary" class="w-full"
            >Buat Akun</Button
          >

          <!-- Divider -->
          <div class="flex items-center gap-4">
            <div class="flex-1 h-px bg-gray-300"></div>
            <span class="text-sm text-gray-500">Atau</span>
            <div class="flex-1 h-px bg-gray-300"></div>
          </div>

          <!-- Google Button -->
          <Button
            type="button"
            hierarchy="secondary"
            class="w-full flex items-center justify-center gap-2"
          >
            <svg width="20" height="20" viewBox="0 0 24 24">
              <path
                fill="#4285F4"
                d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              />
              <path
                fill="#34A853"
                d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              />
              <path
                fill="#FBBC05"
                d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
              />
              <path
                fill="#EA4335"
                d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              />
            </svg>
            Buat Akun dengan Google
          </Button>

          <!-- Footer -->
          <p class="text-xs text-content-secondary text-center">
            Dengan mendaftar, Anda menyetujui
            <a href="#" class="text-blue-600 hover:underline">Ketentuan</a>
            dan
            <a href="#" class="text-blue-600 hover:underline"
              >Kebijakan Privasi</a
            >
            kami.
          </p>
        </form>
      </div>
    </ToastProvider>
  </ConfirmationProvider>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import {
  TextField,
  Button,
  PasswordInput,
  PhoneInput,
  ConfirmationProvider,
  ToastProvider,
  useConfirmation,
  useToast,
} from '@idds/vue';

const phoneLabel = 'Nomor Ponsel';
const nameLabel = 'Nama Lengkap';
const emailLabel = 'Email';
const confirmPasswordLabel = 'Konfirmasi Kata Sandi';

const validateEmail = (
  email: string,
): { isValid: boolean; message: string } => {
  if (!email.trim()) {
    return { isValid: false, message: 'Email wajib diisi' };
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return { isValid: false, message: 'Format email tidak valid' };
  }
  return { isValid: true, message: '' };
};

const validatePhone = (
  phone: string,
): { isValid: boolean; message: string } => {
  if (!phone.trim()) {
    return { isValid: false, message: 'Nomor ponsel wajib diisi' };
  }
  const cleanedPhone = phone.replace(/[\s-+]/g, '');
  if (!/^[0-9]{10,15}$/.test(cleanedPhone)) {
    return { isValid: false, message: 'Nomor ponsel harus 10-15 digit angka' };
  }
  return { isValid: true, message: '' };
};

const validatePassword = (
  password: string,
): { isValid: boolean; message: string } => {
  if (!password.trim()) {
    return { isValid: false, message: 'Kata sandi wajib diisi' };
  }
  if (password.length < 8) {
    return { isValid: false, message: 'Minimal 8 karakter' };
  }
  if (!/[A-Z]/.test(password)) {
    return { isValid: false, message: 'Harus mengandung huruf besar' };
  }
  if (!/[a-z]/.test(password)) {
    return { isValid: false, message: 'Harus mengandung huruf kecil' };
  }
  if (!/[0-9]/.test(password)) {
    return { isValid: false, message: 'Harus mengandung angka' };
  }
  return { isValid: true, message: '' };
};

// Form state
const name = ref('Dwi Anjasmara');
const phone = ref('+6287886683355');
const email = ref('example@email.com');
const password = ref('');
const confirmPassword = ref('');

// Validation state
const submitted = ref(false);
const fieldErrors = ref<Record<string, string>>({});
const fieldStatus = ref<Record<string, 'neutral' | 'error' | 'success'>>({});

// Composables
const { confirm } = useConfirmation();
const { toast } = useToast();

const handleEmailChange = (value: string | Event) => {
  const val =
    typeof value === 'string'
      ? value
      : (value.target as HTMLInputElement).value;
  email.value = val;
  if (submitted.value) {
    const validation = validateEmail(val);
    if (validation.isValid) {
      fieldStatus.value.email = 'success';
      delete fieldErrors.value.email;
    } else {
      fieldStatus.value.email = 'error';
      fieldErrors.value.email = validation.message;
    }
  }
};

const handlePhoneChange = (value: string) => {
  phone.value = value;
  if (submitted.value) {
    const validation = validatePhone(value);
    if (validation.isValid) {
      fieldStatus.value.phone = 'success';
      delete fieldErrors.value.phone;
    } else {
      fieldStatus.value.phone = 'error';
      fieldErrors.value.phone = validation.message;
    }
  }
};

const handlePasswordChange = (value: string) => {
  password.value = value;
  if (submitted.value) {
    const validation = validatePassword(value);
    if (validation.isValid) {
      fieldStatus.value.password = 'success';
      delete fieldErrors.value.password;
    } else {
      fieldStatus.value.password = 'error';
      fieldErrors.value.password = validation.message;
    }
  }
};

const handleConfirmPasswordChange = (value: string) => {
  confirmPassword.value = value;
  if (submitted.value) {
    if (!value.trim()) {
      fieldStatus.value.confirmPassword = 'error';
      fieldErrors.value.confirmPassword = 'Konfirmasi kata sandi wajib diisi';
    } else if (value !== password.value) {
      fieldStatus.value.confirmPassword = 'error';
      fieldErrors.value.confirmPassword = 'Kata sandi tidak cocok';
    } else {
      fieldStatus.value.confirmPassword = 'success';
      delete fieldErrors.value.confirmPassword;
    }
  }
};

const handleSubmit = async () => {
  submitted.value = true;

  const errors: Record<string, string> = {};
  const status: Record<string, 'error' | 'success'> = {};

  // Validate name
  if (!name.value.trim()) {
    errors.name = 'Nama lengkap wajib diisi';
    status.name = 'error';
  }

  // Validate email
  const emailValidation = validateEmail(email.value);
  if (!emailValidation.isValid) {
    errors.email = emailValidation.message;
    status.email = 'error';
  } else {
    status.email = 'success';
  }

  // Validate phone
  const phoneValidation = validatePhone(phone.value);
  if (!phoneValidation.isValid) {
    errors.phone = phoneValidation.message;
    status.phone = 'error';
  } else {
    status.phone = 'success';
  }

  // Validate password
  const passwordValidation = validatePassword(password.value);
  if (!passwordValidation.isValid) {
    errors.password = passwordValidation.message;
    status.password = 'error';
  } else {
    status.password = 'success';
  }

  // Validate confirm password
  if (!confirmPassword.value.trim()) {
    errors.confirmPassword = 'Konfirmasi kata sandi wajib diisi';
    status.confirmPassword = 'error';
  } else if (confirmPassword.value !== password.value) {
    errors.confirmPassword = 'Kata sandi tidak cocok';
    status.confirmPassword = 'error';
  } else {
    status.confirmPassword = 'success';
  }

  fieldErrors.value = errors;
  fieldStatus.value = status;

  // If no errors, submit form
  if (Object.keys(errors).length === 0) {
    console.log('Form submitted:', {
      name: name.value,
      phone: phone.value,
      email: email.value,
    });

    // Show confirmation modal
    const isConfirmed = await confirm({
      title: 'Konfirmasi Pendaftaran',
      message: 'Apakah data yang Anda masukkan sudah benar?',
      confirmText: 'Ya, Daftar',
      cancelText: 'Batal',
    });

    if (isConfirmed) {
      toast({
        title: 'Akun Berhasil Dibuat',
        description: 'Selamat, akun Anda telah berhasil didaftarkan.',
        state: 'positive',
        duration: 3000,
        position: 'top-right',
      });
    }
  }
};
</script>
