'use client'

import React from 'react'
import { useForm } from '@/app/hooks/useForm'
import { getSourceFromPath } from '@/lib/utils/pathMapper'
import { usePathname } from 'next/navigation'
import TextInput from './ui/TextInput'
import TextAreaInput from './ui/TextAreaInput'
import PhoneInput from './ui/PhoneInput'
import showToast from './ui/Toast'
import Button from './ui/Button'
import { sendMessage } from '@/lib/telegram/sendMessage'
import useUserStore from '@/app/store/userStore'

const validationRules = {
  source: { required: true },
  name: { required: true },
  phone_number: { required: true },
  message: { required: true },
}

const ContactUs = () => {
  const pathname = usePathname()
  const source = getSourceFromPath(pathname)

  const { user } = useUserStore()
  const { values, handleChange, handleSubmit, resetField } = useForm(
    {
      source: source,
      name: user?.name || '',
      phone_number: user?.phone_number || '',
      message: '',
    },
    validationRules,
    async (values) => {
      try {
        await sendMessage(values)

        showToast({
          type: 'success',
          message: 'Ваше сообщение отправлено!',
        })

        resetField('message')
      } catch {
        showToast({ type: 'error', message: 'Ой, что то пошло не так..' })
      }
    }
  )

  return (
    <div className="rounded-2xl shadow overflow-hidden">
      <div className="p-6 bg-white sm:p-8">
        <div className="space-y-4">
          <h2 className="text-2xl">Хотели бы связаться с нами?</h2>
          <form className="space-y-4" onSubmit={handleSubmit}>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 h-full">
              <div className="space-y-4 h-full flex flex-col">
                <TextInput
                  label="Ваше имя"
                  value={values.name}
                  handleChange={handleChange}
                  placeholder="Имя"
                  name="name"
                  style="register"
                />
                <PhoneInput
                  value={values.phone_number}
                  handleChange={handleChange}
                  operatorsInfo={false}
                />
              </div>
              <TextAreaInput
                value={values.message}
                handleChange={handleChange}
                height={145}
                label="Чем бы Вы хотели с нами поделиться?"
                name="message"
                placeholder="Что угодно - от предложений до жалоб, мы всегда рады!"
              />
            </div>
            <Button
              text="Отправить"
              className="text-sm font-semibold py-4 px-6 bg-black text-white flex items-center justify-center w-full rounded-2xl whitespace-nowrap"
              type="submit"
            />
          </form>
        </div>
      </div>
    </div>
  )
}

export default ContactUs
