import { useQuery } from '@tanstack/react-query'
import { Container, Stack, Title, Text, SimpleGrid, Group, Button, TextInput, Loader } from '@mantine/core'
import { useDebouncedValue } from '@mantine/hooks'
import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { TbPlus, TbSearch } from 'react-icons/tb'
import { DashboardLayout } from '@/frontend/components/DashboardLayout'
import { AppCard } from '@/frontend/components/AppCard'

export const Route = createFileRoute('/apps/')({
  component: AppsPage,
})

function AppsPage() {
  const [search, setSearch] = useState('')
  const [debouncedSearch] = useDebouncedValue(search, 300)

  const { data: apps, isLoading } = useQuery({
    queryKey: ['apps', debouncedSearch],
    queryFn: () => fetch(`/api/apps?search=${encodeURIComponent(debouncedSearch)}`).then((r) => r.json()),
  })

  return (
    <DashboardLayout>
      <Container size="xl" py="lg">
        <Stack gap="xl">
          <Group justify="space-between" align="flex-end">
            <Stack gap={0}>
              <Title order={2} className="gradient-text">Applications</Title>
              <Text size="sm" c="dimmed">Manage and monitor all your mobile applications from one place.</Text>
            </Stack>
            {/* <Button
              variant="gradient"
              gradient={{ from: '#2563EB', to: '#7C3AED', deg: 135 }}
              leftSection={<TbPlus size={18} />}
              radius="md"
            >
              Add New Application
            </Button> */}
          </Group>

          <Group>
            <TextInput
              placeholder="Search applications..."
              leftSection={<TbSearch size={16} />}
              style={{ flex: 1 }}
              radius="md"
              value={search}
              onChange={(e) => setSearch(e.currentTarget.value)}
            />
          </Group>

          {isLoading ? (
            <Loader size="xl" type="dots" mx="auto" mt="xl" />
          ) : (
            <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="lg">
              {apps?.map((app: any) => (
                <AppCard key={app.id} {...app} />
              ))}
            </SimpleGrid>
          )}
        </Stack>
      </Container>
    </DashboardLayout>
  )
}
