import { View, Text, Image, Button, Input, Textarea } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { getServiceDetail, createServiceOrder } from '../../api'
import './detail.scss'

export default function ServiceDetail() {
  const [service, setService] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [modalVisible, setModalVisible] = useState(false)
  const [formData, setFormData] = useState({
    customer_name: '',
    company_name: '',
    phone_number: '',
    email: '',
    requirements: ''
  })

  useLoad((options) => {
    if (options.id) {
      fetchDetail(options.id)
    }
  })

  const fetchDetail = async (id: string) => {
    try {
      const res: any = await getServiceDetail(Number(id))
      setService(res)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleInput = (key: string, value: string) => {
    setFormData(prev => ({ ...prev, [key]: value }))
  }

  const handleSubmit = async () => {
    if (!formData.customer_name || !formData.phone_number) {
      Taro.showToast({ title: '请填写姓名和电话', icon: 'none' })
      return
    }

    try {
      Taro.showLoading({ title: '提交中...' })
      await createServiceOrder({
        service: service.id,
        ...formData,
        ref_code: Taro.getStorageSync('ref_code') || ''
      })
      Taro.hideLoading()
      setModalVisible(false)
      Taro.showModal({
        title: '提交成功',
        content: '需求已提交，我们的销售顾问将尽快与您联系！',
        showCancel: false
      })
    } catch (err) {
      Taro.hideLoading()
      Taro.showToast({ title: '提交失败', icon: 'none' })
    }
  }

  if (loading) return <View className='page-container'><Text style={{color:'#fff'}}>Loading...</Text></View>
  if (!service) return <View className='page-container'><Text style={{color:'#fff'}}>Service not found</Text></View>

  return (
    <View className='page-container'>
      <View className='detail-header'>
        <Text className='title'>{service.title}</Text>
        <Text className='desc'>{service.description}</Text>
      </View>

      <View className='info-card'>
        <View className='card-title'>
          <View className='bar' style={{ background: service.color }} />
          <Text>服务详情</Text>
        </View>
        <View className='info-item'>
           <Text className='label'>交付周期</Text>
           <Text className='value'>{service.delivery_time || '待沟通'}</Text>
        </View>
        <View className='info-item'>
           <Text className='label'>交付内容</Text>
           <Text className='value'>{service.delivery_content || '根据需求定制'}</Text>
        </View>
      </View>

      {service.detail_image_url && (
        <View className='detail-image-box' style={{ boxShadow: `0 10px 40px ${service.color}22` }}>
           <Image src={service.detail_image_url} className='detail-img' mode='widthFix' />
        </View>
      )}

      <View className='price-card'>
         <Text className='price-title'>服务报价</Text>
         <View className='price-row'>
            <Text className='price-val' style={{ color: service.color }}>¥{service.price}</Text>
            <Text className='price-unit'>/ {service.unit} 起</Text>
         </View>
         <View className='tags'>
            {service.features && service.features.split('\n').map((feat: string, i: number) => (
                <View key={i} className='tag' style={{ 
                    background: `${service.color}11`,
                    color: service.color,
                    border: `1px solid ${service.color}66`
                }}>
                  <Text>{feat}</Text>
                </View>
            ))}
         </View>
      </View>

      <View className='bottom-bar'>
        <Button 
          className='btn-buy' 
          style={{ background: service.color }}
          onClick={() => setModalVisible(true)}
        >
          立即咨询 / 购买
        </Button>
      </View>

      {/* Modal Layer */}
      {modalVisible && (
        <View className='modal-mask' onClick={() => setModalVisible(false)} />
      )}
      <View className={`modal-content ${modalVisible ? 'visible' : ''}`}>
         <Text className='modal-title'>咨询/购买</Text>
         <Text className='modal-desc'>请填写您的联系方式，我们将尽快联系您</Text>
         
         <View className='form-item'>
            <Text className='label'>您的姓名 *</Text>
            <Input className='input' placeholder='请输入姓名' value={formData.customer_name} onInput={(e) => handleInput('customer_name', e.detail.value)} />
         </View>
         <View className='form-item'>
            <Text className='label'>联系电话 *</Text>
            <Input className='input' type='number' placeholder='请输入电话' value={formData.phone_number} onInput={(e) => handleInput('phone_number', e.detail.value)} />
         </View>
         <View className='form-item'>
            <Text className='label'>需求描述</Text>
            <Textarea className='textarea' placeholder='请简单描述您的需求...' value={formData.requirements} onInput={(e) => handleInput('requirements', e.detail.value)} />
         </View>

         <View className='modal-actions'>
            <Button className='btn-cancel' onClick={() => setModalVisible(false)}>取消</Button>
            <Button className='btn-submit' onClick={handleSubmit}>提交需求</Button>
         </View>
      </View>
    </View>
  )
}
