import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:onsolgo/core/constants.dart';
import 'package:onsolgo/screens/artist/artist_series_manage_screen.dart';
import 'package:onsolgo/screens/artist/artist_upcoming_screen.dart';

class ArtistHub extends StatefulWidget {
  const ArtistHub({super.key});
  @override
  State<ArtistHub> createState() => _ArtistHubState();
}

class _ArtistHubState extends State<ArtistHub> {
  @override
  Widget build(BuildContext context) {
    final String uid = FirebaseAuth.instance.currentUser?.uid ?? "";
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.amber[900],
        title: const Text("ARTIST HUB"),
        actions: [
          IconButton(
            tooltip: 'Upcoming releases',
            icon: const Icon(Icons.event_available),
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute<void>(builder: (_) => const ArtistUpcomingScreen()),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          Positioned.fill(
            child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance.collection('manga').where('authorId', isEqualTo: uid).snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
                final docs = snapshot.data!.docs;
                return CustomScrollView(
                  slivers: [
                    SliverToBoxAdapter(
                      child: Card(
                        margin: const EdgeInsets.fromLTRB(15, 15, 15, 8),
                        color: Colors.grey.shade900,
                        child: ListTile(
                          leading: const Icon(Icons.event_available, color: kOnsolGold),
                          title: const Text('MANAGE UPCOMING RELEASES'),
                          subtitle: const Text('Add, edit, or remove Soon tab teasers', style: TextStyle(fontSize: 11)),
                          trailing: const Icon(Icons.chevron_right, color: Colors.white54),
                          onTap: () => Navigator.push(
                            context,
                            MaterialPageRoute<void>(builder: (_) => const ArtistUpcomingScreen()),
                          ),
                        ),
                      ),
                    ),
                    if (docs.isEmpty)
                      SliverFillRemaining(
                        hasScrollBody: false,
                        child: Center(
                          child: Text(
                            'No series assigned to your account yet.',
                            style: TextStyle(color: Colors.grey[500]),
                          ),
                        ),
                      )
                    else
                      SliverPadding(
                        padding: const EdgeInsets.fromLTRB(15, 0, 15, 15),
                        sliver: SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) => Card(
                              color: Colors.grey[900],
                              child: ListTile(
                                title: Text(docs[index]['title'] ?? 'Untitled'),
                                subtitle: const Text('Manage portfolio'),
                                onTap: () => _showOptions(context, docs[index]),
                              ),
                            ),
                            childCount: docs.length,
                          ),
                        ),
                      ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void _showOptions(BuildContext context, DocumentSnapshot series) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.grey[900],
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
      builder: (context) => SafeArea(
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.auto_stories, color: kOnsolGold),
                title: const Text('SERIES & CHAPTERS'),
                subtitle: const Text('Banner, library cover, chapters', style: TextStyle(fontSize: 11)),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.push(
                    context,
                    MaterialPageRoute<void>(builder: (_) => ArtistSeriesManageScreen(series: series)),
                  );
                },
              ),
              ListTile(
                leading: const Icon(Icons.event_available, color: kOnsolGold),
                title: const Text('UPCOMING RELEASES'),
                subtitle: const Text('Manage Soon tab announcements', style: TextStyle(fontSize: 11)),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.push(context, MaterialPageRoute<void>(builder: (_) => const ArtistUpcomingScreen()));
                },
              ),
              ListTile(
                leading: const Icon(Icons.edit),
                title: const Text('EDIT PORTFOLIO INFO'),
                onTap: () {
                  Navigator.pop(context);
                  _editPortfolio(context, series);
                },
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  void _editPortfolio(BuildContext context, DocumentSnapshot series) {
    final d = series.data() as Map<String, dynamic>;
    final s = d['socials'] ?? {};
    final sC = TextEditingController(text: d['synopsis'] ?? "");
    final bC = TextEditingController(text: d['aboutArtist'] ?? "");
    final fbC = TextEditingController(text: s['facebook'] ?? "");
    final igC = TextEditingController(text: s['instagram'] ?? "");
    final xC = TextEditingController(text: s['twitter'] ?? s['x'] ?? "");
    final webC = TextEditingController(text: s['website'] ?? "");

    showDialog(context: context, builder: (ctx) => AlertDialog(
      backgroundColor: Colors.grey[900], title: const Text("Edit Portfolio"),
      content: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min, children: [
        TextField(controller: sC, maxLines: 3, decoration: const InputDecoration(hintText: "Synopsis")),
        TextField(controller: bC, maxLines: 3, decoration: const InputDecoration(hintText: "Artist Bio")),
        TextField(controller: fbC, decoration: const InputDecoration(hintText: "Facebook URL")),
        TextField(controller: igC, decoration: const InputDecoration(hintText: "Instagram URL")),
        TextField(controller: xC, decoration: const InputDecoration(hintText: "X (Twitter) URL")),
        TextField(controller: webC, decoration: const InputDecoration(hintText: "Personal website URL")),
      ])),
      actions: [ElevatedButton(onPressed: () {
        series.reference.update({
          'synopsis': sC.text,
          'aboutArtist': bC.text,
          'socials': {
            'facebook': fbC.text,
            'instagram': igC.text,
            'twitter': xC.text,
            'website': webC.text,
          },
        });
        Navigator.pop(ctx);
      }, child: const Text("SAVE"))],
    ));
  }
}