import {
  collection,
  doc,
  setDoc,
  deleteDoc,
  onSnapshot,
  query,
} from 'firebase/firestore';
import { db } from '../lib/firebase';

export interface TeamMember {
  id: string;
  name: string;
  role: string;
  bio: string;
  imageUrl: string;
  email: string;
  updatedAt?: string;
}

const TEAM_MEMBERS_COLLECTION = 'teamMembers';
const TEAM_STORAGE_KEY = 'timenlife_team_members';

export const DEFAULT_TEAM_MEMBERS: TeamMember[] = [
  {
    id: '1',
    name: 'Fatima Batool',
    role: 'CEO',
    bio: 'Leading Time N Life with a visionary focus on luxury, customer trust, and operational excellence across Pakistan.',
    imageUrl: '',
    email: 'fatima@timenlife.com',
  },
  {
    id: '2',
    name: 'Eisha tir Raazia',
    role: 'Director Marketing',
    bio: 'Driving brand growth, innovative digital marketing campaigns, and community engagement for Time N Life.',
    imageUrl: '',
    email: 'eisha@timenlife.com',
  },
  {
    id: '3',
    name: 'Muhammad Ahmad',
    role: 'Director Sales',
    bio: 'Spearheading nationwide sales strategies, customer satisfaction, and retail partner relations.',
    imageUrl: '',
    email: 'ahmad@timenlife.com',
  },
  {
    id: '4',
    name: 'Azaan Ali',
    role: 'Director Technical Operations',
    bio: 'Overseeing high-performance e-commerce architecture, system security, and technical infrastructure.',
    imageUrl: '',
    email: 'azaan@timenlife.com',
  },
  {
    id: '5',
    name: 'Muhammad Ali',
    role: 'Director Monitoring',
    bio: 'Ensuring strict quality control, order accuracy, fulfillment logistics, and customer metrics.',
    imageUrl: '',
    email: 'ali@timenlife.com',
  },
  {
    id: '6',
    name: 'Mobeen Ahmad',
    role: 'Director HR',
    bio: 'Building an inspiring work culture, talent recruitment, and collaborative team growth.',
    imageUrl: '',
    email: 'mobeen@timenlife.com',
  },
];

let inMemoryTeam: TeamMember[] = [];

export function getStoredTeamMembers(): TeamMember[] {
  if (inMemoryTeam.length > 0) return inMemoryTeam;
  if (typeof window === 'undefined') return DEFAULT_TEAM_MEMBERS;
  try {
    const raw = localStorage.getItem(TEAM_STORAGE_KEY);
    if (!raw) return DEFAULT_TEAM_MEMBERS;
    const parsed = JSON.parse(raw) as TeamMember[];
    if (!Array.isArray(parsed) || parsed.length === 0) return DEFAULT_TEAM_MEMBERS;
    inMemoryTeam = parsed;
    return parsed;
  } catch (e) {
    return DEFAULT_TEAM_MEMBERS;
  }
}

export function saveTeamMembersLocal(list: TeamMember[]): void {
  inMemoryTeam = list;
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(TEAM_STORAGE_KEY, JSON.stringify(list));
  } catch (e) {
    console.warn('LocalStorage error:', e);
  }
}

export function subscribeToTeamMembers(callback: (members: TeamMember[]) => void): () => void {
  // Immediately return current cached members
  callback(getStoredTeamMembers());

  try {
    const q = query(collection(db, TEAM_MEMBERS_COLLECTION));
    const unsub = onSnapshot(
      q,
      (snapshot) => {
        if (!snapshot.empty) {
          const fireMembers: TeamMember[] = [];
          snapshot.forEach((docSnap) => {
            const data = docSnap.data() as TeamMember;
            fireMembers.push({
              id: docSnap.id || data.id,
              name: data.name || '',
              role: data.role || '',
              bio: data.bio || '',
              imageUrl: data.imageUrl || '',
              email: data.email || '',
              updatedAt: data.updatedAt || new Date().toISOString(),
            });
          });

          // Maintain order or sort by id
          fireMembers.sort((a, b) => {
            const numA = parseInt(a.id, 10);
            const numB = parseInt(b.id, 10);
            if (!isNaN(numA) && !isNaN(numB)) return numA - numB;
            return a.id.localeCompare(b.id);
          });

          saveTeamMembersLocal(fireMembers);
          callback(fireMembers);
        } else {
          // If collection is empty in Firebase, sync initial list to Firebase
          saveTeamMembersToFirebase(DEFAULT_TEAM_MEMBERS).catch(() => {});
        }
      },
      (err) => {
        console.warn('Firestore teamMembers subscription error:', err);
        callback(getStoredTeamMembers());
      }
    );
    return unsub;
  } catch (err) {
    console.warn('Failed subscribing to teamMembers in Firebase:', err);
    return () => {};
  }
}

export async function saveTeamMembersToFirebase(members: TeamMember[]): Promise<void> {
  const now = new Date().toISOString();
  saveTeamMembersLocal(members);

  // 1. Save to Firebase Firestore
  try {
    for (const m of members) {
      const docId = m.id || String(Date.now());
      const docRef = doc(db, TEAM_MEMBERS_COLLECTION, docId);
      await setDoc(
        docRef,
        {
          id: docId,
          name: m.name || '',
          role: m.role || '',
          bio: m.bio || '',
          imageUrl: m.imageUrl || '',
          email: m.email || '',
          updatedAt: now,
        },
        { merge: true }
      );
    }
  } catch (err) {
    console.warn('Error saving team members to Firebase Firestore:', err);
  }

  // 2. Dual-save to backend API server for disk sync redundancy
  try {
    await fetch('/api/team-members', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ members }),
    });
  } catch (e) {
    console.warn('Error syncing team members to backend API:', e);
  }
}
