use crate::services::calendar_service::CalendarInfo;
use chrono::{Local, NaiveDate, NaiveTime};
use yew::prelude::*;
use calendar_models::VAlarm;

#[derive(Clone, PartialEq, Debug)]
pub enum EventStatus {
    Confirmed,
    Tentative,
    Cancelled,
}

impl Default for EventStatus {
    fn default() -> Self {
        EventStatus::Confirmed
    }
}

#[derive(Clone, PartialEq, Debug)]
pub enum EventClass {
    Public,
    Private,
    Confidential,
}

impl Default for EventClass {
    fn default() -> Self {
        EventClass::Public
    }
}


#[derive(Clone, PartialEq, Debug)]
pub enum RecurrenceType {
    None,
    Daily,
    Weekly,
    Monthly,
    Yearly,
}

impl Default for RecurrenceType {
    fn default() -> Self {
        RecurrenceType::None
    }
}

#[derive(Clone, PartialEq)]
pub enum ModalTab {
    BasicDetails,
    Advanced,
    People,
    Categories,
    Location,
    Reminders,
}

impl Default for ModalTab {
    fn default() -> Self {
        ModalTab::BasicDetails
    }
}

// EditAction is now imported from event_context_menu - this duplicate removed

#[derive(Clone, PartialEq, Debug)]
pub struct EventCreationData {
    // Basic event info
    pub title: String,
    pub description: String,
    pub location: String,
    pub all_day: bool,
    
    // Timing
    pub start_date: NaiveDate,
    pub end_date: NaiveDate,
    pub start_time: NaiveTime,
    pub end_time: NaiveTime,
    
    // Classification
    pub status: EventStatus,
    pub class: EventClass,
    pub priority: Option<u8>,
    
    // People
    pub organizer: String,
    pub attendees: String,
    
    // Categorization
    pub categories: String,
    
    // Reminders/Alarms
    pub alarms: Vec<VAlarm>,
    
    // Recurrence
    pub recurrence: RecurrenceType,
    pub recurrence_interval: u32,
    pub recurrence_until: Option<NaiveDate>,
    pub recurrence_count: Option<u32>,
    pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat]
    
    // Advanced recurrence
    pub monthly_by_day: Option<String>, // e.g., "1MO" for first Monday
    pub monthly_by_monthday: Option<u8>, // e.g., 15 for 15th day of month
    pub yearly_by_month: Vec<bool>, // [Jan, Feb, Mar, ...] 
    
    // Calendar selection
    pub selected_calendar: Option<String>,
    
    // Edit tracking (for recurring events)
    pub edit_scope: Option<crate::components::EditAction>,
    pub changed_fields: Vec<String>,
    pub original_uid: Option<String>, // Set when editing existing events
    pub occurrence_date: Option<NaiveDate>, // The specific occurrence date being edited
}

impl EventCreationData {
    pub fn to_create_event_params(&self) -> (
        String, // title
        String, // description
        String, // start_date
        String, // start_time
        String, // end_date
        String, // end_time
        String, // location
        bool,   // all_day
        String, // status
        String, // class
        Option<u8>, // priority
        String, // organizer
        String, // attendees
        String, // categories
        Vec<VAlarm>, // alarms
        String, // recurrence
        Vec<bool>, // recurrence_days
        u32, // recurrence_interval
        Option<u32>, // recurrence_count
        Option<String>, // recurrence_until
        Option<String>, // calendar_path
        String, // timezone
    ) {
        
        // Use local date/times and timezone - no UTC conversion
        let effective_end_date = if self.all_day {
            // For all-day events, add one day to convert from inclusive to exclusive end date
            // (iCalendar spec requires exclusive end dates for all-day events)
            self.end_date + chrono::Duration::days(1)
        } else {
            self.end_date
        };
        
        // Get the local timezone
        let timezone = {
            use js_sys::Date;
            let date = Date::new_0();
            let timezone_offset = date.get_timezone_offset(); // Minutes from UTC
            let hours = -(timezone_offset as i32) / 60; // Convert to hours, negate for proper sign
            let minutes = (timezone_offset as i32).abs() % 60;
            format!("{:+03}:{:02}", hours, minutes) // Format as +05:00 or -04:00
        };
        
        let (start_date, start_time, end_date, end_time) = (
            self.start_date.format("%Y-%m-%d").to_string(),
            self.start_time.format("%H:%M").to_string(),
            effective_end_date.format("%Y-%m-%d").to_string(),
            self.end_time.format("%H:%M").to_string(),
        );
        
        (
            self.title.clone(),
            self.description.clone(),
            start_date,
            start_time,
            end_date,
            end_time,
            self.location.clone(),
            self.all_day,
            format!("{:?}", self.status).to_uppercase(),
            format!("{:?}", self.class).to_uppercase(),
            self.priority,
            self.organizer.clone(),
            self.attendees.clone(),
            self.categories.clone(),
            self.alarms.clone(),
            format!("{:?}", self.recurrence),
            self.recurrence_days.clone(),
            self.recurrence_interval,
            self.recurrence_count,
            self.recurrence_until.map(|d| d.format("%Y-%m-%d").to_string()),
            self.selected_calendar.clone(),
            timezone,
        )
    }
}

impl Default for EventCreationData {
    fn default() -> Self {
        let now_local = Local::now();
        let start_date = now_local.date_naive();
        let start_time = NaiveTime::from_hms_opt(9, 0, 0).unwrap_or_default();
        let end_time = NaiveTime::from_hms_opt(10, 0, 0).unwrap_or_default();

        Self {
            title: String::new(),
            description: String::new(),
            location: String::new(),
            all_day: false,
            start_date,
            end_date: start_date,
            start_time,
            end_time,
            status: EventStatus::default(),
            class: EventClass::default(),
            priority: None,
            organizer: String::new(),
            attendees: String::new(),
            categories: String::new(),
            alarms: Vec::new(),
            recurrence: RecurrenceType::default(),
            recurrence_interval: 1,
            recurrence_until: None,
            recurrence_count: None,
            recurrence_days: vec![false; 7],
            monthly_by_day: None,
            monthly_by_monthday: None,
            yearly_by_month: vec![false; 12],
            selected_calendar: None,
            edit_scope: None,
            changed_fields: vec![],
            original_uid: None,
            occurrence_date: None,
        }
    }
}

// Common props for all tab components
#[derive(Properties, PartialEq)]
pub struct TabProps {
    pub data: UseStateHandle<EventCreationData>,
    pub available_calendars: Vec<CalendarInfo>,
}