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

function buildSessionPath(accountId: string) {
  return `./sessions/${accountId}`;
}

function sortAccountsAlphabetically(accounts: WhatsAppAccount[]): WhatsAppAccount[] {
  return [...accounts].sort((a, b) =>
    (a.account_id || a.id).localeCompare((b.account_id || b.id), undefined, { sensitivity: 'base' }),
  );
}

function mapConfigToAccount(configuredAccount: WhatsAppAccountConfig): WhatsAppAccount {
  return {
    id: configuredAccount.id,
    account_id: configuredAccount.id,
    user_id: '',
    phone_number: configuredAccount.phone_number || '',
    display_name: '',
    account_type: configuredAccount.type || 'whatsmeow',
    status: configuredAccount.status || 'disconnected',
    show_qr: configuredAccount.show_qr,
    business_api: configuredAccount.business_api,
    config: configuredAccount.business_api ? JSON.stringify(configuredAccount.business_api, null, 2) : '',
    session_path: configuredAccount.session_path || buildSessionPath(configuredAccount.id),
    last_connected_at: undefined,
    active: !configuredAccount.disabled,
    created_at: '',
    updated_at: '',
  };
}

type BusinessAPIFormData = {
  phone_number_id: string;
  access_token: string;
  waba_id: string;
  business_account_id: string;
  api_version: string;
  webhook_path: string;
  verify_token: string;
};

function emptyBusinessAPIFormData(): BusinessAPIFormData {
  return {
    phone_number_id: '',
    access_token: '',
    waba_id: '',
    business_account_id: '',
    api_version: 'v21.0',
    webhook_path: '',
    verify_token: '',
  };
}

function toBusinessAPIFormData(config?: BusinessAPIConfig): BusinessAPIFormData {
  return {
    phone_number_id: typeof config?.phone_number_id === 'string' ? config.phone_number_id : '',
    access_token: typeof config?.access_token === 'string' ? config.access_token : '',
    waba_id: typeof config?.waba_id === 'string' ? config.waba_id : '',
    business_account_id: typeof config?.business_account_id === 'string' ? config.business_account_id : '',
    api_version: typeof config?.api_version === 'string' && config.api_version ? config.api_version : 'v21.0',
    webhook_path: typeof config?.webhook_path === 'string' ? config.webhook_path : '',
    verify_token: typeof config?.verify_token === 'string' ? config.verify_token : '',
  };
}

function fromBusinessAPIFormData(form: BusinessAPIFormData): BusinessAPIConfig {
  const payload: BusinessAPIConfig = {};

  const phoneNumberID = form.phone_number_id.trim();
  const accessToken = form.access_token.trim();
  const wabaID = form.waba_id.trim();
  const businessAccountID = form.business_account_id.trim();
  const apiVersion = form.api_version.trim();
  const webhookPath = form.webhook_path.trim();
  const verifyToken = form.verify_token.trim();

  if (phoneNumberID) payload.phone_number_id = phoneNumberID;
  if (accessToken) payload.access_token = accessToken;
  if (wabaID) payload.waba_id = wabaID;
  if (businessAccountID) payload.business_account_id = businessAccountID;
  if (apiVersion) payload.api_version = apiVersion;
  if (webhookPath) payload.webhook_path = webhookPath;
  if (verifyToken) payload.verify_token = verifyToken;

  return payload;
}

function parseLegacyBusinessAPIConfig(configJSON?: string): BusinessAPIConfig | undefined {
  if (!configJSON) {
    return undefined;
  }

  try {
    const parsed = JSON.parse(configJSON);
    if (!parsed || typeof parsed !== 'object') {
      return undefined;
    }
    return parsed as BusinessAPIConfig;
  } catch {
    return undefined;
  }
}

