<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Book;
use App\Models\BookChapter;
use App\Models\BookChapterPractice;

class BookChapterPracticeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        $book = Book::where('title', 'Mobile App Development with Flutter & Dart')->first();
        
        if (!$book) {
            $this->command->warn('Book not found. Please run BookSeeder first.');
            return;
        }

        // Get chapters
        $chapters = BookChapter::where('book_id', $book->id)->get();
        
        foreach ($chapters as $chapter) {
            $practices = $this->getPracticesForChapter($chapter);
            
            foreach ($practices as $practiceData) {
                BookChapterPractice::firstOrCreate(
                    [
                        'book_chapter_id' => $chapter->id,
                        'title' => $practiceData['title'],
                    ],
                    $practiceData
                );
            }
        }

        $this->command->info('Practice exercises seeded successfully!');
    }

    /**
     * Get practice exercises for a specific chapter based on its title/content.
     */
    private function getPracticesForChapter(BookChapter $chapter)
    {
        $title = strtolower($chapter->title);
        $practices = [];

        // Dart Fundamentals / Basics
        if (strpos($title, 'dart') !== false && (strpos($title, 'fundamental') !== false || strpos($title, 'basic') !== false)) {
            $practices = [
                [
                    'title' => 'List Operations',
                    'description' => 'Practice working with Lists in Dart. Create, manipulate, and access list elements.',
                    'dart_code' => "void main() {\n  // Create a list of numbers\n  var numbers = [1, 2, 3, 4, 5];\n  \n  // Add an element\n  numbers.add(6);\n  \n  // Access elements\n  print('First element: \${numbers[0]}');\n  print('List length: \${numbers.length}');\n  \n  // Iterate through list\n  for (var num in numbers) {\n    print('Number: \$num');\n  }\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Create a list of your favorite colors\n2. Add 3 more colors to the list\n3. Print the first and last color\n4. Print the total number of colors',
                    'order' => 1,
                    'is_active' => true,
                ],
                [
                    'title' => 'Map Operations',
                    'description' => 'Practice working with Maps (key-value pairs) in Dart.',
                    'dart_code' => "void main() {\n  // Create a map\n  var person = {\n    'name': 'Adu',\n    'age': 22,\n    'city': 'Accra'\n  };\n  \n  // Access values\n  print('Name: \${person['name']}');\n  print('Age: \${person['age']}');\n  \n  // Add new key-value pair\n  person['email'] = 'adu@example.com';\n  \n  // Iterate through map\n  person.forEach((key, value) {\n    print('\$key: \$value');\n  });\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Create a map for a student with name, age, and course\n2. Add a new field for grade\n3. Print all student information\n4. Check if a specific key exists',
                    'order' => 2,
                    'is_active' => true,
                ],
                [
                    'title' => 'Variables and Types',
                    'description' => 'Practice declaring variables with different types and using var, final, and const.',
                    'dart_code' => "void main() {\n  // Using var (type inference)\n  var name = 'Flutter';\n  var count = 10;\n  \n  // Using final (runtime constant)\n  final currentTime = DateTime.now();\n  \n  // Using const (compile-time constant)\n  const maxUsers = 100;\n  \n  // Explicit types\n  String course = 'Mobile Development';\n  int students = 25;\n  double price = 99.99;\n  bool isActive = true;\n  \n  print('Name: \$name');\n  print('Count: \$count');\n  print('Course: \$course');\n  print('Price: \${price.toStringAsFixed(2)}');\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Declare variables for a product (name, price, quantity)\n2. Use appropriate types (String, double, int)\n3. Calculate total cost (price * quantity)\n4. Print all product information',
                    'order' => 3,
                    'is_active' => true,
                ],
                [
                    'title' => 'String Operations',
                    'description' => 'Practice string concatenation, interpolation, and manipulation.',
                    'dart_code' => "void main() {\n  String firstName = 'Adu';\n  String lastName = 'Amankwah';\n  \n  // String concatenation\n  String fullName1 = firstName + ' ' + lastName;\n  \n  // String interpolation (preferred)\n  String fullName2 = '\$firstName \$lastName';\n  \n  // String methods\n  print('Full Name: \$fullName2');\n  print('Length: \${fullName2.length}');\n  print('Uppercase: \${fullName2.toUpperCase()}');\n  print('Lowercase: \${fullName2.toLowerCase()}');\n  \n  // Contains check\n  print('Contains \"Adu\": \${fullName2.contains(\"Adu\")}');\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Create variables for first name and last name\n2. Use interpolation to create full name\n3. Print the name in uppercase\n4. Check if the name contains a specific letter',
                    'order' => 4,
                    'is_active' => true,
                ],
            ];
        }
        // Networking and REST APIs
        elseif (strpos($title, 'network') !== false || strpos($title, 'rest') !== false || strpos($title, 'api') !== false) {
            $practices = [
                [
                    'title' => 'Fetch Data from JSON API',
                    'description' => 'Fetch data from a free online JSON API and display it. This example uses jsonplaceholder.typicode.com.',
                    'dart_code' => "import 'dart:convert';\nimport 'package:http/http.dart' as http;\n\nvoid main() async {\n  try {\n    // Fetch data from free API\n    final response = await http.get(\n      Uri.parse('https://jsonplaceholder.typicode.com/posts/1')\n    );\n    \n    if (response.statusCode == 200) {\n      // Parse JSON response\n      Map<String, dynamic> data = json.decode(response.body);\n      \n      print('Post ID: \${data['id']}');\n      print('Title: \${data['title']}');\n      print('Body: \${data['body']}');\n    } else {\n      print('Failed to load data: \${response.statusCode}');\n    }\n  } catch (e) {\n    print('Error: \$e');\n  }\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Fetch data from https://jsonplaceholder.typicode.com/users/1\n2. Parse the JSON response\n3. Print the user\'s name, email, and phone\n4. Handle errors properly',
                    'order' => 1,
                    'is_active' => true,
                ],
                [
                    'title' => 'Fetch List of Posts',
                    'description' => 'Fetch a list of posts from the API and iterate through them.',
                    'dart_code' => "import 'dart:convert';\nimport 'package:http/http.dart' as http;\n\nvoid main() async {\n  try {\n    final response = await http.get(\n      Uri.parse('https://jsonplaceholder.typicode.com/posts')\n    );\n    \n    if (response.statusCode == 200) {\n      List<dynamic> posts = json.decode(response.body);\n      \n      print('Total posts: \${posts.length}');\n      print('\\nFirst 3 posts:');\n      \n      for (var i = 0; i < 3 && i < posts.length; i++) {\n        print('\\nPost \${i + 1}:');\n        print('ID: \${posts[i]['id']}');\n        print('Title: \${posts[i]['title']}');\n      }\n    }\n  } catch (e) {\n    print('Error: \$e');\n  }\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Fetch all posts from the API\n2. Print the total number of posts\n3. Display the title of the first 5 posts\n4. Find and print the post with ID 10',
                    'order' => 2,
                    'is_active' => true,
                ],
                [
                    'title' => 'Fetch User Data',
                    'description' => 'Fetch user data from a free API and work with nested JSON objects.',
                    'dart_code' => "import 'dart:convert';\nimport 'package:http/http.dart' as http;\n\nvoid main() async {\n  try {\n    final response = await http.get(\n      Uri.parse('https://jsonplaceholder.typicode.com/users/1')\n    );\n    \n    if (response.statusCode == 200) {\n      Map<String, dynamic> user = json.decode(response.body);\n      \n      print('User Information:');\n      print('Name: \${user['name']}');\n      print('Email: \${user['email']}');\n      print('Phone: \${user['phone']}');\n      print('Website: \${user['website']}');\n      \n      // Access nested object (address)\n      Map<String, dynamic> address = user['address'];\n      print('\\nAddress:');\n      print('Street: \${address['street']}');\n      print('City: \${address['city']}');\n      print('Zipcode: \${address['zipcode']}');\n    }\n  } catch (e) {\n    print('Error: \$e');\n  }\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Fetch user data from the API\n2. Extract and print user details\n3. Access nested address information\n4. Format the output nicely',
                    'order' => 3,
                    'is_active' => true,
                ],
                [
                    'title' => 'Fetch Random Quote',
                    'description' => 'Fetch a random quote from a free quote API.',
                    'dart_code' => "import 'dart:convert';\nimport 'package:http/http.dart' as http;\n\nvoid main() async {\n  try {\n    final response = await http.get(\n      Uri.parse('https://api.quotable.io/random')\n    );\n    \n    if (response.statusCode == 200) {\n      Map<String, dynamic> quote = json.decode(response.body);\n      \n      print('Quote:');\n      print('\"\${quote['content']}\"');\n      print('\\n- \${quote['author']}');\n    }\n  } catch (e) {\n    print('Error: \$e');\n  }\n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Fetch a random quote from the API\n2. Display the quote and author\n3. Add error handling\n4. Format the output beautifully',
                    'order' => 4,
                    'is_active' => true,
                ],
            ];
        }
        // Flutter Widgets / UI
        elseif (strpos($title, 'widget') !== false || strpos($title, 'ui') !== false || strpos($title, 'layout') !== false) {
            $practices = [
                [
                    'title' => 'Basic Flutter App',
                    'description' => 'Create a simple Flutter app with a basic widget structure.',
                    'dart_code' => null,
                    'flutter_code' => "import 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: 'My First App',\n      home: Scaffold(\n        appBar: AppBar(\n          title: Text('Welcome'),\n        ),\n        body: Center(\n          child: Text(\n            'Hello, Flutter!',\n            style: TextStyle(fontSize: 24),\n          ),\n        ),\n      ),\n    );\n  }\n}",
                    'type' => 'flutter',
                    'instructions' => '1. Create a Flutter app with a custom title\n2. Add an AppBar with your name\n3. Change the text color and size\n4. Add a background color to the body',
                    'order' => 1,
                    'is_active' => true,
                ],
                [
                    'title' => 'Row and Column Layout',
                    'description' => 'Practice using Row and Column widgets to arrange elements.',
                    'dart_code' => null,
                    'flutter_code' => "import 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: Scaffold(\n        appBar: AppBar(title: Text('Layout Practice')),\n        body: Column(\n          mainAxisAlignment: MainAxisAlignment.center,\n          children: [\n            Text('Item 1', style: TextStyle(fontSize: 20)),\n            SizedBox(height: 20),\n            Text('Item 2', style: TextStyle(fontSize: 20)),\n            SizedBox(height: 20),\n            Row(\n              mainAxisAlignment: MainAxisAlignment.center,\n              children: [\n                Text('Left'),\n                SizedBox(width: 20),\n                Text('Right'),\n              ],\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n}",
                    'type' => 'flutter',
                    'instructions' => '1. Create a Column with 3 text widgets\n2. Add spacing between items using SizedBox\n3. Add a Row inside the Column\n4. Center all elements',
                    'order' => 2,
                    'is_active' => true,
                ],
            ];
        }
        // State Management
        elseif (strpos($title, 'state') !== false) {
            $practices = [
                [
                    'title' => 'Counter with setState',
                    'description' => 'Create a simple counter app using setState for state management.',
                    'dart_code' => null,
                    'flutter_code' => "import 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: CounterApp(),\n    );\n  }\n}\n\nclass CounterApp extends StatefulWidget {\n  @override\n  _CounterAppState createState() => _CounterAppState();\n}\n\nclass _CounterAppState extends State<CounterApp> {\n  int _counter = 0;\n\n  void _incrementCounter() {\n    setState(() {\n      _counter++;\n    });\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(title: Text('Counter App')),\n      body: Center(\n        child: Column(\n          mainAxisAlignment: MainAxisAlignment.center,\n          children: [\n            Text('You have pushed the button this many times:'),\n            Text(\n              '\$_counter',\n              style: Theme.of(context).textTheme.headline4,\n            ),\n          ],\n        ),\n      ),\n      floatingActionButton: FloatingActionButton(\n        onPressed: _incrementCounter,\n        child: Icon(Icons.add),\n      ),\n    );\n  }\n}",
                    'type' => 'flutter',
                    'instructions' => '1. Add a decrement button\n2. Add a reset button\n3. Change the counter color when it reaches 10\n4. Add a maximum limit of 20',
                    'order' => 1,
                    'is_active' => true,
                ],
            ];
        }
        // Forms and Input
        elseif (strpos($title, 'form') !== false || strpos($title, 'input') !== false) {
            $practices = [
                [
                    'title' => 'Simple Form',
                    'description' => 'Create a form with text input and validation.',
                    'dart_code' => null,
                    'flutter_code' => "import 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: FormExample(),\n    );\n  }\n}\n\nclass FormExample extends StatefulWidget {\n  @override\n  _FormExampleState createState() => _FormExampleState();\n}\n\nclass _FormExampleState extends State<FormExample> {\n  final _formKey = GlobalKey<FormState>();\n  final _nameController = TextEditingController();\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(title: Text('Form Example')),\n      body: Form(\n        key: _formKey,\n        child: Padding(\n          padding: EdgeInsets.all(16.0),\n          child: Column(\n            children: [\n              TextFormField(\n                controller: _nameController,\n                decoration: InputDecoration(\n                  labelText: 'Name',\n                  border: OutlineInputBorder(),\n                ),\n                validator: (value) {\n                  if (value == null || value.isEmpty) {\n                    return 'Please enter your name';\n                  }\n                  return null;\n                },\n              ),\n              SizedBox(height: 20),\n              ElevatedButton(\n                onPressed: () {\n                  if (_formKey.currentState!.validate()) {\n                    ScaffoldMessenger.of(context).showSnackBar(\n                      SnackBar(content: Text('Hello, \${_nameController.text}!')),\n                    );\n                  }\n                },\n                child: Text('Submit'),\n              ),\n            ],\n          ),\n        ),\n      ),\n    );\n  }\n}",
                    'type' => 'flutter',
                    'instructions' => '1. Add an email field with validation\n2. Add a password field\n3. Validate email format\n4. Show success message on valid submission',
                    'order' => 1,
                    'is_active' => true,
                ],
            ];
        }
        // Lists and Collections
        elseif (strpos($title, 'list') !== false || strpos($title, 'collection') !== false || strpos($title, 'grid') !== false) {
            $practices = [
                [
                    'title' => 'Simple ListView',
                    'description' => 'Create a ListView to display a list of items.',
                    'dart_code' => null,
                    'flutter_code' => "import 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: ListExample(),\n    );\n  }\n}\n\nclass ListExample extends StatelessWidget {\n  final List<String> items = [\n    'Item 1',\n    'Item 2',\n    'Item 3',\n    'Item 4',\n    'Item 5',\n  ];\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(title: Text('List Example')),\n      body: ListView.builder(\n        itemCount: items.length,\n        itemBuilder: (context, index) {\n          return ListTile(\n            leading: Icon(Icons.star),\n            title: Text(items[index]),\n            subtitle: Text('Subtitle for \${items[index]}'),\n            trailing: Icon(Icons.arrow_forward),\n          );\n        },\n      ),\n    );\n  }\n}",
                    'type' => 'flutter',
                    'instructions' => '1. Add 10 more items to the list\n2. Change the icon for each item\n3. Add onTap functionality to show a message\n4. Add different colors for odd/even items',
                    'order' => 1,
                    'is_active' => true,
                ],
            ];
        }
        // Default practices for other chapters
        else {
            $practices = [
                [
                    'title' => 'Basic Dart Program',
                    'description' => 'Practice basic Dart programming concepts from this chapter.',
                    'dart_code' => "void main() {\n  print('Hello, Dart!');\n  print('Welcome to Flutter Development');\n  \n  // Add your code here\n  \n}",
                    'flutter_code' => null,
                    'type' => 'dart',
                    'instructions' => '1. Print your name and course\n2. Create a variable for your age\n3. Calculate and print your birth year\n4. Print a welcome message',
                    'order' => 1,
                    'is_active' => true,
                ],
            ];
        }

        return $practices;
    }
}
