<script setup>
import { useField, useForm } from 'vee-validate'
import { watch, computed } from 'vue'
import * as yup from 'yup'

// ✅ FIXED: Define props and emits for v-model support
const props = defineProps({
  facebook: { type: String, default: '' },
  instagram: { type: String, default: '' },
  twitter: { type: String, default: '' },
  linkedin: { type: String, default: '' },
  youtube: { type: String, default: '' },
  tiktok: { type: String, default: '' },
  enableSharing: { type: Boolean, default: false }
})

const emit = defineEmits([
  'update:facebook',
  'update:instagram',
  'update:twitter',
  'update:linkedin',
  'update:youtube',
  'update:tiktok',
  'update:enableSharing'
])

// ✅ Validation Schema - Fixed to handle empty values properly
const schema = yup.object({
  facebook: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  instagram: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  twitter: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  linkedin: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  youtube: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  tiktok: yup
    .string()
    .nullable()
    .transform((value, originalValue) => {
      return originalValue === '' ? null : value
    })
    .test('optional-url', 'Enter a valid URL', (value) => {
      if (!value) return true
      return yup.string().url().isValidSync(value)
    }),
  enableSharing: yup.boolean().required(),
})

// ✅ Vee-validate form - Disable validation on mount
const { handleSubmit, setValues, resetForm, errors } = useForm({
  validationSchema: schema,
  validateOnMount: false,
  initialTouched: false,
})

const { value: facebook } = useField('facebook')
const { value: instagram } = useField('instagram')
const { value: twitter } = useField('twitter')
const { value: linkedin } = useField('linkedin')
const { value: youtube } = useField('youtube')
const { value: tiktok } = useField('tiktok')
const { value: enableSharing } = useField('enableSharing')

// ✅ FIXED: Watch props and update internal values
watch(() => props.facebook, (newVal) => {
  facebook.value = newVal || ''
}, { immediate: true })

watch(() => props.instagram, (newVal) => {
  instagram.value = newVal || ''
}, { immediate: true })

watch(() => props.twitter, (newVal) => {
  twitter.value = newVal || ''
}, { immediate: true })

watch(() => props.linkedin, (newVal) => {
  linkedin.value = newVal || ''
}, { immediate: true })

watch(() => props.youtube, (newVal) => {
  youtube.value = newVal || ''
}, { immediate: true })

watch(() => props.tiktok, (newVal) => {
  tiktok.value = newVal || ''
}, { immediate: true })

watch(() => props.enableSharing, (newVal) => {
  enableSharing.value = newVal || false
}, { immediate: true })

// ✅ FIXED: Watch internal values and emit to parent
watch(facebook, (newVal) => {
  emit('update:facebook', newVal || '')
})

watch(instagram, (newVal) => {
  emit('update:instagram', newVal || '')
})

watch(twitter, (newVal) => {
  emit('update:twitter', newVal || '')
})

watch(linkedin, (newVal) => {
  emit('update:linkedin', newVal || '')
})

watch(youtube, (newVal) => {
  emit('update:youtube', newVal || '')
})

watch(tiktok, (newVal) => {
  emit('update:tiktok', newVal || '')
})

watch(enableSharing, (newVal) => {
  emit('update:enableSharing', newVal || false)
})

// ✅ REMOVED: Individual save/reset functions since this is now a child component
// The parent component will handle saving

// ✅ ADDED: Computed for showing preview only when there are values
const hasAnyLinks = computed(() => {
  return facebook.value || instagram.value || twitter.value || linkedin.value || youtube.value || tiktok.value
})
</script>

