import { useState, useEffect } from 'react';
import { 
  Container, 
  Title, 
  Text, 
  Button, 
  Table, 
  Badge, 
  Group, 
  Modal,
  TextInput,
  Select,
  Textarea,
  NumberInput,
  Checkbox,
  Stack,
  Alert,
  Loader,
  Center,
  ActionIcon,
  Code,
  Tooltip
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconEdit, IconTrash, IconPlus, IconAlertCircle, IconWebhook } from '@tabler/icons-react';
import { listRecords, createRecord, updateRecord, deleteRecord } from '../lib/query';
import type { Hook } from '../types';

function sortHooksAlphabetically(hooks: Hook[]): Hook[] {
  return [...hooks].sort((a, b) =>
    a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
  );
}

export default function HooksPage() {
  const [hooks, setHooks] = useState<Hook[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [opened, { open, close }] = useDisclosure(false);
  const [editingHook, setEditingHook] = useState<Hook | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    url: '',
    method: 'POST',
    description: '',
    secret: '',
    headers: '',
    events: '',
    retry_count: 3,
    timeout: 30,
    active: true
  });

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

  const loadHooks = async () => {
    try {
      setLoading(true);
      const data = await listRecords<Hook>('hooks');
      setHooks(sortHooksAlphabetically(data || []));
      setError(null);
    } catch (err) {
      setError('Failed to load hooks');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingHook(null);
    setFormData({
      name: '',
      url: '',
      method: 'POST',
      description: '',
      secret: '',
      headers: '',
      events: '',
      retry_count: 3,
      timeout: 30,
      active: true
    });
    open();
  };

  const handleEdit = (hook: Hook) => {
    setEditingHook(hook);
    setFormData({
      name: hook.name,
      url: hook.url,
      method: hook.method,
      description: hook.description || '',
      secret: hook.secret || '',
      headers: hook.headers || '',
      events: hook.events || '',
      retry_count: hook.retry_count,
      timeout: hook.timeout,
      active: hook.active
    });
    open();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this hook?')) {
      return;
    }
    try {
      await deleteRecord('hooks', id);
      notifications.show({
        title: 'Success',
        message: 'Hook deleted successfully',
        color: 'green',
      });
      await loadHooks();
    } catch (err) {
      notifications.show({
        title: 'Error',
        message: 'Failed to delete hook',
        color: 'red',
      });
      console.error(err);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate URL
    try {
      new URL(formData.url);
    } catch {
      notifications.show({
        title: 'Error',
        message: 'Please enter a valid URL',
        color: 'red',
      });
      return;
    }

    // Validate JSON fields if not empty
    if (formData.headers) {
      try {
        JSON.parse(formData.headers);
      } catch {
        notifications.show({
          title: 'Error',
          message: 'Headers must be valid JSON',
          color: 'red',
        });
        return;
      }
    }
    if (formData.events) {
      try {
        JSON.parse(formData.events);
      } catch {
        notifications.show({
          title: 'Error',
          message: 'Events must be valid JSON',
          color: 'red',
        });
        return;
      }
    }

    try {
      if (editingHook) {
        await updateRecord('hooks', editingHook.id, formData);
        notifications.show({
          title: 'Success',
          message: 'Hook updated successfully',
          color: 'green',
        });
      } else {
        await createRecord('hooks', formData);
        notifications.show({
          title: 'Success',
          message: 'Hook created successfully',
          color: 'green',
        });
      }
      close();
      await loadHooks();
    } catch (err) {
      notifications.show({
        title: 'Error',
        message: `Failed to ${editingHook ? 'update' : 'create'} hook`,
        color: 'red',
      });
      console.error(err);
    }
  };

  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>
        <Button onClick={loadHooks}>Retry</Button>
      </Container>
    );
  }

  return (
    <Container size="xl" py="xl">
      <Group justify="space-between" mb="xl">
        <div>
          <Title order={2}>Webhooks</Title>
          <Text c="dimmed" size="sm">Manage webhook endpoints for WhatsApp events</Text>
        </div>
        <Button leftSection={<IconPlus size={16} />} onClick={handleCreate}>
          New Hook
        </Button>
      </Group>

      <Table highlightOnHover withTableBorder withColumnBorders>
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Name</Table.Th>
            <Table.Th>URL</Table.Th>
            <Table.Th>Method</Table.Th>
            <Table.Th>Events</Table.Th>
            <Table.Th>Retry</Table.Th>
            <Table.Th>Status</Table.Th>
            <Table.Th>Created</Table.Th>
            <Table.Th>Actions</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {hooks.length === 0 ? (
            <Table.Tr>
              <Table.Td colSpan={8}>
                <Center h={200}>
                  <Stack align="center">
                    <IconWebhook size={48} stroke={1.5} color="gray" />
                    <Text c="dimmed">No hooks configured. Create your first webhook to start receiving WhatsApp events.</Text>
                  </Stack>
                </Center>
              </Table.Td>
            </Table.Tr>
          ) : (
            hooks.map((hook) => {
              let eventsList = [];
              try {
                eventsList = hook.events ? JSON.parse(hook.events) : [];
              } catch {
                eventsList = [];
              }

              return (
                <Table.Tr key={hook.id}>
                  <Table.Td fw={500}>{hook.name}</Table.Td>
                  <Table.Td>
                    <Tooltip label={hook.url} position="top">
                      <Code>
                        {hook.url.length > 40 ? hook.url.substring(0, 40) + '...' : hook.url}
                      </Code>
                    </Tooltip>
                  </Table.Td>
                  <Table.Td>
                    <Badge color={
                      hook.method === 'POST' ? 'blue' : 
                      hook.method === 'GET' ? 'green' : 
                      hook.method === 'PUT' ? 'yellow' : 'pink'
                    } variant="light">
                      {hook.method}
                    </Badge>
                  </Table.Td>
                  <Table.Td>
                    {eventsList.length > 0 ? (
                      <Tooltip label={eventsList.join(', ')} position="top">
                        <Badge variant="outline">
                          {eventsList.length} event{eventsList.length !== 1 ? 's' : ''}
                        </Badge>
                      </Tooltip>
                    ) : (
                      <Text c="dimmed" size="sm" fs="italic">All events</Text>
                    )}
                  </Table.Td>
                  <Table.Td>{hook.retry_count}x</Table.Td>
                  <Table.Td>
                    <Badge color={hook.active ? 'green' : 'red'} variant="light">
                      {hook.active ? 'Active' : 'Inactive'}
                    </Badge>
                  </Table.Td>
                  <Table.Td>{new Date(hook.created_at).toLocaleDateString()}</Table.Td>
                  <Table.Td>
                    <Group gap="xs">
                      <ActionIcon 
                        variant="light" 
                        color="blue"
                        onClick={() => handleEdit(hook)}
                      >
                        <IconEdit size={16} />
                      </ActionIcon>
                      <ActionIcon 
                        variant="light" 
                        color="red"
                        onClick={() => handleDelete(hook.id)}
                      >
                        <IconTrash size={16} />
                      </ActionIcon>
                    </Group>
                  </Table.Td>
                </Table.Tr>
              );
            })
          )}
        </Table.Tbody>
      </Table>

      <Modal 
        opened={opened} 
        onClose={close} 
        title={editingHook ? 'Edit Hook' : 'Create Hook'}
        size="lg"
      >
        <form onSubmit={handleSubmit}>
          <Stack>
            <Group grow>
              <TextInput
                label="Name"
                placeholder="My Webhook"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                required
              />

              <Select
                label="Method"
                value={formData.method}
                onChange={(value) => setFormData({ ...formData, method: value || 'POST' })}
                data={['POST', 'PUT', 'PATCH', 'GET']}
                required
              />
            </Group>

            <TextInput
              label="URL"
              placeholder="https://example.com/webhook"
              value={formData.url}
              onChange={(e) => setFormData({ ...formData, url: e.target.value })}
              required
            />

            <Textarea
              label="Description"
              placeholder="Optional description of this webhook"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={2}
            />

            <TextInput
              label="Secret Key"
              placeholder="Optional secret for HMAC signature"
              type="password"
              value={formData.secret}
              onChange={(e) => setFormData({ ...formData, secret: e.target.value })}
              description="Used to sign webhook payloads for verification"
            />

            <Textarea
              label="Custom Headers (JSON)"
              placeholder='{"Authorization": "Bearer token", "X-Custom": "value"}'
              value={formData.headers}
              onChange={(e) => setFormData({ ...formData, headers: e.target.value })}
              rows={3}
              styles={{ input: { fontFamily: 'monospace', fontSize: '13px' } }}
              description="Optional JSON object with custom HTTP headers"
            />

            <Textarea
              label="Event Filter (JSON Array)"
              placeholder='["message.received", "message.sent", "status.update"]'
              value={formData.events}
              onChange={(e) => setFormData({ ...formData, events: e.target.value })}
              rows={3}
              styles={{ input: { fontFamily: 'monospace', fontSize: '13px' } }}
              description="Leave empty to receive all events, or specify an array of event types"
            />

            <Group grow>
              <NumberInput
                label="Retry Count"
                value={formData.retry_count}
                onChange={(value) => setFormData({ ...formData, retry_count: Number(value) || 0 })}
                min={0}
                max={10}
                required
              />

              <NumberInput
                label="Timeout (seconds)"
                value={formData.timeout}
                onChange={(value) => setFormData({ ...formData, timeout: Number(value) || 30 })}
                min={1}
                max={300}
                required
              />
            </Group>

            <Checkbox
              label="Active"
              checked={formData.active}
              onChange={(e) => setFormData({ ...formData, active: e.currentTarget.checked })}
            />

            <Group justify="flex-end" mt="md">
              <Button variant="default" onClick={close}>Cancel</Button>
              <Button type="submit">{editingHook ? 'Update' : 'Create'}</Button>
            </Group>
          </Stack>
        </form>
      </Modal>
    </Container>
  );
}
