import { useState, useEffect } from 'react';
import { 
  Container, 
  Title, 
  Text, 
  Button, 
  Table, 
  Badge, 
  Group, 
  Modal,
  TextInput,
  Select,
  Textarea,
  Checkbox,
  Stack,
  Alert,
  Loader,
  Center,
  ActionIcon
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconEdit, IconTrash, IconPlus, IconAlertCircle, IconBrandWhatsapp } from '@tabler/icons-react';
import { apiClient } from '../lib/api';
import type { WhatsAppAccount } from '../types';

export default function AccountsPage() {
  const [accounts, setAccounts] = useState<WhatsAppAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [opened, { open, close }] = useDisclosure(false);
  const [editingAccount, setEditingAccount] = useState<WhatsAppAccount | null>(null);
  const [formData, setFormData] = useState({
    phone_number: '',
    display_name: '',
    account_type: 'whatsmeow' as 'whatsmeow' | 'business-api',
    config: '',
    active: true
  });

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

  const loadAccounts = async () => {
    try {
      setLoading(true);
      const data = await apiClient.getAccounts();
      setAccounts(data || []);
      setError(null);
    } catch (err) {
      setError('Failed to load accounts');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingAccount(null);
    setFormData({
      phone_number: '',
      display_name: '',
      account_type: 'whatsmeow',
      config: '',
      active: true
    });
    open();
  };

  const handleEdit = (account: WhatsAppAccount) => {
    setEditingAccount(account);
    setFormData({
      phone_number: account.phone_number,
      display_name: account.display_name || '',
      account_type: account.account_type,
      config: account.config || '',
      active: account.active
    });
    open();
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate config JSON if not empty
    if (formData.config) {
      try {
        JSON.parse(formData.config);
      } catch {
        notifications.show({
          title: 'Error',
          message: 'Config must be valid JSON',
          color: 'red',
        });
        return;
      }
    }

    try {
      if (editingAccount) {
        await apiClient.updateAccount(editingAccount.id, formData);
        notifications.show({
          title: 'Success',
          message: 'Account updated successfully',
          color: 'green',
        });
      } else {
        await apiClient.createAccount(formData);
        notifications.show({
          title: 'Success',
          message: 'Account created successfully',
          color: 'green',
        });
      }
      close();
      await loadAccounts();
    } catch (err) {
      notifications.show({
        title: 'Error',
        message: `Failed to ${editingAccount ? 'update' : 'create'} account`,
        color: 'red',
      });
      console.error(err);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'connected': return 'green';
      case 'connecting': return 'yellow';
      case 'disconnected': return 'red';
      default: return 'gray';
    }
  };

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

  return (
    <Container size="xl" py="xl">
      <Group justify="space-between" mb="xl">
        <div>
          <Title order={2}>WhatsApp Accounts</Title>
          <Text c="dimmed" size="sm">Manage your WhatsApp Business and personal accounts</Text>
        </div>
        <Button leftSection={<IconPlus size={16} />} onClick={handleCreate}>
          New Account
        </Button>
      </Group>

      <Table highlightOnHover withTableBorder withColumnBorders>
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Phone Number</Table.Th>
            <Table.Th>Display Name</Table.Th>
            <Table.Th>Type</Table.Th>
            <Table.Th>Connection</Table.Th>
            <Table.Th>Last Connected</Table.Th>
            <Table.Th>Status</Table.Th>
            <Table.Th>Actions</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {accounts.length === 0 ? (
            <Table.Tr>
              <Table.Td colSpan={7}>
                <Center h={200}>
                  <Stack align="center">
                    <IconBrandWhatsapp size={48} stroke={1.5} color="gray" />
                    <Text c="dimmed">No WhatsApp accounts configured. Add your first account to start sending messages.</Text>
                  </Stack>
                </Center>
              </Table.Td>
            </Table.Tr>
          ) : (
            accounts.map((account) => (
              <Table.Tr key={account.id}>
                <Table.Td fw={500}>{account.phone_number || '-'}</Table.Td>
                <Table.Td>{account.display_name || '-'}</Table.Td>
                <Table.Td>
                  <Badge color={account.account_type === 'whatsmeow' ? 'green' : 'blue'} variant="light">
                    {account.account_type === 'whatsmeow' ? 'WhatsApp' : 'Business API'}
                  </Badge>
                </Table.Td>
                <Table.Td>
                  <Badge color={getStatusColor(account.status)} variant="light">
                    {account.status}
                  </Badge>
                </Table.Td>
                <Table.Td>
                  {account.last_connected_at 
                    ? new Date(account.last_connected_at).toLocaleString()
                    : 'Never'}
                </Table.Td>
                <Table.Td>
                  <Badge color={account.active ? 'green' : 'red'} variant="light">
                    {account.active ? 'Active' : 'Inactive'}
                  </Badge>
                </Table.Td>
                <Table.Td>
                  <Group gap="xs">
                    <ActionIcon 
                      variant="light" 
                      color="blue"
                      onClick={() => handleEdit(account)}
                    >
                      <IconEdit size={16} />
                    </ActionIcon>
                    <ActionIcon 
                      variant="light" 
                      color="red"
                      onClick={() => handleDelete(account.id)}
                    >
                      <IconTrash size={16} />
                    </ActionIcon>
                  </Group>
                </Table.Td>
              </Table.Tr>
            ))
          )}
        </Table.Tbody>
      </Table>

      <Modal 
        opened={opened} 
        onClose={close} 
        title={editingAccount ? 'Edit Account' : 'Create Account'}
        size="lg"
      >
        <form onSubmit={handleSubmit}>
          <Stack>
            <TextInput
              label="Phone Number"
              placeholder="+1234567890"
              value={formData.phone_number}
              onChange={(e) => setFormData({ ...formData, phone_number: e.target.value })}
              required
              description="Include country code (e.g., +1 for US)"
            />

            <TextInput
              label="Display Name"
              placeholder="My Business Account"
              value={formData.display_name}
              onChange={(e) => setFormData({ ...formData, display_name: e.target.value })}
            />

            <Select
              label="Account Type"
              value={formData.account_type}
              onChange={(value) => setFormData({ ...formData, account_type: value as 'whatsmeow' | 'business-api' })}
              data={[
                { value: 'whatsmeow', label: 'WhatsApp (WhatsMe)' },
                { value: 'business-api', label: 'Business API' }
              ]}
              required
              description="WhatsApp: Personal/WhatsApp Business app connection. Business API: Official WhatsApp Business API"
            />

            {formData.account_type === 'business-api' && (
              <Textarea
                label="Business API Config (JSON)"
                placeholder={`{
  "api_key": "your-api-key",
  "api_url": "https://api.whatsapp.com",
  "phone_number_id": "123456"
}`}
                value={formData.config}
                onChange={(e) => setFormData({ ...formData, config: e.target.value })}
                rows={6}
                styles={{ input: { fontFamily: 'monospace', fontSize: '13px' } }}
                description="Business API credentials and configuration"
              />
            )}

            <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">{editingAccount ? 'Update' : 'Create'}</Button>
            </Group>
          </Stack>
        </form>
      </Modal>
    </Container>
  );
}
