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

interface Photographer {
  id: string;
  name: string;
  email: string;
  phone: string;
  avatar: string;
  specialties: string[];
  rating: number;
  eventsCompleted: number;
}

const MOCK_PHOTOGRAPHERS: Photographer[] = [
  {
    id: 'photographer-1',
    name: 'Ana Paula Silva',
    email: 'ana.silva@photum.com',
    phone: '(51) 99999-1234',
    avatar: 'https://i.pravatar.cc/150?img=5',
    specialties: ['Formaturas', 'Eventos Universitários', 'Colações de Grau'],
    rating: 4.9,
    eventsCompleted: 87
  },
  {
    id: 'photographer-2',
    name: 'Carlos Mendes',
    email: 'carlos.mendes@photum.com',
    phone: '(51) 99888-5678',
    avatar: 'https://i.pravatar.cc/150?img=12',
    specialties: ['Formaturas', 'Eventos Corporativos'],
    rating: 4.8,
    eventsCompleted: 65
  }
];

// Initial Mock Data
const INITIAL_INSTITUTIONS: Institution[] = [
  {
    id: 'inst-1',
    name: 'Universidade Federal do Rio Grande do Sul',
    type: 'Universidade Pública',
    phone: '(51) 3308-3333',
    email: 'eventos@ufrgs.br',
    address: {
      street: 'Av. Paulo Gama',
      number: '110',
      city: 'Porto Alegre',
      state: 'RS',
      zip: '90040-060'
    },
    description: 'Campus Central - Principais eventos realizados no Salão de Atos',
    ownerId: 'client-1'
  }
];

const INITIAL_EVENTS: EventData[] = [
  {
    id: '1',
    name: 'Formatura Medicina UFRGS',
    date: '2024-10-15',
    time: '19:00',
    type: EventType.GRADUATION,
    status: EventStatus.CONFIRMED,
    address: {
      street: 'Av. das Hortênsias',
      number: '1200',
      city: 'Gramado',
      state: 'RS',
      zip: '95670-000'
    },
    briefing: 'Cerimônia de formatura no Teatro Guaíra. Foco em fotos da colação de grau, formandos e familiares.',
    coverImage: 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?w=800&h=400&fit=crop',
    contacts: [{ id: 'c1', name: 'Cerimonial Silva', role: 'Cerimonialista', phone: '9999-9999', email: 'c@teste.com'}],
    checklist: [],
    ownerId: 'client-1',
    photographerIds: ['photographer-1'],
    institutionId: 'inst-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: [],
    ownerId: 'client-2', // Other client
    photographerIds: []
  }
];

interface DataContextType {
  events: EventData[];
  institutions: Institution[];
  photographers: Photographer[];
  addEvent: (event: EventData) => void;
  updateEventStatus: (id: string, status: EventStatus) => void;
  assignPhotographer: (eventId: string, photographerId: string) => void;
  getEventsByRole: (userId: string, role: string) => EventData[];
  addInstitution: (institution: Institution) => void;
  updateInstitution: (id: string, institution: Partial<Institution>) => void;
  getInstitutionsByUserId: (userId: string) => Institution[];
  getInstitutionById: (id: string) => Institution | undefined;
  getPhotographerById: (id: string) => Photographer | undefined;
}

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

export const DataProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [events, setEvents] = useState<EventData[]>(INITIAL_EVENTS);
  const [institutions, setInstitutions] = useState<Institution[]>(INITIAL_INSTITUTIONS);
  const [photographers] = useState<Photographer[]>(MOCK_PHOTOGRAPHERS);

  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 addInstitution = (institution: Institution) => {
    setInstitutions(prev => [...prev, institution]);
  };

  const updateInstitution = (id: string, updatedData: Partial<Institution>) => {
    setInstitutions(prev => prev.map(inst => 
      inst.id === id ? { ...inst, ...updatedData } : inst
    ));
  };

  const getInstitutionsByUserId = (userId: string) => {
    return institutions.filter(inst => inst.ownerId === userId);
  };

  const getInstitutionById = (id: string) => {
    return institutions.find(inst => inst.id === id);
  };

  const getPhotographerById = (id: string) => {
    return photographers.find(p => p.id === id);
  };

  return (
    <DataContext.Provider value={{ 
      events, 
      institutions,
      photographers,
      addEvent, 
      updateEventStatus, 
      assignPhotographer, 
      getEventsByRole, 
      addInstitution,
      updateInstitution,
      getInstitutionsByUserId,
      getInstitutionById,
      getPhotographerById
    }}>
      {children}
    </DataContext.Provider>
  );
};

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