import React, { useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  X,
  Camera,
  Users,
  BookOpen,
  MessageSquare,
  Info,
  LogOut,
  Building2,
  Factory,
  Droplets
} from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { http } from '../api';

export type AccountRole = 'purchaser' | 'textile' | 'washing';

interface AccountProfileCardProps {
  isOpen: boolean;
  onClose: () => void;
  role: AccountRole;
  onShowUserManual: () => void;
  onShowFeedback: () => void;
  onShowAbout: () => void;
}

const roleThemeConfig = {
  purchaser: {
    headerGradient: 'from-amber-500 to-orange-500',
    avatarGradient: 'from-amber-500 to-orange-500',
    badgeBg: 'bg-amber-100',
    badgeText: 'text-amber-700',
    menuIconBg: 'bg-amber-100',
    menuIconText: 'text-amber-600',
    defaultIcon: Building2,
    defaultCompanyName: '采购商'
  },
  textile: {
    headerGradient: 'from-emerald-500 to-green-600',
    avatarGradient: 'from-emerald-500 to-green-600',
    badgeBg: 'bg-emerald-100',
    badgeText: 'text-emerald-700',
    menuIconBg: 'bg-emerald-100',
    menuIconText: 'text-emerald-600',
    defaultIcon: Factory,
    defaultCompanyName: '纺织厂'
  },
  washing: {
    headerGradient: 'from-violet-400 to-fuchsia-400',
    avatarGradient: 'from-violet-400 to-fuchsia-400',
    badgeBg: 'bg-violet-100',
    badgeText: 'text-violet-600',
    menuIconBg: 'bg-violet-100',
    menuIconText: 'text-violet-600',
    defaultIcon: Droplets,
    defaultCompanyName: '水洗厂'
  }
};

export function AccountProfileCard({
  isOpen,
  onClose,
  role,
  onShowUserManual,
  onShowFeedback,
  onShowAbout
}: AccountProfileCardProps) {
  const navigate = useNavigate();
  const { auth, logout } = useAuth();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const theme = roleThemeConfig[role];
  const DefaultIcon = theme.defaultIcon;

  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!auth.user) return;

    try {
      // TODO: 头像上传接口待后端实现
      const formDataObj = new FormData();
      formDataObj.append('file', file);
      formDataObj.append('bucket', 'avatars');

      const res = await fetch('/api/v1/common/upload', {
        method: 'POST',
        body: formDataObj,
      });

      if (!res.ok) {
        alert('头像上传失败');
        return;
      }

      const json = await res.json();
      const publicUrl = json.data?.url || '';

      await http.patch('/auth/me', { image_url: publicUrl });

      window.location.reload();
    } catch (err) {
      alert('头像上传出错，请重试');
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  const menuItems = [
    {
      id: 'members',
      icon: Users,
      label: '账号管理',
      description: '管理团队成员和账户设置',
      onClick: () => { onClose(); navigate('/members'); }
    },
    {
      id: 'manual',
      icon: BookOpen,
      label: '用户手册',
      description: '查看详细使用指南',
      onClick: () => { onClose(); onShowUserManual(); }
    },
    {
      id: 'feedback',
      icon: MessageSquare,
      label: '用户反馈',
      description: '提交问题或建议',
      onClick: () => { onClose(); onShowFeedback(); }
    },
    {
      id: 'about',
      icon: Info,
      label: '关于',
      description: '版本信息与版权',
      onClick: () => { onClose(); onShowAbout(); }
    }
  ];

  return (
    <AnimatePresence>
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
          onClick={onClose}
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className="bg-white rounded-2xl w-full max-w-sm shadow-2xl overflow-hidden"
            onClick={e => e.stopPropagation()}
          >
            {/* 头部 */}
            <div className={`bg-gradient-to-r ${theme.headerGradient} p-6 text-white`}>
              <div className="flex items-center justify-between">
                <h2 className="text-xl font-bold">账户信息</h2>
                <button
                  onClick={onClose}
                  className="p-2 hover:bg-white/20 rounded-lg transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* 账户详情 */}
            <div className="p-6 space-y-4">
              {/* 用户信息 */}
              <div className="flex items-center gap-4">
                <label
                  className={`w-16 h-16 bg-gradient-to-br ${theme.avatarGradient} rounded-xl flex items-center justify-center shadow-lg cursor-pointer hover:opacity-90 transition-opacity overflow-hidden relative group`}
                >
                  {(auth.user as any)?.image_url ? (
                    <img
                      src={(auth.user as any).image_url}
                      alt="头像"
                      className="w-full h-full object-cover relative z-10"
                    />
                  ) : (
                    <DefaultIcon className="w-8 h-8 text-white relative z-10" />
                  )}
                  <div className="absolute inset-0 bg-black/30 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20">
                    <Camera className="w-5 h-5 text-white" />
                  </div>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleAvatarUpload}
                  />
                </label>
                <div>
                  <p className="font-semibold text-slate-900 text-lg truncate max-w-[200px]">
                    {(auth.user as any)?.display_name || auth.user?.username || '用户'}
                  </p>
                  <p className="text-sm text-slate-500">
                    {auth.company?.name || theme.defaultCompanyName}
                  </p>
                  <span className={`inline-flex items-center gap-1 text-xs ${theme.badgeBg} ${theme.badgeText} px-2 py-0.5 rounded-full mt-1`}>
                    {auth.user?.is_master ? '主账号' : '子账号'}
                  </span>
                </div>
              </div>

              {/* 功能菜单 */}
              <div className="space-y-2 pt-4 border-t border-slate-200">
                {menuItems.map((item) => (
                  <button
                    key={item.id}
                    onClick={item.onClick}
                    className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-left"
                  >
                    <div className={`w-10 h-10 ${theme.menuIconBg} rounded-lg flex items-center justify-center`}>
                      <item.icon className={`w-5 h-5 ${theme.menuIconText}`} />
                    </div>
                    <div>
                      <p className="font-medium text-slate-900">{item.label}</p>
                      <p className="text-xs text-slate-500">{item.description}</p>
                    </div>
                  </button>
                ))}
              </div>

              {/* 退出登录 */}
              <button
                onClick={handleLogout}
                className="w-full py-3 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl transition-colors flex items-center justify-center gap-2 font-medium"
              >
                <LogOut className="w-5 h-5" />
                退出登录
              </button>
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}
