import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { supabase } from '../supabase/client';
import type { Profile, Company, UserRole, AuthState } from '../types';
import { encryptPhone, decryptPhone } from '../utils/crypto';

interface RegisterData {
  username: string;
  password: string;
  displayName: string;
  companyName: string;
  phone: string;
  role: UserRole;
}

interface AuthContextType {
  auth: AuthState;
  login: (username: string, password: string) => Promise<boolean>;
  register: (data: RegisterData) => Promise<{ success: boolean; error?: string }>;
  logout: () => Promise<void>;
  selectRole: (role: UserRole) => void;
  loading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [auth, setAuth] = useState<AuthState>({
    isLoggedIn: false,
    user: null,
    company: null,
    currentRole: null
  });
  const [loading, setLoading] = useState(true);

  // 初始化：检查已有 session
  useEffect(() => {
    const initAuth = async () => {
      const { data: { session } } = await supabase.auth.getSession();
      if (session?.user) {
        const { data: profile } = await supabase
          .from('profiles')
          .select('*')
          .eq('id', session.user.id)
          .maybeSingle();

        if (profile) {
          let company: Company | null = null;
          if (profile.company_id) {
            const { data: comp } = await supabase
              .from('companies')
              .select('*')
              .eq('id', profile.company_id)
              .maybeSingle();
            company = comp;
          }
          setAuth({
            isLoggedIn: true,
            user: profile,
            company,
            currentRole: company?.role || null
          });
        }
      }
      setLoading(false);
    };
    initAuth();

    // 监听 auth 状态变化
    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      if (event === 'SIGNED_IN' && session?.user) {
        setTimeout(async () => {
          const { data: profile } = await supabase
            .from('profiles')
            .select('*')
            .eq('id', session.user.id)
            .maybeSingle();

          if (profile) {
            let company: Company | null = null;
            if (profile.company_id) {
              const { data: comp } = await supabase
                .from('companies')
                .select('*')
                .eq('id', profile.company_id)
                .maybeSingle();
              company = comp;
            }
            setAuth({
              isLoggedIn: true,
              user: profile,
              company,
              currentRole: company?.role || null
            });
          }
        }, 0);
      } else if (event === 'SIGNED_OUT') {
        setAuth({
          isLoggedIn: false,
          user: null,
          company: null,
          currentRole: null
        });
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  const login = useCallback(async (username: string, password: string): Promise<boolean> => {
    const { error } = await supabase.auth.signInWithPassword({
      email: `${username}@meoo.local`,
      password,
    });
    if (error) {
      console.error('登录失败:', error.message);
      return false;
    }
    return true;
  }, []);

  const register = useCallback(async (data: RegisterData): Promise<{ success: boolean; error?: string }> => {
    try {
      // 1. 创建公司
      const { data: companyData, error: companyError } = await supabase
        .from('companies')
        .insert({
          name: data.companyName,
          role: data.role,
          contact_phone: data.phone
        })
        .select()
        .single();

      if (companyError || !companyData) {
        console.error('创建公司失败:', companyError?.message);
        return { success: false, error: '创建公司失败，请稍后重试' };
      }

      // 2. 注册用户
      const { data: authData, error: authError } = await supabase.auth.signUp({
        email: `${data.username}@meoo.local`,
        password: data.password,
      });

      if (authError || !authData.user) {
        console.error('注册失败:', authError?.message);
        // 回滚：删除创建的公司
        await supabase.from('companies').delete().eq('id', companyData.id);

        // 根据错误类型返回具体错误信息
        if (authError?.message?.includes('already registered') || authError?.message?.includes('already exists')) {
          return { success: false, error: '用户名已被注册，请更换用户名' };
        }
        if (authError?.message?.includes('password')) {
          return { success: false, error: '密码不符合要求，请使用至少6位字符' };
        }
        return { success: false, error: '注册失败：' + (authError?.message || '请检查信息后重试') };
      }

      // 3. 创建用户资料（手机号加密存储）
      const { error: profileError } = await supabase
        .from('profiles')
        .insert({
          id: authData.user.id,
          username: data.username,
          display_name: data.displayName,
          phone: encryptPhone(data.phone),
          company_id: companyData.id,
          is_master: true
        });

      if (profileError) {
        console.error('创建用户资料失败:', profileError.message);
        // 回滚：删除创建的公司
        await supabase.from('companies').delete().eq('id', companyData.id);

        if (profileError.message?.includes('unique constraint') || profileError.message?.includes('duplicate')) {
          return { success: false, error: '用户名已被使用，请更换用户名' };
        }
        return { success: false, error: '创建用户资料失败，请稍后重试' };
      }

      return { success: true };
    } catch (err: any) {
      console.error('注册过程出错:', err);
      return { success: false, error: '注册过程出错：' + (err?.message || '请稍后重试') };
    }
  }, []);

  const logout = useCallback(async () => {
    // 清除所有 cookie
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i];
      const eqPos = cookie.indexOf('=');
      const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
      // 设置过期时间为过去，删除 cookie
      document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
      document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${window.location.hostname};`;
    }

    // 清除 localStorage 和 sessionStorage 中的 Supabase 相关数据
    const storageKeys = Object.keys(localStorage);
    for (const key of storageKeys) {
      if (key.startsWith('sb-') || key.includes('supabase')) {
        localStorage.removeItem(key);
      }
    }

    const sessionKeys = Object.keys(sessionStorage);
    for (const key of sessionKeys) {
      if (key.startsWith('sb-') || key.includes('supabase')) {
        sessionStorage.removeItem(key);
      }
    }

    // 清除免密登录和记住密码相关存储
    localStorage.removeItem('saved_username');
    localStorage.removeItem('saved_password');
    localStorage.removeItem('auto_login');
    localStorage.removeItem('auto_login_expiry');

    await supabase.auth.signOut();
    setAuth({
      isLoggedIn: false,
      user: null,
      company: null,
      currentRole: null
    });
  }, []);

  const selectRole = useCallback((role: UserRole) => {
    setAuth(prev => ({ ...prev, currentRole: role }));
  }, []);

  return (
    <AuthContext.Provider value={{ auth, login, register, logout, selectRole, loading }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) throw new Error('useAuth must be used within AuthProvider');
  return context;
}