import SwiftUI

struct Persona: Identifiable {
    let id = UUID()
    let name: String
    let description: String?
    let iconName: String
    
    init(name: String, description: String? = nil, iconName: String) {
        self.name = name
        self.description = description
        self.iconName = iconName
    }
}

enum PersonaTab: String, CaseIterable {
    case myPersonas = "My Personas"
    case favorites = "Favorites"
}

struct PersonasView: View {
    @Binding var isPresented: Bool
    @State private var selectedTab: PersonaTab = .myPersonas
    @State private var searchText: String = ""
    
    let onPersonaSelected: ((Persona) -> Void)?
    let onCreatePersona: (() -> Void)?
    
    init(
        isPresented: Binding<Bool>,
        onPersonaSelected: ((Persona) -> Void)? = nil,
        onCreatePersona: (() -> Void)? = nil
    ) {
        self._isPresented = isPresented
        self.onPersonaSelected = onPersonaSelected
        self.onCreatePersona = onCreatePersona
    }
    
    // Sample personas data
    private let samplePersonas = [
        Persona(name: "Kai", iconName: "persona-shape"),
        Persona(name: "Jani", description: "sounds like sza", iconName: "persona-shape"),
        Persona(name: "Baby timbo", description: "rnb vibes", iconName: "persona-shape"),
        Persona(name: "Zee", iconName: "persona-shape"),
        Persona(name: "Donald", iconName: "persona-shape"),
        Persona(name: "Jaykra", iconName: "persona-shape")
    ]
    
    private var filteredPersonas: [Persona] {
        if searchText.isEmpty {
            return samplePersonas
        } else {
            return samplePersonas.filter { persona in
                persona.name.localizedCaseInsensitiveContains(searchText) ||
                persona.description?.localizedCaseInsensitiveContains(searchText) ?? false
            }
        }
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // Drag Handle
            VStack(spacing: 12) {
                RoundedRectangle(cornerRadius: 100)
                    .fill(Constants.Colors.Background.Fog.thick)
                    .frame(width: 32, height: 4)
            }
            .frame(height: 16)
            .padding(.top, 16)
            
            // Content
            VStack(spacing: 16) {
                // Tab Navigation
                PersonaTabView(selectedTab: $selectedTab)
                
                // Search and Create Section
                HStack(spacing: 8) {
                    // Search Bar
                    HStack(spacing: 8) {
                        Image("Icon/search")
                            .resizable()
                            .renderingMode(.template)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .frame(width: 16, height: 16)
                        
                        TextField("Search", text: $searchText)
                            .font(Constants.Typography.small)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .placeholder(when: searchText.isEmpty) {
                                Text("Search")
                                    .font(Constants.Typography.small)
                                    .foregroundColor(Constants.Colors.Background.Fog.dense)
                            }
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)
                    .frame(height: 40)
                    .background(Constants.Colors.Background.Glass.thin)
                    .clipShape(RoundedRectangle(cornerRadius: 100))
                    
                    // Create Button
                    MediumButton(title: "Create", leftIconAssetName: "Icon/plus", variant: .secondary) {
                        onCreatePersona?()
                    }
                }
                
                // Personas List
                ScrollView {
                    LazyVStack(spacing: 0) {
                        ForEach(filteredPersonas) { persona in
                            PersonaCell(persona: persona) {
                                onPersonaSelected?(persona)
                            }
                            .padding(.horizontal, 0)
                        }
                    }
                }
            }
            .padding(.horizontal, 24)
            .padding(.bottom, 16)
    
        }
        .background(Constants.Colors.Background.secondary)
        .clipShape(RoundedRectangle(cornerRadius: 24))
        .ignoresSafeArea(.container, edges: .bottom)
    }
}

struct PersonaTabView: View {
    @Binding var selectedTab: PersonaTab
    