<template>
  <div class="social-links-section mb-6">
    <h6 class="text-h6 mb-4">Social Links Configuration</h6>
    
    <!-- ✅ REMOVED: Form submit handler since parent handles saving -->
    <VRow>
      <!-- Facebook -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="facebook"
          label="Facebook URL"
          placeholder="https://facebook.com/yourpage"
          prepend-inner-icon="bxl-facebook"
          :error-messages="errors.facebook"
          clearable
        />
      </VCol>

      <!-- Instagram -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="instagram"
          label="Instagram URL"
          placeholder="https://instagram.com/yourprofile"
          prepend-inner-icon="bxl-instagram"
          :error-messages="errors.instagram"
          clearable
        />
      </VCol>

      <!-- Twitter -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="twitter"
          label="Twitter URL"
          placeholder="https://twitter.com/yourhandle"
          prepend-inner-icon="bxl-twitter"
          :error-messages="errors.twitter"
          clearable
        />
      </VCol>

      <!-- LinkedIn -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="linkedin"
          label="LinkedIn URL"
          placeholder="https://linkedin.com/in/yourprofile"
          prepend-inner-icon="bxl-linkedin"
          :error-messages="errors.linkedin"
          clearable
        />
      </VCol>

      <!-- YouTube -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="youtube"
          label="YouTube URL"
          placeholder="https://youtube.com/yourchannel"
          prepend-inner-icon="bxl-youtube"
          :error-messages="errors.youtube"
          clearable
        />
      </VCol>

      <!-- TikTok -->
      <VCol cols="12" md="6">
        <VTextField
          v-model="tiktok"
          label="TikTok URL"
          placeholder="https://tiktok.com/@yourhandle"
          prepend-inner-icon="bxl-tiktok"
          :error-messages="errors.tiktok"
          clearable
        />
      </VCol>

      <!-- Enable Sharing -->
      <VCol cols="12" md="6">
        <VSwitch
          v-model="enableSharing"
          label="Enable Social Sharing"
          color="primary"
          inset
        />
      </VCol>
    </VRow>

    <!-- Preview -->
    <VDivider class="my-4" />
    <div v-if="hasAnyLinks">
      <h6 class="text-h6 mb-4">Social Links Preview</h6>
      <div class="social-preview pa-4 border rounded">
        <VRow>
          <VCol cols="12" md="6" v-if="facebook">
            <VIcon icon="bxl-facebook" color="primary" class="me-2" />
            <a :href="facebook" target="_blank" rel="noopener noreferrer">{{ facebook }}</a>
          </VCol>
          <VCol cols="12" md="6" v-if="instagram">
            <VIcon icon="bxl-instagram" color="error" class="me-2" />
            <a :href="instagram" target="_blank" rel="noopener noreferrer">{{ instagram }}</a>
          </VCol>
          <VCol cols="12" md="6" v-if="twitter">
            <VIcon icon="bxl-twitter" color="info" class="me-2" />
            <a :href="twitter" target="_blank" rel="noopener noreferrer">{{ twitter }}</a>
          </VCol>
          <VCol cols="12" md="6" v-if="linkedin">
            <VIcon icon="bxl-linkedin" color="primary" class="me-2" />
            <a :href="linkedin" target="_blank" rel="noopener noreferrer">{{ linkedin }}</a>
          </VCol>
          <VCol cols="12" md="6" v-if="youtube">
            <VIcon icon="bxl-youtube" color="error" class="me-2" />
            <a :href="youtube" target="_blank" rel="noopener noreferrer">{{ youtube }}</a>
          </VCol>
          <VCol cols="12" md="6" v-if="tiktok">
            <VIcon icon="bxl-tiktok" class="me-2" />
            <a :href="tiktok" target="_blank" rel="noopener noreferrer">{{ tiktok }}</a>
          </VCol>
        </VRow>
        <div class="mt-4">
          <VChip 
            :color="enableSharing ? 'success' : 'warning'"
            size="small"
            label
          >
            {{ enableSharing ? 'Sharing Enabled' : 'Sharing Disabled' }}
          </VChip>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.social-preview {
  background-color: rgb(var(--v-theme-surface));
  min-height: 80px;
}
hr.v-divider.v-theme--light.my-4 {
    display: none!important;
}
.social-links-section.mb-6 {
    padding-bottom: 10px;
}
</style>
