import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:image_picker/image_picker.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/dropdownTheme.dart';

class AddManualAttendanceScreen extends StatefulWidget {
  const AddManualAttendanceScreen({super.key});

  @override
  State<AddManualAttendanceScreen> createState() =>
      _AddManualAttendanceScreenState();
}

class _AddManualAttendanceScreenState extends State<AddManualAttendanceScreen> {
  final TextEditingController dateController = TextEditingController();
  Dropdowntheme ddtheme = Dropdowntheme();

  // Separate controllers for each section
  final checkInTime = TextEditingController();
  final checkInLocation = TextEditingController();
  final checkInDescription = TextEditingController();
  XFile? checkInProof;

  final checkOutTime = TextEditingController();
  final checkOutLocation = TextEditingController();
  final checkOutDescription = TextEditingController();
  XFile? checkOutProof;

  final ImagePicker picker = ImagePicker();
  String? selectedType;
  final List<String> types = ["Check In", "Check Out", "Check In/Out"];
  DateTime? _date;

  bool get isSubmitEnabled {
    if (selectedType == "Check In") {
      return checkInLocation.text.trim().isNotEmpty;
    } else if (selectedType == "Check Out") {
      return checkOutLocation.text.trim().isNotEmpty;
    } else if (selectedType == "Check In/Out") {
      return checkInLocation.text.trim().isNotEmpty &&
          checkOutLocation.text.trim().isNotEmpty;
    }
    return false;
  }


  @override
  void initState() {
    super.initState();
    checkInLocation.addListener(() => setState(() {}));
    checkOutLocation.addListener(() => setState(() {}));
  }
  // ===== Print all submitted values =====
  void _submitForm() {
    print("===== Manual Attendance Submitted =====");
    print("Date: ${dateController.text}");
    print("Type: $selectedType");
    print("Time: ${checkInTime.text}");
    print("Location: ${checkInLocation.text}");
    print("Description: ${checkInDescription.text}");
    print("Proof: ${checkInProof != null ? checkOutProof!.path : 'No file attached'}");
    print("=======================================");
    print("Date: ${dateController.text}");
    print("Type: $selectedType");
    print("Time: ${checkOutTime.text}");
    print("Location: ${checkOutLocation.text}");
    print("Description: ${checkOutDescription.text}");
    print("Proof: ${checkInProof != null ? checkOutProof!.path : 'No file attached'}");
  }

  // ===== Pick File =====
  Future<void> _pickFile(bool isCheckIn) async {
    final XFile? file = await picker.pickImage(source: ImageSource.gallery);
    if (file != null) {
      setState(() {
        if (isCheckIn) {
          checkInProof = file;
        } else {
          checkOutProof = file;
        }
      });
    }
  }

  void setDate(DateTime newDate) {
    _date = newDate;
    dateController.text = "${newDate.day}-${newDate.month}-${newDate.year}";
  }

