import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:krow_domain/krow_domain.dart';

import 'package:flutter_bloc/flutter_bloc.dart';
import '../../blocs/shifts/shifts_bloc.dart';
import '../my_shift_card.dart';
import '../shared/empty_state_view.dart';

class FindShiftsTab extends StatefulWidget {
  final List<Shift> availableJobs;

  const FindShiftsTab({super.key, required this.availableJobs});

  @override
  State<FindShiftsTab> createState() => _FindShiftsTabState();
}

class _FindShiftsTabState extends State<FindShiftsTab> {
  String _searchQuery = '';
  String _jobType = 'all';

  Widget _buildFilterTab(String id, String label) {
    final isSelected = _jobType == id;
    return GestureDetector(
      onTap: () => setState(() => _jobType = id),
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: UiConstants.space4,
          vertical: UiConstants.space2,
        ),
        decoration: BoxDecoration(
          color: isSelected ? UiColors.primary : UiColors.white,
          borderRadius: UiConstants.radiusFull,
          border: Border.all(
            color: isSelected ? UiColors.primary : UiColors.border,
          ),
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: (isSelected
              ? UiTypography.footnote2m.white
              : UiTypography.footnote2m.textSecondary),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // Filter logic
    final filteredJobs = widget.availableJobs.where((s) {
      final matchesSearch =
          s.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          s.location.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          s.clientName.toLowerCase().contains(_searchQuery.toLowerCase());

      if (!matchesSearch) return false;

      if (_jobType == 'all') return true;
      if (_jobType == 'one-day') {
        return s.durationDays == null || s.durationDays! <= 1;
      }
      if (_jobType == 'multi-day') {
        return s.durationDays != null && s.durationDays! > 1;
      }
      return true;
    }).toList();

    return Column(
      children: [
        // Search and Filters
        Container(
          color: UiColors.white,
          padding: const EdgeInsets.symmetric(
            horizontal: UiConstants.space5,
            vertical: UiConstants.space4,
          ),
          child: Column(
            children: [
              // Search Bar
              Row(
                children: [
                  Expanded(
                    child: Container(
                      height: 48,
                      padding: const EdgeInsets.symmetric(
                        horizontal: UiConstants.space3,
                      ),
                      decoration: BoxDecoration(
                        color: UiColors.background,
                        borderRadius: BorderRadius.circular(
                          UiConstants.radiusBase,
                        ),
                        border: Border.all(color: UiColors.border),
                      ),
                      child: Row(
                        children: [
                          const Icon(
                            UiIcons.search,
                            size: 20,
                            color: UiColors.textInactive,
                          ),
                          const SizedBox(width: UiConstants.space2),
                          Expanded(
                            child: TextField(
                              onChanged: (v) =>
                                  setState(() => _searchQuery = v),
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Search jobs, location...",
                                hintStyle: UiTypography.body2r.textPlaceholder,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: UiConstants.space2),
                  Container(
                    height: 48,
                    width: 48,
                    decoration: BoxDecoration(
                      color: UiColors.white,
                      borderRadius: BorderRadius.circular(
                        UiConstants.radiusBase,
                      ),
                      border: Border.all(color: UiColors.border),
                    ),
                    child: const Icon(
                      UiIcons.filter,
                      size: 18,
                      color: UiColors.textSecondary,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: UiConstants.space4),
              // Filter Tabs
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    _buildFilterTab('all', 'All Jobs'),
                    const SizedBox(width: UiConstants.space2),
                    _buildFilterTab('one-day', 'One Day'),
                    const SizedBox(width: UiConstants.space2),
                    _buildFilterTab('multi-day', 'Multi-Day'),
                    const SizedBox(width: UiConstants.space2),
                    _buildFilterTab('long-term', 'Long Term'),
                  ],
                ),
              ),
            ],
          ),
        ),

        Expanded(
          child: filteredJobs.isEmpty
              ? const EmptyStateView(
                  icon: UiIcons.search,
                  title: "No jobs available",
                  subtitle: "Check back later",
                )
              : SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(
                    horizontal: UiConstants.space5,
                  ),
                  child: Column(
                    children: [
                      const SizedBox(height: UiConstants.space5),
                      ...filteredJobs.map(
                        (shift) => Padding(
                          padding: const EdgeInsets.only(
                            bottom: UiConstants.space3,
                          ),
                          child: MyShiftCard(
                            shift: shift,
                            onAccept: () {
                              context.read<ShiftsBloc>().add(
                                AcceptShiftEvent(shift.id),
                              );
                              UiSnackbar.show(
                                context,
                                message:
                                    "Shift application submitted!", // Todo: Localization
                                type: UiSnackbarType.success,
                              );
                            },
                          ),
                        ),
                      ),
                      const SizedBox(height: UiConstants.space32),
                    ],
                  ),
                ),
        ),
      ],
    );
  }
}
