import { useState } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useConfirm } from '../../hooks/useConfirm'
import { Settings as Plus, X } from 'lucide-react'
import PageGuide from '../../components/ui/PageGuide'
import { payrollApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label, Select } from '../../components/ui/Input'
import Modal from '../../components/ui/Modal'

const DATA_SOURCE_LABELS: Record<string, string> = {
  overtime: '加班记录',
  performance: '绩效记录',
  bonus: '奖金记录',
  deduction: '扣款记录',
}

// 金额格式化：保留两位小数 + 千分位

// ========== 薪酬模版管理 ==========

export function TemplateManager() {
  const queryClient = useQueryClient()
  const confirm = useConfirm()
  const [showForm, setShowForm] = useState(false)
  const [editingItem, setEditingItem] = useState<any>(null)
  const [form, setForm] = useState({
    name: '',
    code: '',
    type: 'INPUT' as 'INPUT' | 'CALCULATED',
    formula: '',
    calcType: 'FORMULA' as 'FORMULA' | 'SYSTEM',
    dataSource: '' as string,
    order: 99,
    isEditable: true,
  })

  const { data: items, isLoading } = useQuery<any[]>({
    queryKey: ['payslip-template'],
    queryFn: async () => {
      return await payrollApi.template()
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => payrollApi.removeTemplateItem(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['payslip-template'] })
      toast.success('已删除')
    },
    onError: () => toast.error('删除失败'),
  })

  const createMutation = useMutation({
    mutationFn: (data: any) => payrollApi.createTemplateItem(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['payslip-template'] })
      setShowForm(false)
      toast.success('已新增薪酬项')
    },
    onError: () => toast.error('新增失败'),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => payrollApi.updateTemplateItem(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['payslip-template'] })
      setShowForm(false)
      setEditingItem(null)
      toast.success('已更新')
    },
    onError: () => toast.error('更新失败'),
  })

  /** 打开新增表单 */
  const handleAdd = () => {
    setEditingItem(null)
    setForm({ name: '', code: '', type: 'INPUT', formula: '', calcType: 'FORMULA', dataSource: '', order: items?.length ? items.length + 1 : 99, isEditable: true })
    setShowForm(true)
  }

  /** 打开编辑表单 */
  const handleEdit = (item: any) => {
    setEditingItem(item)
    setForm({
      name: item.name,
      code: item.code,
      type: item.type,
      formula: item.formula || '',
      calcType: item.calcType || 'FORMULA',
      dataSource: item.dataSource || '',
      order: item.order,
      isEditable: item.isEditable,
    })
    setShowForm(true)
  }

  /** 提交表单 */
  const handleSubmit = () => {
    if (!form.name.trim() || !form.code.trim()) {
      toast.error('名称和字段代码不能为空')
      return
    }
    const payload: any = {
      name: form.name.trim(),
      type: form.type,
      formula: form.type === 'CALCULATED' ? form.formula.trim() || null : null,
      calcType: form.type === 'CALCULATED' ? form.calcType : 'FORMULA',
      dataSource: form.dataSource || null,
      order: Number(form.order),
      isEditable: form.isEditable,
    }
    if (editingItem) {
      updateMutation.mutate({ id: editingItem.id, data: payload })
    } else {
      createMutation.mutate({ ...payload, code: form.code.trim() })
    }
  }

  return (
    <div className="space-y-3">
      <Card>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-sm font-medium">薪酬结构模版</h2>
            <span className="text-xs text-gray-500">定义薪酬项和计算关系</span>
          </div>
          <Button size="sm" onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-1" />新增薪酬项
          </Button>
        </div>
        {isLoading ? (
          <div className="text-center py-4 text-gray-500">加载中...</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-left text-xs text-gray-500">
                  <th className="py-2 px-2 w-10">序号</th>
                  <th className="py-2 px-2 w-24">名称</th>
                  <th className="py-2 px-2 w-32">字段代码</th>
                  <th className="py-2 px-2 w-20">类型</th>
                  <th className="py-2 px-2 w-24">计算方式</th>
                  <th className="py-2 px-2 w-24">数据来源</th>
                  <th className="py-2 px-2 w-48">计算公式</th>
                  <th className="py-2 px-2 w-16">可编辑</th>
                  <th className="py-2 px-2 text-right w-24">操作</th>
                </tr>
              </thead>
              <tbody>
                {items?.map((item: any) => (
                  <tr key={item.id} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="py-2 px-2 text-gray-500">{item.order}</td>
                    <td className="py-2 px-2 text-sm font-medium whitespace-nowrap">{item.name}</td>
                    <td className="py-2 px-2 text-gray-500 font-mono whitespace-nowrap">{item.code}</td>
                    <td className="py-2 px-2">
                      <span className={`px-2 py-0.5 rounded text-xs whitespace-nowrap ${item.type === 'INPUT' ? 'bg-blue-50 text-blue-600' : 'bg-purple-50 text-purple-600'}`}>
                        {item.type === 'INPUT' ? '输入项' : '计算项'}
                      </span>
                    </td>
                    <td className="py-2 px-2">
                      {item.type === 'CALCULATED' && (
                        <span className={`px-2 py-0.5 rounded text-xs whitespace-nowrap ${(item.calcType || 'FORMULA') === 'SYSTEM' ? 'bg-amber-50 text-amber-600' : 'bg-teal-50 text-teal-600'}`}>
                          {(item.calcType || 'FORMULA') === 'SYSTEM' ? '系统计算' : '公式计算'}
                        </span>
                      )}
                    </td>
                    <td className="py-2 px-2">
                      {item.dataSource ? (
                        <span className="px-2 py-0.5 rounded text-xs whitespace-nowrap bg-cyan-50 text-cyan-600">
                          {DATA_SOURCE_LABELS[item.dataSource] || item.dataSource}
                        </span>
                      ) : (
                        <span className="text-xs text-gray-400">手动填写</span>
                      )}
                    </td>
                    <td className="py-2 px-2 text-gray-500 font-mono text-xs max-w-48 truncate" title={item.formula || ''}>{item.formula || '—'}</td>
                    <td className="py-2 px-2">
                      <span className={`text-xs ${item.isEditable ? 'text-safe' : 'text-gray-500'}`}>
                        {item.isEditable ? '可编辑' : '不可编辑'}
                      </span>
                    </td>
                    <td className="py-2 px-2">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleEdit(item)}
                          className="text-xs text-gray-500 hover:text-primary"
                        >
                          编辑
                        </button>
                        {!item.isDefault && (
                          <button
                            onClick={async () => {
                              if (await confirm({ title: '删除薪酬项', message: `确认删除薪酬项「${item.name}」？` })) {
                                deleteMutation.mutate(item.id)
                              }
                            }}
                            className="text-xs text-gray-500 hover:text-danger"
                          >
                            删除
                          </button>
                        )}
                        {item.isDefault && <span className="text-xs text-gray-300">预置</span>}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <p className="text-xs text-gray-500 mt-3">
          预置项为系统默认薪酬结构，不可删除。计算项的公式支持引用其他字段进行自动计算。
        </p>
      </Card>

      {/* 新增/编辑弹窗 */}
      {showForm && (
        <Modal open onClose={() => { setShowForm(false); setEditingItem(null) }}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="font-medium">{editingItem ? '编辑薪酬项' : '新增薪酬项'}</h3>
              <button onClick={() => { setShowForm(false); setEditingItem(null) }} className="text-gray-500 hover:text-gray-700">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-3">
              <div>
                <Label>名称</Label>
                <Input
                  type="text"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="如：交通补贴"
                />
              </div>
              <div>
                <Label>字段代码</Label>
                <Input
                  type="text"
                  value={form.code}
                  onChange={(e) => setForm({ ...form, code: e.target.value })}
                  placeholder="如：transportAllowance"
                  disabled={!!editingItem}
                />
                {editingItem && (
                  <p className="text-xs text-gray-500 mt-1">字段代码创建后不可修改</p>
                )}
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label>类型</Label>
                  <Select
                    value={form.type}
                    onChange={(e) => setForm({ ...form, type: e.target.value as 'INPUT' | 'CALCULATED' })}
                    disabled={!!editingItem}
                  >
                    <option value="INPUT">输入项（手动填写）</option>
                    <option value="CALCULATED">计算项（公式自动计算）</option>
                  </Select>
                </div>
                <div>
                  <Label>排序</Label>
                  <Input
                    type="number"
                    value={form.order}
                    onChange={(e) => setForm({ ...form, order: Number(e.target.value) })}
                  />
                </div>
              </div>
              {form.type === 'CALCULATED' && (
                <div className="space-y-2">
                  <div>
                    <Label>计算方式</Label>
                    <Select
                      value={form.calcType}
                      onChange={(e) => setForm({ ...form, calcType: e.target.value as 'FORMULA' | 'SYSTEM' })}
                      disabled={!!editingItem && editingItem.isDefault}
                    >
                      <option value="FORMULA">公式计算（加减乘除表达式）</option>
                      <option value="SYSTEM">系统计算（社保/公积金/个税等）</option>
                    </Select>
                    {editingItem && editingItem.isDefault && (
                      <p className="text-xs text-gray-500 mt-1">预置项的计算方式不可修改</p>
                    )}
                  </div>
                  <div>
                    <Label>{form.calcType === 'SYSTEM' ? '系统函数标识' : '计算公式'}</Label>
                    <Input
                      type="text"
                      value={form.formula}
                      onChange={(e) => setForm({ ...form, formula: e.target.value })}
                      placeholder={form.calcType === 'SYSTEM' ? '如：SOCIAL_EMP' : '如：baseSalary + overtimePay + allowance - deduction'}
                      disabled={!!editingItem && editingItem.isDefault && form.calcType === 'SYSTEM'}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {form.calcType === 'SYSTEM'
                        ? '系统计算标识：SOCIAL_EMP（个人社保）、HOUSING_EMP（个人公积金）、TAX（个税）'
                        : '可引用其他字段代码进行加减乘除运算，支持 min()、max()、round() 函数'}
                    </p>
                  </div>
                </div>
              )}
              {form.type === 'INPUT' && (
                <div>
                  <Label>数据来源</Label>
                  <Select
                    value={form.dataSource}
                    onChange={(e) => setForm({ ...form, dataSource: e.target.value })}
                  >
                    <option value="">手动填写</option>
                    <option value="overtime">加班记录（从加班系统获取）</option>
                    <option value="performance">绩效记录（从绩效系统获取）</option>
                    <option value="bonus">奖金记录（从奖金系统导入）</option>
                    <option value="deduction">扣款记录（从扣款系统导入）</option>
                  </Select>
                  <p className="text-xs text-gray-500 mt-1">选择外部数据来源后，发薪批次中会显示对应的"获取"按钮</p>
                </div>
              )}
              <div>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.isEditable}
                    onChange={(e) => setForm({ ...form, isEditable: e.target.checked })}
                  />
                  <span className="text-sm">发薪批次中可手动编辑</span>
                </label>
              </div>
            </div>

            <div className="flex gap-2">
              <Button
                onClick={handleSubmit}
                disabled={createMutation.isPending || updateMutation.isPending}
                className="flex-1"
              >
                {createMutation.isPending || updateMutation.isPending ? '保存中...' : editingItem ? '保存修改' : '确认新增'}
              </Button>
              <Button variant="secondary" onClick={() => { setShowForm(false); setEditingItem(null) }}>
                取消
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
