import { useState } from 'react'
import useSWR from 'swr'
import {
  Badge,
  Group,
  Stack,
  Text,
  Title,
  Paper,
  Table,
  TextInput,
  ActionIcon,
  Avatar,
  Code,
  Button,
  Box,
  Pagination,
  ThemeIcon,
  ScrollArea,
  Container,
} from '@mantine/core'
import { useMediaQuery } from '@mantine/hooks'
import { createFileRoute, useParams } from '@tanstack/react-router'
import {
  TbSearch,
  TbDownload,
  TbX,
  TbHistory,
  TbCalendar,
  TbUser,
  TbHome2
} from 'react-icons/tb'
import { API_URLS } from '../config/api'

export const Route = createFileRoute('/apps/$appId/logs')({
  component: AppLogsPage,
})

interface LogEntry {
  id: string
  createdAt: string
  action: string
  desc: string
  username: string
  village: string
}

const fetcher = (url: string) => fetch(url).then((res) => res.json())

function AppLogsPage() {
  const { appId } = useParams({ from: '/apps/$appId/logs' })
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [searchQuery, setSearchQuery] = useState('')

  const isDesaPlus = appId === 'desa-plus'
  const isMobile = useMediaQuery('(max-width: 768px)')

  const apiUrl = isDesaPlus ? API_URLS.getLogsAllVillages(page, searchQuery) : null
  const { data: response, error, isLoading } = useSWR(apiUrl, fetcher)
  const logs: LogEntry[] = response?.data?.log || []

  const handleSearchChange = (val: string) => {
    setSearch(val)
    if (val.length >= 3 || val.length === 0) {
      setSearchQuery(val)
      setPage(1)
    }
  }

  const handleClearSearch = () => {
    setSearch('')
    setSearchQuery('')
    setPage(1)
  }

  const getActionColor = (action: string) => {
    const a = action.toUpperCase()
    if (a === 'LOGIN') return 'blue'
    if (a === 'LOGOUT') return 'gray'
    if (a === 'CREATE') return 'teal'
    if (a === 'UPDATE') return 'orange'
    if (a === 'DELETE') return 'red'
    return 'brand-blue'
  }

  if (!isDesaPlus) {
    return (
      <Container size="xl" py="xl">
        <Paper p="xl" radius="xl" className="glass" style={{ textAlign: 'center' }}>
          <TbHistory size={48} color="gray" opacity={0.5} />
          <Title order={3} mt="md">Activity Logs</Title>
          <Text c="dimmed">This feature is currently customized for Desa+. Other apps coming soon.</Text>
        </Paper>
      </Container>
    )
  }

  return (
    <Stack gap="xl" py="md">
      <Paper withBorder radius="2xl" p="xl" className="glass" style={{ borderLeft: '6px solid #7C3AED' }}>
        <Stack gap="lg">
          <Group justify="space-between" align="center">
            <Stack gap={4}>
              <Group gap="xs">
                <ThemeIcon variant="light" color="violet" size="lg" radius="md">
                  <TbHistory size={22} />
                </ThemeIcon>
                <Title order={3}>Activity Logs</Title>
              </Group>
              <Text size="sm" c="dimmed" ml={40}>
                {isLoading ? 'Loading logs...' : `Auditing ${response?.data?.total || 0} events across all villages`}
              </Text>
            </Stack>
            <Button
              variant="light"
              color="gray"
              leftSection={<TbDownload size={18} />}
              radius="md"
              size="md"
            >
              Export
            </Button>
          </Group>

          <TextInput
            placeholder="Search action or village..."
            leftSection={<TbSearch size={18} />}
            size="md"
            rightSection={
              search ? (
                <ActionIcon variant="transparent" color="gray" onClick={handleClearSearch} size="md">
                  <TbX size={18} />
                </ActionIcon>
              ) : null
            }
            value={search}
            onChange={(e) => handleSearchChange(e.currentTarget.value)}
            radius="md"
            style={{ maxWidth: 500 }}
            ml={40}
          />
        </Stack>
      </Paper>

      {isLoading ? (
        <Paper p="xl" radius="xl" withBorder style={{ textAlign: 'center' }}>
          <Text c="dimmed">Fetching activity logs...</Text>
        </Paper>
      ) : error ? (
        <Paper p="xl" radius="xl" withBorder style={{ textAlign: 'center' }}>
          <Text c="red">Failed to load logs from API.</Text>
        </Paper>
      ) : logs.length === 0 ? (
        <Paper p="xl" radius="xl" withBorder style={{ textAlign: 'center' }}>
          <TbHistory size={40} color="gray" opacity={0.4} />
          <Text c="dimmed" mt="md">No activity found for this search.</Text>
        </Paper>
      ) : (
        <Paper withBorder radius="2xl" className="glass" style={{ overflow: 'hidden' }}>
          <ScrollArea h={isMobile ? undefined : 'auto'} offsetScrollbars>
            <Table 
              verticalSpacing="lg" 
              horizontalSpacing="xl" 
              highlightOnHover 
              withColumnBorders={false}
              style={{ 
                tableLayout: isMobile ? 'auto' : 'fixed', 
                width: '100%',
                minWidth: isMobile ? 900 : 'unset'
              }}
            >
              <Table.Thead bg="rgba(0,0,0,0.05)">
                <Table.Tr>
                  <Table.Th style={{ border: 'none', width: isMobile ? undefined : '18%' }}>Timestamp</Table.Th>
                  <Table.Th style={{ border: 'none', width: isMobile ? undefined : '20%' }}>User & Village</Table.Th>
                  <Table.Th style={{ border: 'none', width: isMobile ? undefined : '12%' }}>Action</Table.Th>
                  <Table.Th style={{ border: 'none', width: isMobile ? undefined : '50%' }}>Description</Table.Th>
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {logs.map((log) => (
                  <Table.Tr key={log.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                    <Table.Td>
                      <Group gap={8} wrap="nowrap" align="flex-start">
                        <ThemeIcon variant="transparent" color="gray" size="sm">
                          <TbCalendar size={14} />
                        </ThemeIcon>
                        <Stack gap={0}>
                          <Text size="xs" fw={700} style={{ color: 'var(--mantine-color-white)' }}>
                            {log.createdAt.split(' ').slice(1).join(' ')}
                          </Text>
                          <Text size="xs" c="dimmed">
                            {log.createdAt.split(' ')[0]}
                          </Text>
                        </Stack>
                      </Group>
                    </Table.Td>
                    <Table.Td>
                      <Stack gap={4} style={{ overflow: 'hidden' }}>
                        <Group gap={8} wrap="nowrap">
                          <Avatar size="xs" radius="xl" color="brand-blue" variant="light">
                            {log.username.charAt(0)}
                          </Avatar>
                          <Text size="xs" fw={700} truncate="end">{log.username}</Text>
                        </Group>
                        <Group gap={8} wrap="nowrap">
                          <TbHome2 size={12} color="gray" />
                          <Text size="xs" c="dimmed" truncate="end">{log.village}</Text>
                        </Group>
                      </Stack>
                    </Table.Td>
                    <Table.Td>
                      <Badge 
                        variant="dot" 
                        color={getActionColor(log.action)} 
                        radius="sm" 
                        size="xs"
                        styles={{ root: { fontWeight: 800 } }}
                      >
                        {log.action}
                      </Badge>
                    </Table.Td>
                    <Table.Td>
                      <Code color="brand-blue" bg="rgba(37, 99, 235, 0.05)" fw={600} style={{ fontSize: '11px', display: 'block', whiteSpace: 'normal' }}>
                        {log.desc}
                      </Code>
                    </Table.Td>
                  </Table.Tr>
                ))}
              </Table.Tbody>
            </Table>
          </ScrollArea>
        </Paper>
      )}

      {!isLoading && !error && response?.data?.totalPage > 0 && (
        <Group justify="center" mt="xl">
          <Pagination
            value={page}
            onChange={setPage}
            total={response.data.totalPage}
            radius="md"
            withEdges={false}
            siblings={1}
            boundaries={1}
          />
        </Group>
      )}
    </Stack>
  )
}