function getConnectionStatus(
  account: WhatsAppAccount,
): string {
  return account.status;
}

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 [qrModalOpened, { open: openQRModal, close: closeQRModal }] = useDisclosure(false);
  const [editingAccount, setEditingAccount] = useState<WhatsAppAccount | null>(null);
  const [selectedQRAccount, setSelectedQRAccount] = useState<WhatsAppAccount | null>(null);
  const [qrImageError, setQRImageError] = useState<string | null>(null);
  const [qrRefreshTick, setQRRefreshTick] = useState(0);
  const [formData, setFormData] = useState({
    account_id: '',
    phone_number: '',
    display_name: '',
    account_type: 'whatsmeow' as 'whatsmeow' | 'business-api',
    business_api: emptyBusinessAPIFormData(),
    active: true
  });

  const loadAccounts = useCallback(async (showLoader = true) => {
    try {
      if (showLoader) {
        setLoading(true);
      }
      const configuredAccounts = await apiClient.getAccountConfigs();
      setAccounts(sortAccountsAlphabetically((configuredAccounts || []).map(mapConfigToAccount)));
      setError(null);
    } catch (err) {
      setError('Failed to load accounts');
      console.error(err);
    } finally {
      if (showLoader) {
        setLoading(false);
      }
    }
  }, []);

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

  useEffect(() => {
    const interval = setInterval(() => {
      void loadAccounts(false);
    }, 5000);

    return () => clearInterval(interval);
  }, [loadAccounts]);

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

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

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this account?')) {
      return;
    }
    try {
      await apiClient.removeAccountConfig(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 getQRCodePath = (accountId: string) => `/api/qr/${encodeURIComponent(accountId)}`;

  const getQRCodeUrl = (accountId: string) => `${window.location.origin}${getQRCodePath(accountId)}`;

  const handleOpenQRModal = (account: WhatsAppAccount) => {
    setSelectedQRAccount(account);
    setQRImageError(null);
    setQRRefreshTick(0);
    openQRModal();
  };

  const handleCloseQRModal = () => {
    setSelectedQRAccount(null);
    setQRImageError(null);
    setQRRefreshTick(0);
    closeQRModal();
  };

  useEffect(() => {
    if (!qrModalOpened || !selectedQRAccount) {
      return;
    }

    const refreshInterval = setInterval(() => {
      setQRRefreshTick((previous) => previous + 1);
      setQRImageError(null);
    }, 4000);

    return () => clearInterval(refreshInterval);
  }, [qrModalOpened, selectedQRAccount]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const accountId = (editingAccount?.id || formData.account_id).trim();
    const businessAPIPayload = fromBusinessAPIFormData(formData.business_api);

    if (
      formData.account_type === 'business-api' &&
      (!businessAPIPayload.phone_number_id || !businessAPIPayload.access_token)
    ) {
      notifications.show({
        title: 'Error',
        message: 'Phone Number ID and Access Token are required for Business API accounts',
        color: 'red',
      });
      return;
    }

    try {
      const payload: WhatsAppAccountConfig = {
        id: accountId,
        type: formData.account_type,
        phone_number: formData.phone_number.trim(),
        session_path: editingAccount?.session_path || buildSessionPath(accountId),
        disabled: !formData.active,
      };

      if (formData.account_type === 'business-api') {
        payload.business_api = businessAPIPayload;
      }

      if (editingAccount) {
        await apiClient.updateAccountConfig(payload);
        notifications.show({
          title: 'Success',
          message: 'Account updated successfully',
          color: 'green',
        });
      } else {
        await apiClient.addAccountConfig(payload);
        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 'pairing': 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>Account ID</Table.Th>
            <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={8}>
                <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) => {
              const connectionStatus = getConnectionStatus(account);
              return (
              <Table.Tr key={account.id}>
                <Table.Td fw={500}>{account.account_id || '-'}</Table.Td>
                <Table.Td>{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' : 'Meta Business API'}
                  </Badge>
                </Table.Td>
                <Table.Td>
                  <Badge color={getStatusColor(connectionStatus)} variant="light">
                    {connectionStatus}
                  </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">
                    {account.account_type === 'whatsmeow' && (
                      <ActionIcon
                        variant="light"
                        color="teal"
                        onClick={() => handleOpenQRModal(account)}
                        title="View QR code"
                      >
                        <IconQrcode size={16} />
                      </ActionIcon>
                    )}
                    <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="Account ID"
              placeholder="my-business-account"
              value={formData.account_id}
              onChange={(e) => setFormData({ ...formData, account_id: e.target.value })}
              required
              disabled={!!editingAccount}
              description={
                editingAccount
                  ? 'Account ID is fixed after creation'
                  : 'Unique identifier for this account (lowercase, alphanumeric, hyphens allowed)'
              }
            />

            <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' },
                { value: 'business-api', label: 'Meta Business API' }
              ]}
              required
              disabled={!!editingAccount}
              description="Whatsapp: Personal/WhatsApp Business app connection. Meta Business API: Official WhatsApp Business API"
            />

            {formData.account_type === 'business-api' && (
              <>
                <TextInput
                  label="Phone Number ID"
                  placeholder="123456789012345"
                  value={formData.business_api.phone_number_id}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, phone_number_id: e.target.value },
                    })
                  }
                  required
                  description="Required Meta phone number identifier"
                />

                <TextInput
                  label="Access Token"
                  placeholder="EAAG..."
                  type="password"
                  value={formData.business_api.access_token}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, access_token: e.target.value },
                    })
                  }
                  required
                  description="Required WhatsApp Business API token"
                />

                <TextInput
                  label="WABA ID"
                  placeholder="Optional (resolved automatically when omitted)"
                  value={formData.business_api.waba_id}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, waba_id: e.target.value },
                    })
                  }
                />

                <TextInput
                  label="Business Account ID"
                  placeholder="Optional Facebook Business Manager ID"
                  value={formData.business_api.business_account_id}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, business_account_id: e.target.value },
                    })
                  }
                />

                <TextInput
                  label="API Version"
                  placeholder="v21.0"
                  value={formData.business_api.api_version}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, api_version: e.target.value },
                    })
                  }
                  description="Defaults to v21.0 if empty"
                />

                <TextInput
                  label="Webhook Path"
                  placeholder="/webhooks/whatsapp/{account}"
                  value={formData.business_api.webhook_path}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, webhook_path: e.target.value },
                    })
                  }
                />

                <TextInput
                  label="Verify Token"
                  placeholder="Optional webhook verification token"
                  value={formData.business_api.verify_token}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      business_api: { ...formData.business_api, verify_token: e.target.value },
                    })
                  }
                />
              </>
            )}

            <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>

      <Modal
        opened={qrModalOpened}
        onClose={handleCloseQRModal}
        title={`QR Code: ${selectedQRAccount?.account_id || selectedQRAccount?.id || ''}`}
        size="lg"
      >
        <Stack>
          {selectedQRAccount && (
            <>
              <Text size="sm" c="dimmed">QR image URL</Text>
              <Code block>{getQRCodeUrl(selectedQRAccount.id)}</Code>
              <Anchor
                href={getQRCodePath(selectedQRAccount.id)}
                target="_blank"
                rel="noopener noreferrer"
              >
                Open QR image in new tab
              </Anchor>
              {qrImageError ? (
                <Alert icon={<IconAlertCircle size={16} />} color="yellow" title="QR unavailable">
                  {qrImageError}
                </Alert>
              ) : (
                <img
                  src={`${getQRCodePath(selectedQRAccount.id)}?t=${qrRefreshTick}`}
                  alt={`QR code for account ${selectedQRAccount.account_id || selectedQRAccount.id}`}
                  style={{ width: '100%', maxWidth: 420, alignSelf: 'center', borderRadius: 8 }}
                  onError={() =>
                    setQRImageError('No QR code available. The account may already be connected or pairing has not started yet.')
                  }
                />
              )}
            </>
          )}
        </Stack>
      </Modal>
    </Container>
  );
}
