import { useEffect, useState } from "react";
import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import {
  Space,
  Tabs,
  Button,
  Tag,
  Toast,
  Popup,
  Input,
  Form
} from '@nutui/nutui-react-taro';
import {
  QrCode,
  Share,
  Copy,
  Download,
  User,
  Phone,
  Calendar,
  Gift
} from '@nutui/icons-react-taro';
import './invite.scss';

// 邀请记录数据类型
interface InviteRecord {
  id: string;
  inviteeName: string;
  inviteePhone: string;
  inviteDate: string;
  status: 'pending' | 'registered' | 'signed';
  reward: string;
}

// 邀请统计数据类型
interface InviteStats {
  totalInvites: number;
  registeredCount: number;
  signedCount: number;
  totalReward: string;
}

const CustomerInvite = () => {
  const [statusBarHeight, setStatusBarHeight] = useState<number>(0);
  const [activeTab, setActiveTab] = useState<string>('qrcode');
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
  const [inviteRecords, setInviteRecords] = useState<InviteRecord[]>([]);
  const [inviteStats, setInviteStats] = useState<InviteStats | null>(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');
  const [showInviteForm, setShowInviteForm] = useState(false);
  const [inviteFormData, setInviteFormData] = useState({
    name: '',
    phone: ''
  });

  // 模拟邀请记录数据
  const mockInviteRecords: InviteRecord[] = [
    {
      id: '1',
      inviteeName: '张三',
      inviteePhone: '138****1234',
      inviteDate: '2025-08-20 14:30:00',
      status: 'signed',
      reward: '500'
    },
    {
      id: '2',
      inviteeName: '李四',
      inviteePhone: '139****5678',
      inviteDate: '2025-08-19 10:15:00',
      status: 'registered',
      reward: '200'
    },
    {
      id: '3',
      inviteeName: '王五',
      inviteePhone: '136****9012',
      inviteDate: '2025-08-18 16:45:00',
      status: 'pending',
      reward: '0'
    }
  ];

  // 模拟邀请统计数据
  const mockInviteStats: InviteStats = {
    totalInvites: 15,
    registeredCount: 8,
    signedCount: 3,
    totalReward: '2,800'
  };

  const tabList = [
    { title: '邀请二维码', value: 'qrcode' },
    { title: '邀请记录', value: 'records' },
    { title: '邀请统计', value: 'stats' }
  ];

  const showToastMsg = (msg: string) => {
    setToastMsg(msg);
    setShowToast(true);
    setTimeout(() => setShowToast(false), 2000);
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '待注册';
      case 'registered':
        return '已注册';
      case 'signed':
        return '已签约';
      default:
        return '';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return '#ff6b35';
      case 'registered':
        return '#1890ff';
      case 'signed':
        return '#52c41a';
      default:
        return '#999';
    }
  };

  // 生成二维码
  const generateQRCode = () => {
    // 模拟生成二维码URL
    const inviteCode = 'INV' + Date.now().toString().slice(-6);
    const qrUrl = `https://example.com/invite?code=${inviteCode}`;
    setQrCodeUrl(qrUrl);

    // 实际项目中这里应该调用二维码生成库
    showToastMsg('二维码已生成');
  };

  // 复制邀请链接
  const copyInviteLink = () => {
    const inviteLink = `https://example.com/invite?code=INV123456`;

    Taro.setClipboardData({
      data: inviteLink,
      success: () => {
        showToastMsg('邀请链接已复制到剪贴板');
      },
      fail: () => {
        showToastMsg('复制失败，请重试');
      }
    });
  };

  // 分享邀请
  const shareInvite = () => {
    Taro.showShareMenu({
      withShareTicket: true,
      success: () => {
        showToastMsg('分享成功');
      },
      fail: () => {
        showToastMsg('分享失败');
      }
    });
  };

  // 下载二维码
  const downloadQRCode = () => {
    showToastMsg('下载功能开发中');
  };

  // 手动邀请
  const handleManualInvite = () => {
    setShowInviteForm(true);
  };

  // 提交邀请表单
  const submitInviteForm = () => {
    if (!inviteFormData.name || !inviteFormData.phone) {
      showToastMsg('请填写完整信息');
      return;
    }

    // 模拟发送邀请
    showToastMsg('邀请已发送');
    setShowInviteForm(false);
    setInviteFormData({ name: '', phone: '' });

    // 刷新邀请记录
    loadInviteData().then();
  };

  // 加载邀请数据
  const loadInviteData = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setInviteRecords(mockInviteRecords);
      setInviteStats(mockInviteStats);
    } catch (error) {
      showToastMsg('加载失败，请重试');
    }
  };

  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(Number(res.statusBarHeight))
      },
    });

    generateQRCode();
    loadInviteData().then();
  }, []);

  const renderQRCodeTab = () => (
    <View className="qrcode-container">
      <View className="qr-card">
        <View className="qr-header">
          <View className="qr-title pt-2">我的邀请二维码</View>
          <View className="qr-subtitle py-2">扫码注册即可获得奖励</View>
        </View>

        <View className="qr-code">
          {qrCodeUrl ? (
            <View className="qr-placeholder">
              <QrCode size={80} color="#333" />
              <Text className="qr-text">二维码</Text>
            </View>
          ) : (
            <View className="qr-loading">
              <Text>生成中...</Text>
            </View>
          )}
        </View>

        <Space className="qr-actions mt-4">
          <Button
            className="action-btn"
            size="small"
            onClick={copyInviteLink}
          >
            <View className={'flex items-center justify-center px-1'}>
              <Copy size={14} />
              <Text className="ml-1">复制链接</Text>
            </View>
          </Button>
          <Button
            className="action-btn"
            size="small"
            onClick={shareInvite}
          >
            <View className={'flex items-center justify-center px-1'}>
              <Share size={14} />
              <Text className="ml-1">分享邀请</Text>
            </View>
          </Button>
          <Button
            size="small"
            onClick={downloadQRCode}
          >
            <View className={'flex items-center justify-center px-1'}>
              <Download size={14} />
              <Text className="ml-1">下载二维码</Text>
            </View>
          </Button>
        </Space>
      </View>

      <View className="invite-tips">
        <View className="tips-header">
          <Gift size={16} color="#52c41a" />
          <Text className="tips-title">邀请奖励规则</Text>
        </View>
        <View className="tips-content">
          <Text className="tip-item">• 邀请好友注册：奖励200元</Text>
          <Text className="tip-item">• 好友成功签约：额外奖励300元</Text>
          <Text className="tip-item">• 奖励将在好友完成相应操作后24小时内到账</Text>
        </View>
      </View>

      <View className="manual-invite">
        <Button
          className="manual-btn"
          onClick={handleManualInvite}
        >
          手动邀请好友
        </Button>
      </View>
    </View>
  );

  const renderRecordsTab = () => (
    <View className="records-container">
      {inviteRecords.length > 0 ? (
        inviteRecords.map((record) => (
          <View key={record.id} className="record-item">
            <View className="record-header">
              <View className="user-info">
                <User size={16} color="#666" />
                <Text className="user-name">{record.inviteeName}</Text>
              </View>
              <Tag
                color={getStatusColor(record.status)}
                plain
              >
                {getStatusText(record.status)}
              </Tag>
            </View>

            <View className="record-details">
              <View className="detail-item">
                <Phone size={14} color="#999" />
                <Text className="detail-text">{record.inviteePhone}</Text>
              </View>
              <View className="detail-item">
                <Calendar size={14} color="#999" />
                <Text className="detail-text">{record.inviteDate}</Text>
              </View>
              <View className="detail-item">
                <Gift size={14} color="#52c41a" />
                <Text className="detail-text">
                  奖励：¥{record.reward}
                </Text>
              </View>
            </View>
          </View>
        ))
      ) : (
        <View className="empty-records">
          <Text>暂无邀请记录</Text>
        </View>
      )}
    </View>
  );

  const renderStatsTab = () => (
    <View className="stats-container">
      {inviteStats && (
        <>
          <View className="stats-overview">
            <View className="stat-item">
              <Text className="stat-number">{inviteStats.totalInvites}</Text>
              <Text className="stat-label">总邀请数</Text>
            </View>
            <View className="stat-item">
              <Text className="stat-number">{inviteStats.registeredCount}</Text>
              <Text className="stat-label">已注册</Text>
            </View>
            <View className="stat-item">
              <Text className="stat-number">{inviteStats.signedCount}</Text>
              <Text className="stat-label">已签约</Text>
            </View>
          </View>

          <View className="reward-summary">
            <Space className="reward-card flex items-center justify-center">
              <Text>累计奖励</Text>
              <Text>¥{inviteStats.totalReward}</Text>
              <Button type={'success'} size="small">
                提现
              </Button>
            </Space>
          </View>

          <View className="stats-chart">
            <Text className="chart-title">邀请趋势</Text>
            <View className="chart-placeholder">
              <Text>图表功能开发中</Text>
            </View>
          </View>
        </>
      )}
    </View>
  );

  return (
    <View className="customer-invite-page">
      {/* 头部背景 */}
      <View className="header-bg" style={{ height: '180px' }} />

      {/* 标签页 */}
      <View className="tabs-container">
        <Tabs
          value={activeTab}
          onChange={(value) => setActiveTab(value as string)}
        >
          {tabList.map(tab => (
            <Tabs.TabPane key={tab.value} title={tab.title} value={tab.value} />
          ))}
        </Tabs>
      </View>

      {/* 内容区域 */}
      <View className="content-container">
        {activeTab === 'qrcode' && renderQRCodeTab()}
        {activeTab === 'records' && renderRecordsTab()}
        {activeTab === 'stats' && renderStatsTab()}
      </View>

      {/* 手动邀请弹窗 */}
      <Popup
        visible={showInviteForm}
        position="bottom"
        onClose={() => setShowInviteForm(false)}
      >
        <View className="invite-form">
          <View className="form-header">
            <Text className="form-title">邀请好友</Text>
          </View>
          <Form>
            <Form.Item label="姓名" required>
              <Input
                placeholder="请输入好友姓名"
                value={inviteFormData.name}
                onChange={(value) => setInviteFormData(prev => ({ ...prev, name: value }))}
              />
            </Form.Item>
            <Form.Item label="手机号" required>
              <Input
                placeholder="请输入好友手机号"
                type="tel"
                value={inviteFormData.phone}
                onChange={(value) => setInviteFormData(prev => ({ ...prev, phone: value }))}
              />
            </Form.Item>
          </Form>
          <View className="form-actions">
            <Button
              className="cancel-btn"
              onClick={() => setShowInviteForm(false)}
            >
              取消
            </Button>
            <Button
              className="submit-btn"
              onClick={submitInviteForm}
            >
              发送邀请
            </Button>
          </View>
        </View>
      </Popup>

      {/* Toast提示 */}
      <Toast
        visible={showToast}
        content={toastMsg}
        duration={2000}
      />
    </View>
  );
};

export default CustomerInvite;
