import { useState, useEffect } from 'react';
import { 
  Container, 
  Title, 
  Text, 
  Table, 
  Badge, 
  Group, 
  Alert,
  Loader,
  Center,
  Stack,
  TextInput,
  Select,
  Pagination,
  Code,
  Tooltip
} from '@mantine/core';
import { IconAlertCircle, IconFileText, IconSearch } from '@tabler/icons-react';
import { apiClient } from '../lib/api';
import type { EventLog } from '../types';

export default function EventLogsPage() {
  const [logs, setLogs] = useState<EventLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  useEffect(() => {
    loadLogs();
  }, []);

  const loadLogs = async () => {
    try {
      setLoading(true);
      const data = await apiClient.getEventLogs({ limit: 1000, offset: 0 });
      setLogs(data || []);
      setError(null);
    } catch (err) {
      setError('Failed to load event logs');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const getSuccessColor = (success: boolean) => {
    return success ? 'green' : 'red';
  };

  // Filter logs
  const filteredLogs = logs.filter((log) => {
    const matchesSearch = !searchQuery || 
      log.event_type.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.action?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.entity_type?.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesType = !filterType || log.event_type === filterType;
    
    return matchesSearch && matchesType;
  });

  // Paginate
  const totalPages = Math.ceil(filteredLogs.length / itemsPerPage);
  const paginatedLogs = filteredLogs.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // Get unique event types for filter
  const eventTypes = Array.from(new Set(logs.map(log => log.event_type)));

  if (loading) {
    return (
      <Container size="xl" py="xl">
        <Center h={400}>
          <Loader size="lg" />
        </Center>
      </Container>
    );
  }

  if (error) {
    return (
      <Container size="xl" py="xl">
        <Alert icon={<IconAlertCircle size={16} />} title="Error" color="red" mb="md">
          {error}
        </Alert>
      </Container>
    );
  }

  return (
    <Container size="xl" py="xl">
      <Group justify="space-between" mb="xl">
        <div>
          <Title order={2}>Event Logs</Title>
          <Text c="dimmed" size="sm">System activity and audit trail</Text>
        </div>
      </Group>

      <Group mb="md">
        <TextInput
          placeholder="Search logs..."
          leftSection={<IconSearch size={16} />}
          value={searchQuery}
          onChange={(e) => {
            setSearchQuery(e.target.value);
            setCurrentPage(1);
          }}
          style={{ flex: 1 }}
        />
        <Select
          placeholder="Filter by type"
          data={[
            { value: '', label: 'All Types' },
            ...eventTypes.map(type => ({ value: type, label: type }))
          ]}
          value={filterType}
          onChange={(value) => {
            setFilterType(value);
            setCurrentPage(1);
          }}
          clearable
          style={{ minWidth: 200 }}
        />
      </Group>

      <Table highlightOnHover withTableBorder withColumnBorders>
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Timestamp</Table.Th>
            <Table.Th>Event Type</Table.Th>
            <Table.Th>Action</Table.Th>
            <Table.Th>Entity</Table.Th>
            <Table.Th>User</Table.Th>
            <Table.Th>Status</Table.Th>
            <Table.Th>Details</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {paginatedLogs.length === 0 ? (
            <Table.Tr>
              <Table.Td colSpan={7}>
                <Center h={200}>
                  <Stack align="center">
                    <IconFileText size={48} stroke={1.5} color="gray" />
                    <Text c="dimmed">
                      {searchQuery || filterType ? 'No matching logs found' : 'No event logs available'}
                    </Text>
                  </Stack>
                </Center>
              </Table.Td>
            </Table.Tr>
          ) : (
            paginatedLogs.map((log) => {
              let entityDisplay = log.entity_type || '-';
              if (log.entity_id) {
                entityDisplay += ` (${log.entity_id.substring(0, 8)}...)`;
              }

              return (
                <Table.Tr key={log.id}>
                  <Table.Td>
                    <Text size="sm">
                      {new Date(log.created_at).toLocaleString()}
                    </Text>
                  </Table.Td>
                  <Table.Td>
                    <Badge variant="light">
                      {log.event_type}
                    </Badge>
                  </Table.Td>
                  <Table.Td>
                    <Text size="sm">{log.action || '-'}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Text size="sm">{entityDisplay}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Text size="sm">{log.user_id ? `User ${log.user_id.substring(0, 8)}...` : '-'}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Badge color={getSuccessColor(log.success)} variant="light">
                      {log.success ? 'Success' : 'Failed'}
                    </Badge>
                  </Table.Td>
                  <Table.Td>
                    {log.error ? (
                      <Tooltip label={log.error} position="left" multiline w={300}>
                        <Code color="red" style={{ cursor: 'help' }}>Error</Code>
                      </Tooltip>
                    ) : log.data ? (
                      <Tooltip label={log.data} position="left" multiline w={300}>
                        <Code style={{ cursor: 'help' }}>View Data</Code>
                      </Tooltip>
                    ) : (
                      <Text size="sm" c="dimmed">-</Text>
                    )}
                  </Table.Td>
                </Table.Tr>
              );
            })
          )}
        </Table.Tbody>
      </Table>

      {totalPages > 1 && (
        <Group justify="center" mt="xl">
          <Pagination 
            total={totalPages} 
            value={currentPage} 
            onChange={setCurrentPage}
          />
        </Group>
      )}

      <Group justify="space-between" mt="md">
        <Text size="sm" c="dimmed">
          Showing {paginatedLogs.length} of {filteredLogs.length} logs
        </Text>
        {(searchQuery || filterType) && (
          <Text size="sm" c="dimmed">
            (filtered from {logs.length} total)
          </Text>
        )}
      </Group>
    </Container>
  );
}
