'use client'

import {
  Box,
  Container,
  Heading,
  Text,
  VStack,
  HStack,
  SimpleGrid,
  FormControl,
  FormLabel,
  Input,
  Textarea,
  Button,
  useColorModeValue,
  Icon,
  Flex,
  useToast,
  Select,
} from '@chakra-ui/react'
import { FiMail, FiPhone, FiMapPin, FiClock } from 'react-icons/fi'
import { useState } from 'react'

interface ContactFormData {
  name: string
  lastname: string
  email: string
  phone: string
  message: string
}

const ContactInfo = ({ icon, title, content, href }: any) => {
  const Component = href ? 'a' : 'div'
  const linkProps = href ? { href } : {}

  return (
    <Box
      as={Component}
      {...linkProps}
      bg={useColorModeValue('white', 'gray.800')}
      rounded="2xl"
      p={6}
      shadow="lg"
      border="1px"
      borderColor={useColorModeValue('gray.100', 'gray.700')}
      _hover={{
        transform: 'translateY(-2px)',
        shadow: 'xl',
        borderColor: useColorModeValue('brand.200', 'brand.500')
      }}
      transition="all 0.3s ease"
      cursor={href ? 'pointer' : 'default'}
    >
      <VStack spacing={4} align="center">
        <Box
          p={3}
          bg={useColorModeValue('brand.50', 'brand.900')}
          rounded="xl"
        >
          <Icon as={icon} w={6} h={6} color="brand.500" />
        </Box>
        <VStack spacing={1} textAlign="center">
          <Text
            fontWeight={600}
            color={useColorModeValue('gray.700', 'white')}
            fontSize="lg"
          >
            {title}
          </Text>
          <Text
            color={useColorModeValue('gray.600', 'gray.400')}
            fontSize="sm"
          >
            {content}
          </Text>
        </VStack>
      </VStack>
    </Box>
  )
}

