/**
 * 员工端底部导航栏
 */

import { useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { DollarSign, FileText, ScrollText, LogOut, PenTool, ClipboardList, KeyRound, UserCircle } from 'lucide-react'
import { toast } from 'sonner'
import { portalApi } from '../../lib/api-services'
import Modal from '../../components/ui/Modal'
import Button from '../../components/ui/Button'
import { Input, Label } from '../../components/ui/Input'

const navItems = [
  { path: '/portal/payslip', label: '工资条', icon: DollarSign },
  { path: '/portal/contract', label: '我的合同', icon: FileText },
  { path: '/portal/esign', label: '电子签署', icon: PenTool },
  { path: '/portal/policies', label: '规章制度', icon: ScrollText },
  { path: '/portal/records', label: '我的记录', icon: ClipboardList },
  { path: '/portal/profile', label: '个人资料', icon: UserCircle },
]

export default function PortalNav() {
  const location = useLocation()
  const navigate = useNavigate()
  const [showPwdModal, setShowPwdModal] = useState(false)
  const [oldPwd, setOldPwd] = useState('')
  const [newPwd, setNewPwd] = useState('')
  const [confirmPwd, setConfirmPwd] = useState('')
  const [pwdLoading, setPwdLoading] = useState(false)

  const handleLogout = () => {
    localStorage.removeItem('portalToken')
    localStorage.removeItem('portalEmployee')
    navigate('/portal/login')
  }

  /** 修改密码 */
  const handleChangePassword = async () => {
    if (!oldPwd || !newPwd || !confirmPwd) {
      toast.error('请填写所有字段')
      return
    }
    if (newPwd.length < 6) {
      toast.error('新密码至少6位')
      return
    }
    if (newPwd !== confirmPwd) {
      toast.error('两次输入的新密码不一致')
      return
    }
    setPwdLoading(true)
    try {
      const data: any = await portalApi.changePassword(oldPwd, newPwd)
      toast.success(data?.message || '密码修改成功')
      setShowPwdModal(false)
      setOldPwd(''); setNewPwd(''); setConfirmPwd('')
    } catch (err: any) {
      toast.error(err?.response?.data?.error?.message || '修改失败')
    } finally {
      setPwdLoading(false)
    }
  }

  return (
    <>
      <div className="flex items-center justify-between mb-6 pb-3 border-b border-gray-200">
        <div className="flex items-center gap-4">
          {navItems.map((item) => {
            const Icon = item.icon
            const active = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                className={`flex items-center gap-1 text-sm ${active ? 'text-primary font-medium' : 'text-gray-500 hover:text-gray-700'}`}
              >
                <Icon className="w-4 h-4" />
                {item.label}
              </Link>
            )
          })}
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowPwdModal(true)}
            className="flex items-center gap-1 text-sm text-gray-400 hover:text-gray-600"
          >
            <KeyRound className="w-4 h-4" />
            修改密码
          </button>
          <button
            onClick={handleLogout}
            className="flex items-center gap-1 text-sm text-gray-400 hover:text-gray-600"
          >
            <LogOut className="w-4 h-4" />
            退出
          </button>
        </div>
      </div>

      {/* 修改密码弹窗 */}
      {showPwdModal && (
        <Modal open onClose={() => setShowPwdModal(false)} title="修改密码">
          <div className="space-y-3">
            <div>
              <Label>旧密码</Label>
              <Input type="password" value={oldPwd} onChange={(e) => setOldPwd(e.target.value)} placeholder="请输入旧密码" />
            </div>
            <div>
              <Label>新密码</Label>
              <Input type="password" value={newPwd} onChange={(e) => setNewPwd(e.target.value)} placeholder="至少6位" />
            </div>
            <div>
              <Label>确认新密码</Label>
              <Input type="password" value={confirmPwd} onChange={(e) => setConfirmPwd(e.target.value)} placeholder="再次输入新密码" />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="secondary" onClick={() => setShowPwdModal(false)}>取消</Button>
              <Button onClick={handleChangePassword} disabled={pwdLoading}>
                {pwdLoading ? '修改中...' : '确认修改'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </>
  )
}
