<?php

namespace Database\Seeders;

use App\Models\Company;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use App\Models\Team;
use App\Models\Project;
use App\Models\Task;
use App\Models\Tag;
use App\Models\Comment;
use App\Models\Activity;

class DatabaseSeeder
{
    public function run(): void
    {
        // Create permissions
        $permissionNames = [
            'create_project', 'edit_project', 'delete_project',
            'create_task', 'assign_task', 'update_task_status',
            'comment_task', 'manage_users', 'manage_teams', 'view_reports',
        ];

        $permissions = [];
        foreach ($permissionNames as $name) {
            $permissions[$name] = Permission::create(['name' => $name, 'guard_name' => 'web']);
        }

        // Create roles with escalating permissions
        $rolePermissions = [
            'Super Admin' => $permissionNames,
            'Company Admin' => $permissionNames,
            'Manager' => ['create_project', 'edit_project', 'create_task', 'assign_task', 'update_task_status', 'comment_task', 'manage_teams', 'view_reports'],
            'Team Leader' => ['create_project', 'edit_project', 'create_task', 'assign_task', 'update_task_status', 'comment_task', 'view_reports'],
            'Employee' => ['create_task', 'update_task_status', 'comment_task'],
            'Viewer' => ['comment_task'],
        ];

        foreach ($rolePermissions as $roleName => $perms) {
            $role = Role::create(['name' => $roleName, 'guard_name' => 'web']);
            $permIds = [];
            foreach ($perms as $p) {
                $permIds[] = $permissions[$p]->id;
            }
            $role->permissions()->sync($permIds);
        }

        // Create company
        $company = Company::create([
            'name' => 'Acme Corporation',
            'slug' => 'acme-corporation',
            'subscription_plan' => 'enterprise',
            'description' => 'Leading technology and innovation company',
        ]);

        // Create users
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'System Administrator',
            'department' => 'IT',
            'is_active' => true,
        ]);
        $admin->assignRole('Super Admin');

        $manager = User::create([
            'name' => 'Sarah Manager',
            'email' => 'manager@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'Project Manager',
            'department' => 'Engineering',
        ]);
        $manager->assignRole('Manager');

        $leader = User::create([
            'name' => 'John Leader',
            'email' => 'leader@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'Team Lead',
            'department' => 'Engineering',
        ]);
        $leader->assignRole('Team Leader');

        $employee1 = User::create([
            'name' => 'Alice Developer',
            'email' => 'alice@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'Senior Developer',
            'department' => 'Engineering',
        ]);
        $employee1->assignRole('Employee');

        $employee2 = User::create([
            'name' => 'Bob Designer',
            'email' => 'bob@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'UI/UX Designer',
            'department' => 'Design',
        ]);
        $employee2->assignRole('Employee');

        $viewer = User::create([
            'name' => 'Charlie Viewer',
            'email' => 'viewer@asana.test',
            'password' => bcrypt('password'),
            'company_id' => $company->id,
            'job_title' => 'Stakeholder',
            'department' => 'Management',
        ]);
        $viewer->assignRole('Viewer');

        // Create teams
        $engTeam = Team::create([
            'company_id' => $company->id,
            'name' => 'Engineering',
            'department' => 'Technology',
            'description' => 'Software development team',
            'color' => '#6366f1',
        ]);
        $engTeam->members()->attach([
            $manager->id => ['role' => 'lead'],
            $leader->id => ['role' => 'lead'],
            $employee1->id => ['role' => 'member'],
        ]);

        $designTeam = Team::create([
            'company_id' => $company->id,
            'name' => 'Design',
            'department' => 'Creative',
            'description' => 'UI/UX and graphic design team',
            'color' => '#ec4899',
        ]);
        $designTeam->members()->attach([
            $employee2->id => ['role' => 'lead'],
        ]);

        $marketingTeam = Team::create([
            'company_id' => $company->id,
            'name' => 'Marketing',
            'department' => 'Marketing',
            'description' => 'Digital marketing and growth team',
            'color' => '#f59e0b',
        ]);

        // Create tags
        $tagBug = Tag::create(['company_id' => $company->id, 'name' => 'Bug', 'color' => '#ef4444']);
        $tagFeature = Tag::create(['company_id' => $company->id, 'name' => 'Feature', 'color' => '#3b82f6']);
        $tagUrgent = Tag::create(['company_id' => $company->id, 'name' => 'Urgent', 'color' => '#f97316']);
        $tagDesign = Tag::create(['company_id' => $company->id, 'name' => 'Design', 'color' => '#ec4899']);
        $tagBackend = Tag::create(['company_id' => $company->id, 'name' => 'Backend', 'color' => '#8b5cf6']);

        // Create projects
        $project1 = Project::create([
            'company_id' => $company->id,
            'team_id' => $engTeam->id,
            'owner_id' => $manager->id,
            'name' => 'Website Redesign',
            'description' => 'Complete redesign of the company website with modern UI/UX',
            'status' => 'in_progress',
            'priority' => 'high',
            'color' => '#6366f1',
            'start_date' => now()->subDays(14),
            'due_date' => now()->addDays(30),
            'progress' => 35,
        ]);
        $project1->members()->attach([
            $manager->id => ['role' => 'owner'],
            $leader->id => ['role' => 'member'],
            $employee1->id => ['role' => 'member'],
            $employee2->id => ['role' => 'member'],
        ]);

        $project2 = Project::create([
            'company_id' => $company->id,
            'team_id' => $engTeam->id,
            'owner_id' => $leader->id,
            'name' => 'Mobile App Development',
            'description' => 'Build a cross-platform mobile application',
            'status' => 'not_started',
            'priority' => 'medium',
            'color' => '#10b981',
            'start_date' => now()->addDays(7),
            'due_date' => now()->addDays(90),
            'progress' => 0,
        ]);

        $project3 = Project::create([
            'company_id' => $company->id,
            'team_id' => $designTeam->id,
            'owner_id' => $employee2->id,
            'name' => 'Brand Identity Update',
            'description' => 'Update brand guidelines, logo, and design system',
            'status' => 'in_progress',
            'priority' => 'medium',
            'color' => '#ec4899',
            'start_date' => now()->subDays(7),
            'due_date' => now()->addDays(21),
            'progress' => 50,
        ]);

        $project4 = Project::create([
            'company_id' => $company->id,
            'team_id' => $marketingTeam->id,
            'owner_id' => $manager->id,
            'name' => 'Q1 Marketing Campaign',
            'description' => 'Plan and execute Q1 digital marketing campaign',
            'status' => 'completed',
            'priority' => 'high',
            'color' => '#f59e0b',
            'start_date' => now()->subDays(60),
            'due_date' => now()->subDays(5),
            'progress' => 100,
        ]);

        // Create tasks for project 1
        $tasks = [
            ['title' => 'Create wireframes', 'status' => 'completed', 'priority' => 'high', 'assignee_id' => $employee2->id, 'due_date' => now()->subDays(5), 'is_completed' => true],
            ['title' => 'Design homepage mockup', 'status' => 'completed', 'priority' => 'high', 'assignee_id' => $employee2->id, 'due_date' => now()->subDays(2), 'is_completed' => true],
            ['title' => 'Set up Laravel project', 'status' => 'completed', 'priority' => 'medium', 'assignee_id' => $employee1->id, 'due_date' => now()->subDays(7), 'is_completed' => true],
            ['title' => 'Implement navigation header', 'status' => 'in_progress', 'priority' => 'medium', 'assignee_id' => $employee1->id, 'due_date' => now()->addDays(3)],
            ['title' => 'Build hero section', 'status' => 'in_progress', 'priority' => 'medium', 'assignee_id' => $employee1->id, 'due_date' => now()->addDays(5)],
            ['title' => 'Create about page', 'status' => 'todo', 'priority' => 'low', 'assignee_id' => $employee2->id, 'due_date' => now()->addDays(10)],
            ['title' => 'Implement contact form', 'status' => 'todo', 'priority' => 'medium', 'assignee_id' => $employee1->id, 'due_date' => now()->addDays(12)],
            ['title' => 'Add responsive design', 'status' => 'todo', 'priority' => 'high', 'assignee_id' => $employee1->id, 'due_date' => now()->addDays(15)],
            ['title' => 'Performance optimization', 'status' => 'todo', 'priority' => 'medium', 'assignee_id' => $leader->id, 'due_date' => now()->addDays(20)],
            ['title' => 'QA testing', 'status' => 'review', 'priority' => 'high', 'assignee_id' => $leader->id, 'due_date' => now()->addDays(2)],
            ['title' => 'Fix header dropdown bug', 'status' => 'in_progress', 'priority' => 'urgent', 'assignee_id' => $employee1->id, 'due_date' => now()->subDays(1)],
            ['title' => 'SEO optimization', 'status' => 'todo', 'priority' => 'low', 'assignee_id' => null, 'due_date' => now()->addDays(25)],
        ];

        $position = 0;
        foreach ($tasks as $taskData) {
            $task = Task::create(array_merge($taskData, [
                'project_id' => $project1->id,
                'creator_id' => $manager->id,
                'position' => $position++,
            ]));

            // Add tags to some tasks
            if ($task->priority === 'urgent') $task->tags()->attach($tagUrgent->id);
            if (str_contains(strtolower($task->title), 'design')) $task->tags()->attach($tagDesign->id);
            if (str_contains(strtolower($task->title), 'bug')) $task->tags()->attach($tagBug->id);
        }

        // Add some comments
        $firstTask = Task::first();
        if ($firstTask) {
            Comment::create([
                'task_id' => $firstTask->id,
                'user_id' => $manager->id,
                'body' => 'Great progress on this! Let\'s make sure we follow the brand guidelines.',
            ]);
            Comment::create([
                'task_id' => $firstTask->id,
                'user_id' => $employee2->id,
                'body' => 'I\'ve uploaded the latest wireframes. Please review when you get a chance.',
            ]);
        }

        // Add activities
        Activity::create([
            'company_id' => $company->id,
            'subject_type' => 'App\\Models\\Project',
            'subject_id' => $project1->id,
            'causer_id' => $manager->id,
            'action' => 'created',
            'description' => 'created project "Website Redesign"',
        ]);

        Activity::create([
            'company_id' => $company->id,
            'subject_type' => 'App\\Models\\Task',
            'subject_id' => $firstTask->id ?? 1,
            'causer_id' => $employee1->id,
            'action' => 'status_changed',
            'description' => 'changed task status to "In Progress"',
            'properties' => ['old_status' => 'todo', 'new_status' => 'in_progress'],
        ]);
    }
}