export default function ContactForm() {
  const [formData, setFormData] = useState<ContactFormData>({
    name: '',
    lastname: '',
    email: '',
    phone: '',
    message: ''
  })
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<any>({})
  const [responseMessage, setResponseMessage] = useState<any>(null)
  const toast = useToast()

  const validate = () => {
    const errors: any = {}

    if (!formData.name.trim()) {
      errors.name = 'Ime je obavezno'
    }

    if (!formData.lastname.trim()) {
      errors.lastname = 'Prezime je obavezno'
    }

    if (!formData.email.trim()) {
      errors.email = 'Email je obavezan'
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      errors.email = 'Email format nije valjan'
    }

    if (!formData.phone.trim()) {
      errors.phone = 'Telefon je obavezan'
    }

    if (!formData.message.trim()) {
      errors.message = 'Poruka je obavezna'
    }

    return errors
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    setIsLoading(true);

    const validationErrors = validate();
    if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        setIsLoading(false);
        return;
    }

    setErrors({});

    // Send data to your backend API
    try {
        const res = await fetch("/api/contact", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(formData),
        });

        const responseData = await res.json();

        if (!res.ok) {
            throw new Error(responseData.error || responseData.message || "Failed to send message");
        }

        setResponseMessage({
            title: "Poruka je uspešno poslata!",
            description: "Hvala na interesovanju,<br />Aktiv tim će Vas kontaktirati uskoro.",
            status: "success",
        });

        toast({
          title: 'Poruka je uspešno poslata!',
          description: 'Hvala na interesovanju, Aktiv tim će Vas kontaktirati uskoro.',
          status: 'success',
          duration: 5000,
          isClosable: true,
        })

        setFormData({ name: "", phone: "", email: "", message: "", lastname: "" });
    } catch (error) {
        console.error('Contact form error:', error);

        const errorMessage = error instanceof Error ? error.message : "Unknown error";

        setResponseMessage({
            title: "Poruka nije poslata!",
            description: `Greška: ${errorMessage}\nMožete nas kontaktirati putem telefona: +381 60 62 62 844`,
            status: "error",
        });

        toast({
          title: 'Poruka nije poslata!',
          description: `Greška: ${errorMessage}. Možete nas kontaktirati putem telefona: +381 60 62 62 844`,
          status: 'error',
          duration: 7000,
          isClosable: true,
        })
    } finally {
        setIsLoading(false);
    }
  }

  return (
    <Box pt={20} pb={20}>
      <Container maxW="7xl">
        {/* Header Section */}
        <VStack spacing={8} mb={16} textAlign="center">
          <Heading
            fontSize={{ base: '3xl', md: '4xl', lg: '5xl' }}
            fontWeight={700}
            color={useColorModeValue('gray.700', 'white')}
            lineHeight="shorter"
          >
            Kontaktirajte{' '}
            <Text as="span" color="brand.500">
              nas danas
            </Text>
          </Heading>
          <Text
            fontSize={{ base: 'lg', md: 'xl' }}
            color={useColorModeValue('gray.600', 'gray.400')}
            maxW="3xl"
            lineHeight="tall"
          >
            Imamo tim stručnjaka spreman da odgovori na sva vaša pitanja i pomogne vam
            da odaberete najbolje rešenje za vaše poslovanje.
          </Text>
        </VStack>

        {/* Contact Info Cards */}
        <SimpleGrid columns={{ base: 1, md: 2, lg: 4 }} spacing={6} mb={16}>
          <ContactInfo
            icon={FiMail}
            title="Email"
            content="info@aktiv.rs"
            href="mailto:info@aktiv.rs"
          />
          <ContactInfo
            icon={FiPhone}
            title="Telefon"
            content="+381 060 62 62 844"
            href="tel:+381606262677"
          />
          <ContactInfo
            icon={FiMapPin}
            title="Adresa"
            content="Niš, Srbija"
          />
          <ContactInfo
            icon={FiClock}
            title="Radno vreme"
            content="Pon-Pet: 09:00-17:00"
          />
        </SimpleGrid>

        {/* Contact Form */}
        <SimpleGrid columns={{ base: 1, lg: 2 }} spacing={16} alignItems="start">
          {/* Form */}
          <Box
            bg={useColorModeValue('white', 'gray.800')}
            rounded="3xl"
            p={8}
            shadow="xl"
            border="1px"
            borderColor={useColorModeValue('gray.100', 'gray.700')}
          >
            <VStack spacing={6} as="form" onSubmit={handleSubmit}>
              <VStack spacing={2} align="start" w="full">
                <Heading size="lg" color={useColorModeValue('gray.700', 'white')}>
                  Pošaljite nam poruku
                </Heading>
                <Text color={useColorModeValue('gray.600', 'gray.400')}>
                  Popunite formu i odgovoriću vam u najkraćem roku
                </Text>
              </VStack>

              <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4} w="full">
                <FormControl isRequired>
                  <FormLabel color={useColorModeValue('gray.700', 'gray.300')}>
                    Ime
                  </FormLabel>
                  <Input
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder="Vaše ime"
                    size="lg"
                    rounded="xl"
                    border="1px"
                    borderColor={useColorModeValue('gray.300', 'gray.600')}
                    isInvalid={!!errors.name}
                    _focus={{
                      borderColor: 'brand.500',
                      boxShadow: '0 0 0 1px brand.500'
                    }}
                  />
                  {errors.name && <Text color="red.500" fontSize="sm" mt={1}>{errors.name}</Text>}
                </FormControl>

                <FormControl isRequired>
                  <FormLabel color={useColorModeValue('gray.700', 'gray.300')}>
                    Prezime
                  </FormLabel>
                  <Input
                    name="lastname"
                    value={formData.lastname}
                    onChange={handleChange}
                    placeholder="Vaše prezime"
                    size="lg"
                    rounded="xl"
                    border="1px"
                    borderColor={useColorModeValue('gray.300', 'gray.600')}
                    isInvalid={!!errors.lastname}
                    _focus={{
                      borderColor: 'brand.500',
                      boxShadow: '0 0 0 1px brand.500'
                    }}
                  />
                  {errors.lastname && <Text color="red.500" fontSize="sm" mt={1}>{errors.lastname}</Text>}
                </FormControl>
              </SimpleGrid>

              <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4} w="full">
                <FormControl isRequired>
                  <FormLabel color={useColorModeValue('gray.700', 'gray.300')}>
                    Email adresa
                  </FormLabel>
                  <Input
                    name="email"
                    type="email"
                    value={formData.email}
                    onChange={handleChange}
                    placeholder="vaš@email.com"
                    size="lg"
                    rounded="xl"
                    border="1px"
                    borderColor={useColorModeValue('gray.300', 'gray.600')}
                    isInvalid={!!errors.email}
                    _focus={{
                      borderColor: 'brand.500',
                      boxShadow: '0 0 0 1px brand.500'
                    }}
                  />
                  {errors.email && <Text color="red.500" fontSize="sm" mt={1}>{errors.email}</Text>}
                </FormControl>

                <FormControl isRequired>
                  <FormLabel color={useColorModeValue('gray.700', 'gray.300')}>
                    Telefon
                  </FormLabel>
                  <Input
                    name="phone"
                    value={formData.phone}
                    onChange={handleChange}
                    placeholder="+381 XX XXX XXXX"
                    size="lg"
                    rounded="xl"
                    border="1px"
                    borderColor={useColorModeValue('gray.300', 'gray.600')}
                    isInvalid={!!errors.phone}
                    _focus={{
                      borderColor: 'brand.500',
                      boxShadow: '0 0 0 1px brand.500'
                    }}
                  />
                  {errors.phone && <Text color="red.500" fontSize="sm" mt={1}>{errors.phone}</Text>}
                </FormControl>
              </SimpleGrid>

              <FormControl isRequired>
                <FormLabel color={useColorModeValue('gray.700', 'gray.300')}>
                  Poruka
                </FormLabel>
                <Textarea
                  name="message"
                  value={formData.message}
                  onChange={handleChange}
                  placeholder="Opišite vaše pitanje ili zahtev..."
                  rows={6}
                  resize="vertical"
                  rounded="xl"
                  border="1px"
                  borderColor={useColorModeValue('gray.300', 'gray.600')}
                  isInvalid={!!errors.message}
                  _focus={{
                    borderColor: 'brand.500',
                    boxShadow: '0 0 0 1px brand.500'
                  }}
                />
                {errors.message && <Text color="red.500" fontSize="sm" mt={1}>{errors.message}</Text>}
              </FormControl>

              <Button
                type="submit"
                colorScheme="brand"
                size="lg"
                w="full"
                rounded="xl"
                isLoading={isLoading}
                loadingText="Šalje se..."
                _hover={{
                  transform: 'translateY(-2px)',
                  boxShadow: 'lg'
                }}
                py={6}
                fontSize="md"
                fontWeight={600}
              >
                Pošaljite poruku
              </Button>
            </VStack>
          </Box>

          {/* Additional Info */}
          <VStack spacing={8} align="start">
            <Box>
              <Heading
                size="lg"
                mb={4}
                color={useColorModeValue('gray.700', 'white')}
              >
                Zašto da nas kontaktirate?
              </Heading>
              <VStack spacing={4} align="start">
                <HStack spacing={3}>
                  <Box w={2} h={2} bg="brand.500" rounded="full" />
                  <Text color={useColorModeValue('gray.600', 'gray.400')}>
                    Besplatna konsultacija i demo programa
                  </Text>
                </HStack>
                <HStack spacing={3}>
                  <Box w={2} h={2} bg="brand.500" rounded="full" />
                  <Text color={useColorModeValue('gray.600', 'gray.400')}>
                    Personalizovana ponuda za vaše potrebe
                  </Text>
                </HStack>
                <HStack spacing={3}>
                  <Box w={2} h={2} bg="brand.500" rounded="full" />
                  <Text color={useColorModeValue('gray.600', 'gray.400')}>
                    Pomoć pri migraciji sa postojećeg sistema
                  </Text>
                </HStack>
                <HStack spacing={3}>
                  <Box w={2} h={2} bg="brand.500" rounded="full" />
                  <Text color={useColorModeValue('gray.600', 'gray.400')}>
                    Obuka tima za korišćenje programa
                  </Text>
                </HStack>
              </VStack>
            </Box>

            <Box
              bg={useColorModeValue('brand.50', 'gray.700')}
              rounded="2xl"
              p={6}
              border="1px"
              borderColor={useColorModeValue('brand.100', 'gray.600')}
            >
              <VStack spacing={3} align="start">
                <Heading
                  size="md"
                  color={useColorModeValue('gray.700', 'white')}
                >
                  Brz odgovor garantovan
                </Heading>
                <Text
                  color={useColorModeValue('gray.600', 'gray.300')}
                  fontSize="sm"
                >
                  Odgovaramo na sve upite u roku od 24 sata. Za hitne zahteve,
                  kontaktirajte nas direktno na telefon.
                </Text>
              </VStack>
            </Box>

            <Box
              bg={useColorModeValue('white', 'gray.800')}
              rounded="2xl"
              p={6}
              shadow="lg"
              border="1px"
              borderColor={useColorModeValue('gray.100', 'gray.700')}
            >
              <VStack spacing={3} align="start">
                <Heading
                  size="md"
                  color={useColorModeValue('gray.700', 'white')}
                >
                  Potreban je demo?
                </Heading>
                <Text
                  color={useColorModeValue('gray.600', 'gray.300')}
                  fontSize="sm"
                  mb={2}
                >
                  Zakažite personalizovanu prezentaciju programa prilagođenu
                  vašim potrebama.
                </Text>
                <Button
                  colorScheme="brand"
                  variant="outline"
                  size="sm"
                  rounded="lg"
                >
                  Zakaži demo
                </Button>
              </VStack>
            </Box>
          </VStack>
        </SimpleGrid>
      </Container>
    </Box>
  )
}