import React, { useEffect, useState } from 'react';
import { Row, Col, Form, Input, Modal, Select, Button, InputNumber } from "antd";
import {  SaveOutlined } from '@ant-design/icons';
import { useAuth } from "../../hooks";
import { DefaultLayout } from '../../components/layouts';
import { firestore } from '../../services/firebase';
import HttpService from "../../services/httpService";
import { doc, getDoc, updateDoc } from "firebase/firestore";

const Perfil = () => {

  const titulo = 'Editar perfil';
  const [ form ] = Form.useForm();
  const { session } = useAuth();
  const { Option } = Select;
  const [ usuario, setUsuario ] = useState(null);
  const [ guadandoCargando, setGuardandoCargando ] = useState(false);


  const onFinish = async (values) => {
    try {
      setGuardandoCargando(true)
      const { ciudad, email, facebook, genero, instagram, nombre, telefono, twitter } = values;

      let body = {
        uid: session?.uid,
        ciudad: ciudad,
        email: email?.trim(),
        facebook: facebook?.trim() || '',
        genero: genero, 
        instagram: instagram?.trim() || '',
        nombre: nombre?.trim(),
        telefono: `${telefono}`?.replace("+52", "") || "", 
        twitter: twitter?.trim() || '',
      }

      const res = await HttpService.putCF('/registro', body);
  
      if( res?.status >= 200 && res?.status <= 299 ) {
        await updateDoc(doc(firestore, "usuarios", session?.uid), body);  

        Modal.success({
          title: 'Éxito',
          content: 'Tu perfil ha sido actualizado.',
        });
      }

    } catch (error) {
      console.log('Error al registrat usuario: ', error)
      Modal.warning({
        title: 'Atención',
        content: 'Hubo un problema al guardar el usuario',
      });
    } finally {
      setGuardandoCargando(false)
    }

  };

  const onFinishFailed = () => {
    Modal.warning({
      title: 'Atención',
      content: 'Por favor revise los datos.',
      style: { marginTop: '20vh' },
    });
  };

  // Obtener usuario
  useEffect(() => {
    let mounted = true;
    if( mounted && session ) {
      try {
        setTimeout(async() => {
          const docRef = doc(firestore, "usuarios", session?.uid);
          const docSnap = await getDoc(docRef);
          setUsuario(docSnap.data());
        }, 0);
      } catch (error) {
        console.log('errror al obtener usuario: ', error);
      }
    }
  }, [session]);

  // Set form
  useEffect(() => {
    let mounted = true;
    if( mounted && session ) {
      form.setFieldsValue({
        ...usuario,
      })
    }
    return () => mounted = false;
  }, [form, session, usuario]);

  return (
    <DefaultLayout
      title={titulo}
    >
      <Form
        name="form"
        form={form}
        autoComplete="off"
        layout="vertical"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >

        {/* Nombre - Género - Correo  */}
        <Row gutter={10}>
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Nombre"
              name="nombre"
              rules={[{ required: true, message: "Requerido" }]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Género"
              name="genero"
              rules={[{ required: true, message: "Requerido" }]}
            >
              <Select
                placeholder="Seleccionar un género"
                style={{ width: '100%' }}
              >
                <Option value="m">Mujer</Option>
                <Option value="h">Hombre</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Correo electrónico"
              name="email"
              rules={[ { type: 'email', message: 'Por favor, escriba un correo electrónico válido' }, { required: true, message: 'Requerido' } ]}
            >
              <Input />
            </Form.Item>
          </Col>

        </Row>

        {/* Facebook - Twitter - Instagram  */}
        <Row gutter={10}>
       
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Facebook"
              name="facebook"
            >
              <Input />
            </Form.Item>
          </Col>

          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Twitter"
              name="twitter"
            >
              <Input />
            </Form.Item>
          </Col>

          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              label="Instagram"
              name="instagram"
            >
              <Input />
            </Form.Item>
          </Col>

        </Row>

        {/*  Celular - Rol - Ciudad */}
        <Row gutter={10}>
          
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              rules={[{ required: true, message: "Requerido" }]}
              label="Celular"
              name="telefono"
            >
              <InputNumber minLength={10} maxLength={10} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
  
          <Col
            className="gutter-row"
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Form.Item
              rules={[{ required: true, message: "Requerido" }]}
              label="Ciudad"
              name="ciudad"
            >
              <Input />
            </Form.Item>
          </Col>

        </Row>

        <Row gutter={10}>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 12 }}
            lg={{ span:  8 }}
          >
            <Button
              type="primary"
              htmlType="submit"
              icon={<SaveOutlined />}
              block
              size="large"
              loading={guadandoCargando}
            >
              Guardar
            </Button>
          </Col>
        </Row>

      </Form>
    </DefaultLayout>
  )
}

export default Perfil;