import { useState, useEffect, useCallback, useRef } from 'react';
import { Card, Row, Col, Statistic, Tag, Typography, Space, Button, Descriptions, Spin, App, Input, Drawer, Switch } from 'antd';
import {
  PhoneOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  MessageOutlined,
  ThunderboltOutlined,
  SyncOutlined,
  MobileOutlined,
  SendOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { SmsDeviceStatus, SmsCampaign, SmsPaginatedResponse } from '@/types/sms';
import type { AppOutletContext } from '@/types/api';
import { useOutletContext } from 'react-router-dom';

const { Title, Text } = Typography;
const { TextArea } = Input;

export default function SmsDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();

  const [deviceStatus, setDeviceStatus] = useState<SmsDeviceStatus | null>(null);
  const [campaigns, setCampaigns] = useState<SmsCampaign[]>([]);
  const [conversationStats, setConversationStats] = useState<{ total: number; active: number; optedOut: number; unread: number } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setPageHeader({ title: 'SMS Dashboard', subtitle: 'Termux Android SMS integration' });
  }, [setPageHeader]);

  const fetchData = useCallback(async () => {
    try {
      const [deviceRes, campaignsRes, statsRes] = await Promise.all([
        api.get('/sms/device').catch(() => ({ data: null })),
        api.get<SmsPaginatedResponse<SmsCampaign>>('/sms/campaigns', { params: { limit: 5 } }).catch(() => ({ data: { items: [] } })),
        api.get('/sms/conversations/stats').catch(() => ({ data: null })),
      ]);
      setDeviceStatus(deviceRes.data);
      setCampaigns(campaignsRes.data.items || []);
      setConversationStats(statsRes.data);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 15000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const handleSync = async () => {
    try {
      await api.post('/sms/device/sync');
      message.success('Response sync triggered');
      fetchData();
    } catch {
      message.error('Sync failed');
    }
  };

  // --- Quick Send ---
  const [quickPhone, setQuickPhone] = useState('');
  const [quickMessage, setQuickMessage] = useState('');
  const [quickSending, setQuickSending] = useState(false);

  const handleQuickSend = async () => {
    if (!quickPhone.trim() || !quickMessage.trim()) {
      message.warning('Enter both a phone number and a message');
      return;
    }
    setQuickSending(true);
    try {
      await api.post('/sms/messages/send', { phone: quickPhone.trim(), message: quickMessage.trim() });
      message.success('Message sent');
      setQuickMessage('');
    } catch {
      message.error('Failed to send message');
    } finally {
      setQuickSending(false);
    }
  };

  // --- Logs Drawer ---
  const [logsOpen, setLogsOpen] = useState(false);
  const [logLines, setLogLines] = useState<string[]>([]);
  const [logInfo, setLogInfo] = useState<{ totalLines: number; fileSize: number } | null>(null);
  const [logsLoading, setLogsLoading] = useState(false);
  const [logsAutoRefresh, setLogsAutoRefresh] = useState(false);
  const logsEndRef = useRef<HTMLDivElement>(null);

  const fetchLogs = useCallback(async () => {
    setLogsLoading(true);
    try {
      const { data } = await api.get<{ lines: string[]; totalLines: number; fileSize: number }>(
        '/sms/device/logs', { params: { lines: 200 } }
      );
      setLogLines(data.lines);
      setLogInfo({ totalLines: data.totalLines, fileSize: data.fileSize });
      setTimeout(() => logsEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
    } catch {
      // Endpoint may not exist yet — silently handle
      setLogLines(['Failed to fetch logs. The endpoint may not be available yet.']);
    } finally {
      setLogsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (logsOpen) fetchLogs();
  }, [logsOpen, fetchLogs]);

  useEffect(() => {
    if (!logsOpen || !logsAutoRefresh) return;
    const interval = setInterval(fetchLogs, 5000);
    return () => clearInterval(interval);
  }, [logsOpen, logsAutoRefresh, fetchLogs]);

  const colorLogLine = (line: string) => {
    if (/\bERROR\b/i.test(line)) return '#ff4d4f';
    if (/\bWARN(ING)?\b/i.test(line)) return '#faad14';
    return '#d9d9d9';
  };

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;

  const activeCampaigns = campaigns.filter((c) => c.status === 'RUNNING');

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      {/* Quick Send */}
      <Card title={<><SendOutlined /> Quick Send</>} size="small">
        <Row gutter={16} align="bottom">
          <Col xs={24} sm={8} md={6}>
            <Text type="secondary" style={{ fontSize: 12 }}>Phone Number</Text>
            <Input
              value={quickPhone}
              onChange={(e) => setQuickPhone(e.target.value)}
              placeholder="+1 555 123 4567"
              prefix={<PhoneOutlined />}
              style={{ marginTop: 4 }}
            />
          </Col>
          <Col xs={24} sm={12} md={14}>
            <Text type="secondary" style={{ fontSize: 12 }}>Message</Text>
            <TextArea
              value={quickMessage}
              onChange={(e) => setQuickMessage(e.target.value)}
              placeholder="Type your message..."
              rows={1}
              maxLength={1600}
              showCount
              style={{ marginTop: 4 }}
            />
          </Col>
          <Col xs={24} sm={4} md={4}>
            <Button
              type="primary"
              icon={<SendOutlined />}
              loading={quickSending}
              onClick={handleQuickSend}
              block
            >
              Send
            </Button>
          </Col>
        </Row>
      </Card>

      {/* Device Status */}
      <Card
        title={<><MobileOutlined /> Device Status</>}
        extra={
          <Space>
            <Button icon={<FileTextOutlined />} onClick={() => setLogsOpen(true)} size="small">View Phone Logs</Button>
            <Button icon={<SyncOutlined />} onClick={handleSync} size="small">Sync Now</Button>
          </Space>
        }
      >
        {deviceStatus ? (
          <Descriptions column={{ xs: 1, sm: 2, md: 4 }}>
            <Descriptions.Item label="Connection">
              {deviceStatus.isConnected
                ? <Tag color="success" icon={<CheckCircleOutlined />}>Connected</Tag>
                : <Tag color="error" icon={<CloseCircleOutlined />}>Disconnected</Tag>
              }
            </Descriptions.Item>
            <Descriptions.Item label="Battery">
              {deviceStatus.batteryLevel !== null
                ? <Text>{deviceStatus.batteryLevel}% ({deviceStatus.batteryStatus})</Text>
                : <Text type="secondary">Unknown</Text>
              }
            </Descriptions.Item>
            <Descriptions.Item label="Total Sent">
              {deviceStatus.totalSent}
            </Descriptions.Item>
            <Descriptions.Item label="Last Check">
              {deviceStatus.lastCheckedAt
                ? new Date(deviceStatus.lastCheckedAt).toLocaleString()
                : 'Never'
              }
            </Descriptions.Item>
          </Descriptions>
        ) : (
          <Text type="secondary">No device status available. Is SMS enabled?</Text>
        )}
      </Card>

      {/* Quick Stats */}
      <Row gutter={[16, 16]}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Active Campaigns"
              value={activeCampaigns.length}
              prefix={<ThunderboltOutlined />}
              valueStyle={{ color: activeCampaigns.length > 0 ? '#52c41a' : undefined }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Conversations"
              value={conversationStats?.total ?? 0}
              prefix={<MessageOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Unread"
              value={conversationStats?.unread ?? 0}
              prefix={<PhoneOutlined />}
              valueStyle={{ color: (conversationStats?.unread ?? 0) > 0 ? '#faad14' : undefined }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Opted Out"
              value={conversationStats?.optedOut ?? 0}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* Recent Campaigns */}
      <Card title="Recent Campaigns">
        {campaigns.length === 0 ? (
          <Text type="secondary">No campaigns yet. Create one from the Campaigns page.</Text>
        ) : (
          <Space direction="vertical" style={{ width: '100%' }}>
            {campaigns.map((c) => (
              <Card key={c.id} size="small" type="inner">
                <Row justify="space-between" align="middle">
                  <Col>
                    <Title level={5} style={{ margin: 0 }}>{c.name}</Title>
                    <Text type="secondary">{c.contactList?.name}</Text>
                  </Col>
                  <Col>
                    <Space>
                      <Tag color={
                        c.status === 'RUNNING' ? 'processing' :
                        c.status === 'COMPLETED' ? 'success' :
                        c.status === 'PAUSED' ? 'warning' :
                        c.status === 'FAILED' ? 'error' : 'default'
                      }>{c.status}</Tag>
                      <Text>{c.totalSent}/{c.totalRecipients} sent</Text>
                      {c.totalFailed > 0 && <Text type="danger">{c.totalFailed} failed</Text>}
                      {c.totalResponded > 0 && <Text type="success">{c.totalResponded} responded</Text>}
                    </Space>
                  </Col>
                </Row>
              </Card>
            ))}
          </Space>
        )}
      </Card>

      {/* Logs Drawer */}
      <Drawer
        title="Phone Logs"
        open={logsOpen}
        onClose={() => { setLogsOpen(false); setLogsAutoRefresh(false); }}
        width={720}
        extra={
          <Space>
            <Text type="secondary" style={{ fontSize: 12 }}>
              {logInfo ? `${logInfo.totalLines} lines (${(logInfo.fileSize / 1024).toFixed(1)} KB)` : ''}
            </Text>
            <Switch
              checkedChildren="Auto"
              unCheckedChildren="Auto"
              checked={logsAutoRefresh}
              onChange={setLogsAutoRefresh}
              size="small"
            />
            <Button size="small" icon={<SyncOutlined spin={logsLoading} />} onClick={fetchLogs}>
              Refresh
            </Button>
          </Space>
        }
      >
        <div
          style={{
            background: '#1a1a2e',
            borderRadius: 6,
            padding: 12,
            height: 'calc(100vh - 160px)',
            overflow: 'auto',
            fontFamily: "'JetBrains Mono', 'Fira Code', 'Consolas', monospace",
            fontSize: 12,
            lineHeight: 1.6,
          }}
        >
          {logLines.map((line, i) => (
            <div key={i} style={{ color: colorLogLine(line), whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
              {line}
            </div>
          ))}
          <div ref={logsEndRef} />
        </div>
      </Drawer>
    </Space>
  );
}
