import React, { useState, useEffect } from 'react'
import useAuth from 'app/hooks/useAuth'
import { Link, Navigate, useParams } from 'react-router-dom'
import { useNavigate, useLocation } from 'react-router-dom'
import { MatxLoading, SimpleCard } from 'app/components'
import { styled } from '@mui/system'
import {
    Box,
    Button,
    Card,
    Grid,
    Icon,
    IconButton,
    Tooltip,
} from '@mui/material'
import moment from 'moment'
import BusinessSerService from 'app/services/allThingsLocals/BusinessSerService'
import { Small } from 'app/components/Typography'
import UserResponseService from 'app/services/istar/UserResponseService'
import {
    PDFDownloadLink,
    Page,
    Text,
    View,
    Document,
    StyleSheet,
    Image,
} from '@react-pdf/renderer'
import { toast } from 'react-toastify'

const Heading = styled('h6')(({ theme }) => ({
    margin: 0,
    marginTop: '4px',
    fontWeight: '500',
    fontSize: '14px',
    color: theme.palette.primary.main,
}))

const Container = styled('div')(({ theme }) => ({
    margin: '30px',
    [theme.breakpoints.down('sm')]: {
        margin: '16px',
    },
    '& .breadcrumb': {
        marginBottom: '30px',
        [theme.breakpoints.down('sm')]: {
            marginBottom: '16px',
        },
    },
}))

const StyledCard = styled(Card)(({ theme }) => ({
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '24px !important',
    background: theme.palette.background.paper,
    [theme.breakpoints.down('sm')]: {
        padding: '16px !important',
    },
}))

const ContentBox = styled('div')(({ theme }) => ({
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    '& small': {
        color: theme.palette.text.secondary,
    },
    '& .icon': {
        opacity: 0.6,
        fontSize: '44px',
        color: theme.palette.primary.main,
    },
}))

const styles = StyleSheet.create({
    page: {
        flexDirection: 'row',
        backgroundColor: '#E4E4E4',
    },
    section: {
        margin: 10,
        padding: 10,
        flexGrow: 1,
    },
})

function GuestResponse(props) {
    const { id } = useParams()
    const navigate = useNavigate()
    const location = useLocation()
    console.log('LOCATIONS:', location)
    const [data, setData] = useState()
    const [isLoading, setIsLoading] = useState(false)
    const [revenue, setRevenue] = React.useState('')
    const [error, setError] = React.useState(false)

    React.useEffect(() => {
        if (id) {
            setIsLoading(true)
            UserResponseService.customerResponses({
                guestId: id,
            })
                .then((res) => {
                    console.log('UserResponseService:', res)
                    setData(res)
                })
                .catch((err) => {
                    console.log(err?.response?.data?.error)
                    setError(true)
                    toast.error('No response found for this customer.')
                    // navigate(-1)
                })
                .finally(() => {
                    setIsLoading(false)
                })
        }
    }, [])

    if (isLoading) {
        return <MatxLoading />
    }

    return (
        <Container>
            {error && (
                <p style={{ color: 'red' }}>
                    No response found for this customer. After filling form,
                    this customer leaves the test.
                </p>
            )}
            {!error && (
                <>
                    <Grid container spacing={2}>
                        <Grid item lg={4} md={4} sm={12} xs={12}>
                            <Button
                                variant="outlined"
                                onClick={() => {
                                    console.log('LOCAION:', location)
                                    navigate(location.state.prevPath)
                                }}
                            >
                                Go Back
                            </Button>
                        </Grid>
                        <Grid
                            item
                            lg={8}
                            md={8}
                            sm={12}
                            xs={12}
                            style={{ color: 'orange' }}
                        >
                            <PDFDownloadLink
                                document={
                                    <Document>
                                        <Page size="A4" style={styles.page}>
                                            <View style={styles.section}>
                                                {data && (
                                                    <View>
                                                        <Text>
                                                            User name:{' '}
                                                            {data?.guest
                                                                ?.firstName +
                                                                ' ' +
                                                                data?.guest
                                                                    ?.lastName}
                                                        </Text>
                                                        {data?.responses
                                                            ?.length > 0 &&
                                                            data.responses.map(
                                                                (da) => (
                                                                    <View>
                                                                        <Text>
                                                                            <p>
                                                                                Question:{' '}
                                                                                <b>
                                                                                    {
                                                                                        da
                                                                                            ?.question
                                                                                            ?.question
                                                                                    }
                                                                                </b>
                                                                            </p>
                                                                        </Text>
                                                                        <Text>
                                                                            <p>
                                                                                Answer:{' '}
                                                                                <b>
                                                                                    {
                                                                                        da?.answer
                                                                                    }
                                                                                </b>
                                                                            </p>
                                                                        </Text>
                                                                    </View>
                                                                )
                                                            )}
                                                        {data?.testGraph && (
                                                            <Image
                                                                src={
                                                                    data?.testGraph
                                                                }
                                                                alt="Test Graph"
                                                                width="500px"
                                                                height="500px"
                                                            />
                                                        )}
                                                    </View>
                                                )}
                                            </View>
                                        </Page>
                                    </Document>
                                }
                                fileName="test.pdf"
                            >
                                {({ blob, url, loading, error }) =>
                                    loading
                                        ? 'Loading document...'
                                        : 'Download result!'
                                }
                            </PDFDownloadLink>
                        </Grid>
                    </Grid>
                    {data && data.responses.length > 0 && (
                        <SimpleCard title={`User Responses`}>
                            {data.responses.map((da, index) => (
                                <SimpleCard key={index}>
                                    <p>
                                        Question:{' '}
                                        <b>{da?.question?.question}</b>
                                    </p>
                                    <p>
                                        Answer: <b>{da?.answer}</b>
                                    </p>
                                </SimpleCard>
                            ))}
                        </SimpleCard>
                    )}
                </>
            )}
        </Container>
    )
}
export default GuestResponse
