// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/models/meetings/meetings_model.dart';
import 'package:qadirneyriz/screens/meeting_summary/state.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/utils/tools/tools.dart';
import 'package:qadirneyriz/widgets/card_meeting.dart';
import 'package:qadirneyriz/widgets/custom_appbar.dart';
import 'package:qadirneyriz/widgets/custom_button.dart';

class MeetingSummaryScreen extends StatefulWidget {
  final Datum meetingItem;
  const MeetingSummaryScreen({
    Key? key,
    required this.meetingItem,
  }) : super(key: key);

  @override
  State<MeetingSummaryScreen> createState() => _MeetingSummaryScreenState();
}

class _MeetingSummaryScreenState extends State<MeetingSummaryScreen> {
  late TextEditingController _textControllerDescription;

  @override
  void initState() {
    super.initState();
    _textControllerDescription = TextEditingController();
  }

  @override
  void dispose() {
    _textControllerDescription.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<MeetingSummaryState>(
        builder: (context, value, child) {
          return CustomScrollView(
            slivers: <Widget>[
              CustomAppbar(
                title: 'صورت جلسه',
              ),
              SliverPadding(
                padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 2),
                sliver: SliverToBoxAdapter(
                  child: CustomCardMeeting(
                    titel: widget.meetingItem.subject!.subject ?? '',
                    date: widget.meetingItem.dateJalali ?? '',
                    location: widget.meetingItem.location!.address ?? '',
                    fromTime: widget.meetingItem.azHour ?? '',
                    toTime: widget.meetingItem.taHour ?? '',
                    cardId: widget.meetingItem.id ?? -1,
                  ),
                ),
              ),
              SliverPadding(
                padding:
                    const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                sliver: SliverToBoxAdapter(
                  child: Container(
                    decoration: BoxDecoration(
                      color: const Color(0xffF4F9F6),
                      boxShadow: [
                        BoxShadow(
                          color: config.ui.mainGray.withOpacity(.1),
                          spreadRadius: .1,
                          offset: const Offset(0, 2),
                          blurRadius: 6,
                        ),
                      ],
                      borderRadius: const BorderRadius.all(Radius.circular(12)),
                    ),
                    child: CustomTextArea(
                      hintText: 'شرح جلسه',
                      controller: _textControllerDescription,
                    ),
                  ),
                ),
              ),
              SliverToBoxAdapter(
                child: ReceiptUploadDialog(
                  state: value,
                ),
              ),
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(30.0),
                  child: submitSammaryButton(context, value),
                ),
              )
            ],
          );
        },
      ),
    );
  }

  Widget submitSammaryButton(BuildContext context, MeetingSummaryState state) {
    switch (state.statusMinuteMeeting) {
      case Status.loading:
        return CustomButton(hieght: 50, text: 'صبر کنید!');

      default:
        return CustomButton(
          hieght: 50,
          text: 'ثبت صورت جلسه',
          onPressed: () async {
            if (_textControllerDescription.text == '') {
              // call add new subject
              Tools.showCustomSnackBar(
                text: 'موضوع وارد کنید!',
                isError: true,
                context,
              );
            } else if (state.selectedFiles == null) {
              // call add new subject
              Tools.showCustomSnackBar(
                text: 'فایل وارد کنید!',
                isError: true,
                context,
              );
            } else {
              final status = await state.addMinuteMeeting(
                  id: widget.meetingItem.id ?? -1,
                  description: _textControllerDescription.text,
                  meetingFiles: state.selectedFiles ?? []);

              if (status == Status.ready) {
                // call refrresh subjects
              } else {
                Tools.showCustomSnackBar(
                  text: state.errorsMinuteMeeting == null
                      ? state.messageMinuteMeeting ??
                          '  AppLocalizations.of(context)!.haserror'
                      : Tools.combineErrorMessages(
                          state.errorsMinuteMeeting ?? {}),
                  isError: true,
                  context,
                );
              }
            }
          },
        );
    }
  }
}

class CustomTextArea extends StatelessWidget {
  final String hintText;
  final TextEditingController controller;
  final int maxLines;
  final int minLines;

  const CustomTextArea({
    Key? key,
    required this.hintText,
    required this.controller,
    this.maxLines = 20,
    this.minLines = 4,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: controller,
      maxLines: maxLines,
      minLines: minLines,
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(color: Colors.black.withOpacity(.4), fontSize: 13),
        border: InputBorder.none,
        contentPadding: const EdgeInsets.all(12.0),
      ),
    );
  }
}

class ReceiptUploadDialog extends StatefulWidget {
  final MeetingSummaryState state;
  const ReceiptUploadDialog({
    Key? key,
    required this.state,
  }) : super(key: key);

  @override
  _ReceiptUploadDialogState createState() => _ReceiptUploadDialogState();
}

class _ReceiptUploadDialogState extends State<ReceiptUploadDialog> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xffF4F9F6),
          boxShadow: [
            BoxShadow(
              color: config.ui.mainGray.withOpacity(.1),
              spreadRadius: .1,
              offset: const Offset(0, 2),
              blurRadius: 6,
            ),
          ],
          borderRadius: const BorderRadius.all(Radius.circular(12)),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 25, horizontal: 10),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'آپلود فایل',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: config.ui.mainGreen,
                ),
              ),
              const SizedBox(height: 20),

              // Upload box
              FileBorderBox(
                child: GestureDetector(
                  onTap: widget.state.pickFiles,
                  child: Column(
                    children: [
                      Icon(Icons.cloud_upload_outlined,
                          size: 30, color: config.ui.mainGreen),
                      Text(
                        'انتخاب فایل',
                        style:
                            TextStyle(fontSize: 12, color: config.ui.mainGreen),
                      ),
                    ],
                  ),
                ),
              ),

              // File preview
              if (widget.state.selectedFiles != null)
                FilePreview(
                  files: widget.state.selectedFiles!,
                  onDelete: widget.state.removeFile,
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class FilePreview extends StatelessWidget {
  final List<PlatformFile> files;
  final void Function(int) onDelete;

  const FilePreview({
    super.key,
    required this.files,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: files.length,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
          margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            border: Border(bottom: BorderSide(color: config.ui.secendGreen)),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const Icon(Icons.file_present_outlined, color: Color(0xffD0D5ED)),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  files[index].name,
                  style: const TextStyle(fontSize: 12),
                ),
              ),
              IconButton(
                icon: Icon(Icons.delete, color: config.ui.secendGreen),
                onPressed: () => onDelete(index),
              ),
            ],
          ),
        );
      },
    );
  }
}

class FileBorderBox extends StatelessWidget {
  final Widget child;
  const FileBorderBox({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: config.ui.mainGreen,
          style: BorderStyle.solid,
          width: .5,
        ),
      ),
      child: Center(child: child),
    );
  }
}