    var body: some View {
        HStack(spacing: 0) {
            ForEach(PersonaTab.allCases, id: \.self) { tab in
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        selectedTab = tab
                    }
                }) {
                    VStack(spacing: 0) {
                        Text(tab.rawValue)
                            .font(selectedTab == tab ? Constants.Typography.mediumTitle : Constants.Typography.mediumRegular)
                            .foregroundColor(selectedTab == tab ? Constants.Colors.Foreground.primary : Constants.Colors.Foreground.tertiary)
                            .tracking(0.32)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 16)
                        
                        // Bottom border for selected tab
                        Rectangle()
                            .fill(selectedTab == tab ? Constants.Colors.Foreground.primary : Color.clear)
                            .frame(height: 2)
                    }
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
        .overlay(
            Rectangle()
                .fill(Constants.Colors.Border.primary)
                .frame(height: 1),
            alignment: .bottom
        )
        .frame(height: 56)
    }
}

struct PersonaCell: View {
    let persona: Persona
    let onTap: () -> Void
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 8) {
                // Persona Icon - Using persona-shape mask with random artwork
                Image(randomArtwork(for: persona.name))
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 24, height: 24)
                    .mask(
                        Image("Icon/persona-shape")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 24, height: 24)
                    )
                
                // Name and Description
                VStack(alignment: .leading, spacing: 2) {
                    Text(persona.name)
                        .font(Constants.Typography.mediumRegular)
                        .foregroundColor(Constants.Colors.Foreground.primary)
                        .tracking(0.32)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    if let description = persona.description {
                        Text(description)
                            .font(Constants.Typography.xSmallRegular)
                            .foregroundColor(Constants.Colors.Foreground.secondary)
                            .tracking(0.24)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }
                }
                
                Spacer()
                
                // More Button
                Button(action: {
                    // Handle more options
                    print("More options for \(persona.name)")
                }) {
                    Image("Icon/more-horizontal")
                        .resizable()
                        .renderingMode(.template)
                        .foregroundColor(Constants.Colors.Foreground.tertiary)
                        .frame(width: 16, height: 16)
                }
                .buttonStyle(PlainButtonStyle())
            }
            .padding(.vertical, 16)
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    // Generate random artwork based on persona name for visual variety
    private func randomArtwork(for name: String) -> String {
        let hash = name.hashValue
        let artworkImages = [
            "Artwork/1", "Artwork/2", "Artwork/3", "Artwork/4", "Artwork/5", 
            "Artwork/6", "Artwork/7", "Artwork/8", "Artwork/9", "Artwork/10",
            "Artwork/11", "Artwork/12", "Artwork/13"
        ]
        return artworkImages[abs(hash) % artworkImages.count]
    }
}

// MARK: - TextField Placeholder Extension
extension View {
    func placeholder<Content: View>(
        when shouldShow: Bool,
        alignment: Alignment = .leading,
        @ViewBuilder placeholder: () -> Content) -> some View {
        
        ZStack(alignment: alignment) {
            placeholder().opacity(shouldShow ? 1 : 0)
            self
        }
    }
}

// MARK: - Convenience View Modifier
extension View {
    func personasSheet(
        isPresented: Binding<Bool>,
        detents: [PresentationDetent] = [.medium, .large],
        onPersonaSelected: ((Persona) -> Void)? = nil,
        onCreatePersona: (() -> Void)? = nil
    ) -> some View {
        self.sheet(isPresented: isPresented) {
            PersonasView(
                isPresented: isPresented,
                onPersonaSelected: onPersonaSelected,
                onCreatePersona: onCreatePersona
            )
            .presentationDetents(Set(detents))
            .presentationDragIndicator(.hidden)
            .presentationCornerRadius(24)
        }
    }
}

// MARK: - Preview
#Preview {
    @Previewable @State var isPresented = true
    
    Color.clear
        .personasSheet(
            isPresented: $isPresented,
            onPersonaSelected: { persona in
                print("Selected persona: \(persona.name)")
            },
            onCreatePersona: {
                print("Create new persona")
            }
        )
}