  Future<void> _pickTime(TextEditingController controller) async {
    final TimeOfDay? picked =
    await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (picked != null) {
      controller.text = picked.format(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: const Color(0xFEFFFFFF),
        title: Row(
          children: [
            InkResponse(
              onTap: () => Navigator.pop(context, true),
              child: SvgPicture.asset("assets/svg/appbar_back_button.svg",
                  height: 25),
            ),
            const SizedBox(width: 10),
            Text("Add Manual Attendance",
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: AppColors.semi_black,
                )),
          ],
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(18),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              /// Date
              _buildLabel("Date"),
              const SizedBox(height: 6),
              TextField(
                controller: dateController,
                readOnly: true,
                onTap: () => setDate(DateTime.now()),
                decoration: _inputDecoration("Select Date")
                    .copyWith(suffixIcon: const Icon(Icons.calendar_today)),
              ),
              const SizedBox(height: 16),

              /// Type Dropdown
              _buildLabel("Type"),
              const SizedBox(height: 6),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 2),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: DropdownButtonHideUnderline(
                  child: DropdownButton2<String>(
                    isExpanded: true,
                    hint: const Text("Select Type"),
                    value: selectedType,
                    items: types
                        .map((e) => DropdownMenuItem<String>(
                      value: e,
                      child: Text(e),
                    ))
                        .toList(),
                    onChanged: (val) => setState(() => selectedType = val),
                    // buttonStyleData: ddtheme.buttonStyleData,
                    iconStyleData: ddtheme.iconStyleData,
                    // menuItemStyleData: ddtheme.menuItemStyleData,
                    dropdownStyleData: ddtheme.dropdownStyleData,
                  ),
                ),
              ),
              const SizedBox(height: 20),

              /// Conditional Sections
              if (selectedType == "Check In")
                _buildSection(
                  title: "Check In",
                  timeController: checkInTime,
                  locationController: checkInLocation,
                  descriptionController: checkInDescription,
                  proofFile: checkInProof,
                  onPickProof: () => _pickFile(true),
                ),
              if (selectedType == "Check Out")
                _buildSection(
                  title: "Check Out",
                  timeController: checkOutTime,
                  locationController: checkOutLocation,
                  descriptionController: checkOutDescription,
                  proofFile: checkOutProof,
                  onPickProof: () => _pickFile(false),
                ),
              if (selectedType == "Check In/Out") ...[
                _buildSection(
                  title: "Check In",
                  timeController: checkInTime,
                  locationController: checkInLocation,
                  descriptionController: checkInDescription,
                  proofFile: checkInProof,
                  onPickProof: () => _pickFile(true),
                ),
                _buildSection(
                  title: "Check Out",
                  timeController: checkOutTime,
                  locationController: checkOutLocation,
                  descriptionController: checkOutDescription,
                  proofFile: checkOutProof,
                  onPickProof: () => _pickFile(false),
                ),
              ],

              const SizedBox(height: 24),

              /// Submit Button
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    backgroundColor:
                    isSubmitEnabled ? Colors.blue : Colors.grey.shade400,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8)),
                  ),
                  onPressed: isSubmitEnabled
                      ? () {
                    _submitForm();
                    print("Submit pressed for $selectedType");
                  }
                      : null,
                  child: const Text("Submit",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w500,
                      )),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Reusable Section
  Widget _buildSection({
    required String title,
    required TextEditingController timeController,
    required TextEditingController locationController,
    required TextEditingController descriptionController,
    required XFile? proofFile,
    required VoidCallback onPickProof,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildLabel("$title Time"),
        const SizedBox(height: 6),
        TextField(
          controller: timeController,
          readOnly: true,
          onTap: () => _pickTime(timeController),
          decoration: _inputDecoration("Select Time")
              .copyWith(suffixIcon: const Icon(Icons.access_time)),
        ),
        const SizedBox(height: 16),

        _buildLabel("$title Location"),
        const SizedBox(height: 6),
        TextField(
          controller: locationController,
          decoration: _inputDecoration("Enter Location"),
        ),
        const SizedBox(height: 16),

        _buildLabel("$title Description"),
        const SizedBox(height: 6),
        TextField(
          controller: descriptionController,
          maxLines: 3,
          decoration: _inputDecoration("Write Description"),
        ),
        const SizedBox(height: 18),

        /// Proof
        SizedBox(
          width: double.infinity,
          child: OutlinedButton(
            onPressed: onPickProof,
            style: OutlinedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 14),
              backgroundColor: Colors.blue.shade50,
              side: BorderSide(color: Colors.blue.shade200),
              shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
            ),
            child: Text("Attach $title Proof",
                style: const TextStyle(
                    fontSize: 16,
                    color: Colors.blue,
                    fontFamily: "Plus Jakarta Sans",
                    fontWeight: FontWeight.w500)),
          ),
        ),
        // Show proof preview
        if (proofFile != null) ...[
          const SizedBox(height: 10),
          Row(
            children: [
              const Icon(Icons.check_circle, color: Colors.green),
              const SizedBox(width: 8),
              Expanded(
                  child: Text(
                      "Attached: ${proofFile!.name}",
                      overflow: TextOverflow.ellipsis)),
              IconButton(
                icon: const Icon(Icons.close, color: Colors.red),
                onPressed: () => setState(() => proofFile = null),
              ),
            ],
          )
        ],
        const SizedBox(height: 24),
      ],
    );
  }

  Widget _buildLabel(String text) => Text(text,
      style: const TextStyle(
          fontSize: 15,
          fontFamily: "Plus Jakarta Sans",
          fontWeight: FontWeight.w500));

  InputDecoration _inputDecoration(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: const TextStyle(
          fontSize: 14,
          fontFamily: "Plus Jakarta Sans",
          fontWeight: FontWeight.w400,
          color: Colors.grey),
      filled: true,
      fillColor: Colors.grey.shade100,
      enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none),
      focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.blue)),
    );
  }
}
