
import React, { createContext, useContext, useState, ReactNode } from 'react';
import { EventData, EventStatus, EventType, Attachment } from '../types';

// Initial Mock Data
const INITIAL_EVENTS: EventData[] = [
  {
    id: '1',
    name: 'Casamento Juliana & Marcos',
    date: '2024-10-15',
    time: '16:00',
    type: EventType.WEDDING,
    status: EventStatus.CONFIRMED,
    address: {
      street: 'Av. das Hortênsias',
      number: '1200',
      city: 'Gramado',
      state: 'RS',
      zip: '95670-000'
    },
    briefing: 'Cerimônia ao pôr do sol. Foco em fotos espontâneas dos noivos e pais.',
    coverImage: 'https://picsum.photos/id/1059/800/400',
    contacts: [{ id: 'c1', name: 'Cerimonial Silva', role: 'Cerimonialista', phone: '9999-9999', email: 'c@teste.com'}],
    checklist: [],
    attachments: [
        { name: 'Ensaio 1', size: '2mb', type: 'image/jpeg', url: 'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=400&q=80' },
        { name: 'Ensaio 2', size: '2mb', type: 'image/jpeg', url: 'https://images.unsplash.com/photo-1511285560982-1351cdeb9821?auto=format&fit=crop&w=400&q=80' }
    ],
    ownerId: 'client-1',
    photographerIds: ['photographer-1']
  },
  {
    id: '2',
    name: 'Conferência Tech Innovators',
    date: '2024-11-05',
    time: '08:00',
    type: EventType.CORPORATE,
    status: EventStatus.PENDING_APPROVAL,
    address: {
      street: 'Rua Olimpíadas',
      number: '205',
      city: 'São Paulo',
      state: 'SP',
      zip: '04551-000'
    },
    briefing: 'Cobrir palestras principais e networking no coffee break.',
    coverImage: 'https://picsum.photos/id/3/800/400',
    contacts: [],
    checklist: [],
    attachments: [],
    ownerId: 'client-2', // Other client
    photographerIds: []
  }
];

interface DataContextType {
  events: EventData[];
  addEvent: (event: EventData) => void;
  updateEventStatus: (id: string, status: EventStatus) => void;
  assignPhotographer: (eventId: string, photographerId: string) => void;
  getEventsByRole: (userId: string, role: string) => EventData[];
  addAttachment: (eventId: string, attachment: Attachment) => void;
}

const DataContext = createContext<DataContextType | undefined>(undefined);

export const DataProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [events, setEvents] = useState<EventData[]>(INITIAL_EVENTS);

  const addEvent = (event: EventData) => {
    setEvents(prev => [event, ...prev]);
  };

  const updateEventStatus = (id: string, status: EventStatus) => {
    setEvents(prev => prev.map(e => e.id === id ? { ...e, status } : e));
  };

  const assignPhotographer = (eventId: string, photographerId: string) => {
    setEvents(prev => prev.map(e => {
        if (e.id === eventId) {
            const current = e.photographerIds || [];
            if (!current.includes(photographerId)) {
                return { ...e, photographerIds: [...current, photographerId] };
            }
        }
        return e;
    }));
  };

  const getEventsByRole = (userId: string, role: string) => {
    if (role === 'SUPERADMIN' || role === 'BUSINESS_OWNER') {
      return events;
    }
    if (role === 'EVENT_OWNER') {
      return events.filter(e => e.ownerId === userId);
    }
    if (role === 'PHOTOGRAPHER') {
      return events.filter(e => e.photographerIds.includes(userId));
    }
    return [];
  };

  const addAttachment = (eventId: string, attachment: Attachment) => {
      setEvents(prev => prev.map(e => {
          if (e.id === eventId) {
              return { ...e, attachments: [...e.attachments, attachment] };
          }
          return e;
      }));
  };

  return (
    <DataContext.Provider value={{ events, addEvent, updateEventStatus, assignPhotographer, getEventsByRole, addAttachment }}>
      {children}
    </DataContext.Provider>
  );
};

export const useData = () => {
  const context = useContext(DataContext);
  if (!context) throw new Error('useData must be used within a DataProvider');
  return context;
};