import {
  Button,
  Checkbox,
  DatePicker,
  FormContainer,
  FormItem,
  Input,
  Notification,
  Tabs,
  toast,
} from '@/components/ui'
import DateTimepicker from '@/components/ui/DatePicker/DateTimepicker'
import TabContent from '@/components/ui/Tabs/TabContent'
import TabList from '@/components/ui/Tabs/TabList'
import TabNav from '@/components/ui/Tabs/TabNav'
import { UserInfoViewModel } from '@/proxy/admin'
import { getUserDetail, putUserDetail, putUserLookout } from '@/proxy/admin/identity.service'
import { useLocalization } from '@/utils/hooks/useLocalization'
import dayjs from 'dayjs'
import { Field, FieldArray, FieldProps, Form, Formik } from 'formik'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import { HiOutlineLockOpen, HiOutlineUser } from 'react-icons/hi'
import { useParams } from 'react-router-dom'

function UserDetails() {
  const { userId } = useParams()
  const { translate } = useLocalization()
  const [userDetails, setUserDetails] = useState<UserInfoViewModel>()

  const getUser = async () => {
    const { data } = await getUserDetail(userId || '')

    setUserDetails(data)
  }

  useEffect(() => {
    getUser()
  }, [])

  //translate('::AbpIdentity.Profile'),
  return userDetails ? (
    <>
      <Helmet
        titleTemplate="%s | Kurs Platform"
        title={userDetails.email}
        defaultTitle="Kurs Platform"
      ></Helmet>
      <Tabs defaultValue="user">
        <TabList>
          <TabNav value="user" icon={<HiOutlineUser />}>
            { translate('::Abp.Identity.User.UserInformation') }
          </TabNav>
          <TabNav value="lockout" icon={<HiOutlineLockOpen />}>
            { translate('::Abp.Identity.User.LockoutManagement') }
          </TabNav>
        </TabList>
        <TabContent value="user">
          <div className="mt-5">
            <Formik
              initialValues={userDetails}
              onSubmit={async (values, { resetForm, setSubmitting }) => {
                setSubmitting(true)
                await putUserDetail({ ...values })

                toast.push(
                  <Notification type="success" duration={2000}>
                    {translate('Kaydet')}
                  </Notification>,
                  {
                    placement: 'top-center',
                  },
                )

                getUser()
                setSubmitting(false)
              }}
            >
              {({ touched, errors, resetForm, isSubmitting, values }) => {
                const userRoleNames = values.userRoleNames
                const roles = values.roles

                return (
                  <Form>
                    <FormContainer size="sm">
                      <div className="w-1/2">
                        <div className="form-label mb-2">{translate('::Abp.Identity.User.UserInformation.RoleManagement')}</div>
                        <div className="border-2 rounded-lg">
                          <FieldArray name="roles">
                            {({ form, remove, push }) => (
                              <div className="grid grid-cols-4 text-center">
                                {roles && roles.length > 0
                                  ? roles.map((_, index: number) => {
                                      return (
                                        <div key={index} className="p-2">
                                          <FormItem
                                            labelClass="block text-center"
                                            className="mb-0 justify-center"
                                            label={roles[index].name}
                                          >
                                            <Field
                                              className="mr-0"
                                              name={`roles[${index}].isAssigned`}
                                              component={Checkbox}
                                            />
                                          </FormItem>
                                        </div>
                                      )
                                    })
                                  : null}
                              </div>
                            )}
                          </FieldArray>
                        </div>
                        <div className="mb-3"></div>

                        <FormItem
                          labelClass="!justify-start"
                          labelWidth="40%"
                          label={translate('::Abp.Identity.User.UserInformation.EmailAddress')}
                        >
                          <Field
                            type="text"
                            disabled
                            name="email"
                            placeholder="Email Address"
                            component={Input}
                          />
                        </FormItem>

                        <FormItem labelClass="!justify-start" labelWidth="40%" 
                          label={translate('::Abp.Identity.User.UserInformation.Name')}
                        >
                          <Field type="text" name="name" placeholder="Name" component={Input} />
                        </FormItem>

                        <FormItem labelClass="!justify-start" labelWidth="40%" 
                          label={translate('::Abp.Identity.User.UserInformation.Surname')}
                        >
                          <Field
                            type="text"
                            name="surname"
                            placeholder="Surname"
                            component={Input}
                          />
                        </FormItem>

                        <FormItem labelClass="!justify-start" labelWidth="40%" 
                          label={translate('::Abp.Identity.User.UserInformation.PhoneNumber')}
                        >
                          <Field
                            type="text"
                            name="phoneNumber"
                            placeholder="Phone Number"
                            component={Input}
                          />
                        </FormItem>

                        <FormItem
                          labelClass="!justify-start"
                          labelWidth="40%"
                          label={translate('::Abp.Identity.User.UserInformation.PasswordChangeTime')}
                        >
                          <Field name="lastPasswordChangeTime">
                            {({ field, form }: FieldProps) => (
                              <DateTimepicker
                                field={field}
                                form={form}
                                value={field.value ? dayjs(field.value).toDate() : null}
                                placeholder="Select Date"
                                onChange={(date: any) => {
                                  form.setFieldValue(
                                    field.name,
                                    date ? dayjs(date).format('YYYY-MM-DDTHH:mm:ss[Z]') : null,
                                  )
                                }}
                              />
                            )}
                          </Field>
                        </FormItem>

                        <FormItem
                          labelClass="!justify-start"
                          labelWidth="40%"
                          label={translate('::RocketUsername')}
                        >
                          <Field
                            type="text"
                            name="rocketUsername"
                            placeholder={translate('::RocketUsername')}
                            component={Input}
                          />
                        </FormItem>

                        <FormItem labelClass="!justify-start" labelWidth="40%" 
                          label={translate('::Abp.Identity.User.UserInformation.CreateTime')}
                        >
                          <Field name="creationTime">
                            {({ field, form }: FieldProps) => (
                              <Input
                                field={field}
                                form={form}
                                value={field.value ? dayjs(field.value).format('L LT') : undefined}
                                disabled
                              />
                            )}
                          </Field>
                        </FormItem>
                        <FormItem labelClass="!justify-start" labelWidth="40%" 
                          label={translate('::Abp.Identity.User.UserInformation.UpdateTime')}
                        >
                          <Field name="lastModificationTime">
                            {({ field, form }: FieldProps) => (
                              <Input
                                field={field}
                                form={form}
                                value={field.value ? dayjs(field.value).format('L LT') : undefined}
                                disabled
                              />
                            )}
                          </Field>
                        </FormItem>
                      </div>
                    </FormContainer>

                    <div>
                      <Button variant="solid" loading={isSubmitting} type="submit">
                        {isSubmitting ? translate('::SavingWithThreeDot') : translate('::Save')}
                      </Button>
                    </div>
                  </Form>
                )
              }}
            </Formik>
          </div>
        </TabContent>
        <TabContent value="lockout">
          <div className="mt-5">
            <Formik
              initialValues={userDetails}
              onSubmit={async (values, { setSubmitting }) => {
                setSubmitting(true)

                await putUserLookout({ ...values })

                toast.push(
                  <Notification type="success" duration={2000}>
                    {'Lockout bilgileri kaydedildi.'}
                  </Notification>,
                  {
                    placement: 'top-center',
                  },
                )

                getUser()

                setSubmitting(false)
              }}
            >
              {({ touched, errors, resetForm, isSubmitting, values }) => {
                const userRoleNames = values.userRoleNames
                return (
                  <Form>
                    <FormContainer size="sm">
                      <div className="w-1/2">
                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.Status')}
                        >
                          <Field name="isActive" placeholder={translate('::Abp.Identity.User.LockoutManagement.Status')} component={Checkbox} />
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.AdminVerification')}
                        >
                          <Field
                            name="isVerified"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.AdminVerification')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.EmailConfirmed')}
                        >
                          <Field
                            name="emailConfirmed"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.EmailConfirmed')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.PhoneNumberConfirmed')}
                        >
                          <Field
                            name="phoneNumberConfirmed"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.PhoneNumberConfirmed')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.TwoFactorEnabled')}
                        >
                          <Field
                            name="twoFactorEnabled"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.TwoFactorEnabled')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.LoginEndDate')}
                        >
                          <Field name="loginEndDate">
                            {({ field, form }: FieldProps) => (
                              <DatePicker
                                field={field}
                                form={form}
                                value={field.value ? dayjs(field.value).toDate() : null}
                                placeholder={translate('::Abp.Identity.User.LockoutManagement.LoginEndDate')}
                                onChange={(date) => {
                                  form.setFieldValue(
                                    field.name,
                                    date ? dayjs(date).format('YYYY-MM-DDTHH:mm:ss[Z]') : null,
                                  )
                                }}
                              />
                            )}
                          </Field>
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.AccountLockoutEnabled')}
                        >
                          <Field
                            name="lockoutEnabled"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.AccountLockoutEnabled')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.AccountLocked')}
                        >
                          <Field
                            name="lockUser"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.AccountLocked')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.AccountEndDate')}
                        >
                          <Field name="lockoutEnd">
                            {({ field, form }: FieldProps) => (
                              <DatePicker
                                field={field}
                                form={form}
                                value={field.value ? dayjs(field.value).toDate() : null}
                                placeholder={translate('::Abp.Identity.User.LockoutManagement.AccountEndDate')}
                                onChange={(date) => {
                                  form.setFieldValue(
                                    field.name,
                                    date ? dayjs(date).format('YYYY-MM-DDTHH:mm:ss[Z]') : null,
                                  )
                                }}
                              />
                            )}
                          </Field>
                        </FormItem>

                        <hr className="mb-3" />

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.ShouldChangePwOnNextLogin')}
                        >
                          <Field
                            name="shouldChangePasswordOnNextLogin"
                            placeholder={translate('::Abp.Identity.User.LockoutManagement.ShouldChangePwOnNextLogin')}
                            component={Checkbox}
                          />
                        </FormItem>

                        <FormItem
                          layout="horizontal"
                          labelClass="!justify-start"
                          labelWidth="50%"
                          label={translate('::Abp.Identity.User.LockoutManagement.AccessFailedCount')}
                        >
                          <Field type="number" name="accessFailedCount" component={Input} />
                        </FormItem>
                      </div>
                    </FormContainer>

                    <div>
                      <Button variant="solid" loading={isSubmitting} type="submit">
                        {isSubmitting ? translate('::SavingWithThreeDot') : translate('::Save')}
                      </Button>
                    </div>
                  </Form>
                )
              }}
            </Formik>
          </div>
        </TabContent>
      </Tabs>
    </>
  ) : (
    <></>
  )
}

export default UserDetails
