<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Booking;
use App\Models\Payout;
use App\Models\Payment;
use App\Models\Review;
use App\Models\BabysitterProfile;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class BabysitterDashboardController extends Controller
{
    public function getBabysitterDashboard(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            // Check if user is babysitter
            if (!$user || !$this->isBabysitter($user)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized. Only babysitters can access this dashboard.'
                ], 403);
            }

            // Get date range filters
            $startDate = $request->get('start_date') ? Carbon::parse($request->get('start_date')) : Carbon::now()->subMonth();
            $endDate = $request->get('end_date') ? Carbon::parse($request->get('end_date')) : Carbon::now();

            // Fetch all dashboard data
            $results = $this->fetchBabysitterDashboardData($user, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $results,
                'period' => [
                    'start_date' => $startDate->toDateString(),
                    'end_date' => $endDate->toDateString()
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Babysitter Dashboard Error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch babysitter dashboard data',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Check if user is babysitter
     */
    private function isBabysitter($user): bool
    {
        // Check if user has babysitter profile
        return BabysitterProfile::where('user_id', $user->user_id)->exists();
    }

    /**
     * Fetch all babysitter dashboard data
     */
    private function fetchBabysitterDashboardData($user, $startDate, $endDate)
    {
        return DB::transaction(function () use ($user, $startDate, $endDate) {
            // 1. Basic Statistics
            $basicStats = $this->getBasicStatistics($user);

            // 2. Financial Statistics (now includes today_earnings)
            $financialStats = $this->getFinancialStatistics($user, $startDate, $endDate);

            // 3. Booking Statistics
            $bookingStats = $this->getBookingStatistics($user);

            // 4. Review Statistics
            $reviewStats = $this->getReviewStatistics($user);

            // 5. Recent Activity
            $recentActivity = $this->getRecentActivity($user);

            // 6. Upcoming Bookings
            $upcomingBookings = $this->getUpcomingBookings($user);

            return [
                'summary_cards' => [
                    'total_earnings' => $financialStats['total_earnings'],
                    'pending_payouts' => $financialStats['pending_payouts'],
                    'completed_bookings' => $bookingStats['completed_bookings'],
                    'active_bookings' => $bookingStats['active_bookings'],
                    'total_reviews' => $reviewStats['total_reviews'],
                    'average_rating' => $reviewStats['average_rating'],
                    'response_rate' => $basicStats['response_rate'],
                    'profile_views' => $basicStats['profile_views'],
                    'today_earnings' => $financialStats['today_earnings'] // Added here
                ],
                'basic_statistics' => $basicStats,
                'financial_statistics' => $financialStats,
                'booking_statistics' => $bookingStats,
                'review_statistics' => $reviewStats,
                'recent_activity' => $recentActivity,
                'upcoming_bookings' => $upcomingBookings
            ];
        });
    }

    /**
     * Get Basic Statistics
     */
    private function getBasicStatistics($user): array
    {
        $babysitterProfile = BabysitterProfile::where('user_id', $user->user_id)->first();

        // Calculate response rate (based on booking requests)
        $totalRequests = Booking::where('babysitter_id', $user->user_id)->count();
        $respondedRequests = Booking::where('babysitter_id', $user->user_id)
            ->whereIn('booking_status', ['confirmed', 'active', 'completed', 'cancelled'])
            ->count();

        $responseRate = $totalRequests > 0 ? round(($respondedRequests / $totalRequests) * 100, 2) : 0;

        return [
            'member_since' => $user->created_at->format('M Y'),
            'response_rate' => $responseRate,
            'profile_views' => $babysitterProfile->profile_views ?? 0,
            'completion_rate' => $this->getCompletionRate($user),
            'reliability_score' => $this->getReliabilityScore($user),
            'verification_status' => $babysitterProfile->verification_status ?? 'pending'
        ];
    }

    /**
     * Get Completion Rate
     */
    private function getCompletionRate($user): float
    {
        $totalBookings = Booking::where('babysitter_id', $user->user_id)
            ->whereIn('booking_status', ['confirmed', 'active', 'completed'])
            ->count();

        $completedBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'completed')
            ->count();

        return $totalBookings > 0 ? round(($completedBookings / $totalBookings) * 100, 2) : 0;
    }

    /**
     * Get Reliability Score
     */
    private function getReliabilityScore($user): float
    {
        // Based on completed bookings, on-time performance, and reviews
        $completedBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'completed')
            ->count();

        $totalBookings = Booking::where('babysitter_id', $user->user_id)
            ->whereIn('booking_status', ['completed', 'cancelled'])
            ->count();

        $reliabilityRate = $totalBookings > 0 ? round(($completedBookings / $totalBookings) * 100, 2) : 100;

        // Adjust based on average rating
        $averageRating = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->avg('rating') ?? 5;

        $ratingFactor = ($averageRating / 5) * 20; // 20% weight for ratings

        return min(100, round($reliabilityRate * 0.8 + $ratingFactor, 2));
    }

    /**
     * Get Financial Statistics (Updated to include today_earnings)
     */
    private function getFinancialStatistics($user, $startDate, $endDate): array
    {
        // Total earnings from completed payments
        $totalEarnings = Payment::where('babysitter_id', $user->user_id)
            ->where('payment_status', 'completed')
            ->sum('babysitter_payout_amount');

        // Pending payouts
        $pendingPayouts = Payout::where('babysitter_id', $user->user_id)
            ->where('payout_status', 'pending')
            ->sum('amount');

        // Completed payouts
        $completedPayouts = Payout::where('babysitter_id', $user->user_id)
            ->where('payout_status', 'completed')
            ->sum('amount');

        // Earnings this month
        $monthlyEarnings = Payment::where('babysitter_id', $user->user_id)
            ->where('payment_status', 'completed')
            ->whereYear('created_at', Carbon::now()->year)
            ->whereMonth('created_at', Carbon::now()->month)
            ->sum('babysitter_payout_amount');

        // Earnings in date range
        $periodEarnings = Payment::where('babysitter_id', $user->user_id)
            ->where('payment_status', 'completed')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->sum('babysitter_payout_amount');

        // Today's earnings - Added this field
        $todayEarnings = Payment::where('babysitter_id', $user->user_id)
            ->where('payment_status', 'completed')
            ->whereDate('created_at', Carbon::today())
            ->sum('babysitter_payout_amount');

        return [
            'total_earnings' => $totalEarnings,
            'pending_payouts' => $pendingPayouts,
            'completed_payouts' => $completedPayouts,
            'monthly_earnings' => $monthlyEarnings,
            'period_earnings' => $periodEarnings,
            'today_earnings' => $todayEarnings, // Added this line
            'average_booking_value' => $this->getAverageBookingValue($user),
            'next_payout_date' => $this->getNextPayoutDate($user)
        ];
    }

    /**
     * Get Average Booking Value
     */
    private function getAverageBookingValue($user): float
    {
        $completedPayments = Payment::where('babysitter_id', $user->user_id)
            ->where('payment_status', 'completed')
            ->get();

        $totalEarnings = $completedPayments->sum('babysitter_payout_amount');
        $bookingCount = $completedPayments->count();

        return $bookingCount > 0 ? round($totalEarnings / $bookingCount, 2) : 0;
    }

    /**
     * Get Next Payout Date
     */
    private function getNextPayoutDate($user): ?string
    {
        $nextPayout = Payout::where('babysitter_id', $user->user_id)
            ->where('payout_status', 'pending')
            ->where('scheduled_payout_date', '>=', Carbon::today())
            ->orderBy('scheduled_payout_date', 'asc')
            ->first();

        return $nextPayout ? $nextPayout->scheduled_payout_date : null;
    }

    /**
     * Get Booking Statistics
     */
    private function getBookingStatistics($user): array
    {
        $totalBookings = Booking::where('babysitter_id', $user->user_id)->count();
        $activeBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'active')
            ->count();
        $completedBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'completed')
            ->count();
        $upcomingBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'confirmed')
            ->where('start_date', '>=', Carbon::today())
            ->count();
        $cancelledBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('booking_status', 'cancelled')
            ->count();

        // Recent bookings (last 7 days)
        $recentBookings = Booking::where('babysitter_id', $user->user_id)
            ->where('created_at', '>=', Carbon::now()->subDays(7))
            ->count();

        return [
            'total_bookings' => $totalBookings,
            'active_bookings' => $activeBookings,
            'completed_bookings' => $completedBookings,
            'upcoming_bookings' => $upcomingBookings,
            'cancelled_bookings' => $cancelledBookings,
            'recent_bookings_7_days' => $recentBookings,
            'completion_rate' => $totalBookings > 0 ? round(($completedBookings / $totalBookings) * 100, 2) : 0,
            'status_distribution' => [
                'active_percentage' => $totalBookings > 0 ? round(($activeBookings / $totalBookings) * 100, 2) : 0,
                'completed_percentage' => $totalBookings > 0 ? round(($completedBookings / $totalBookings) * 100, 2) : 0,
                'upcoming_percentage' => $totalBookings > 0 ? round(($upcomingBookings / $totalBookings) * 100, 2) : 0,
                'cancelled_percentage' => $totalBookings > 0 ? round(($cancelledBookings / $totalBookings) * 100, 2) : 0
            ]
        ];
    }

    /**
     * Get Review Statistics
     */
    private function getReviewStatistics($user): array
    {
        $totalReviews = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->count();

        $averageRating = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->avg('rating') ?? 0;

        // Rating distribution
        $ratingDistribution = [];
        for ($i = 1; $i <= 5; $i++) {
            $ratingDistribution[$i] = Review::where('reviewed_user_id', $user->user_id)
                ->where('review_type', 'parent_to_babysitter')
                ->where('rating', $i)
                ->count();
        }

        // Recent reviews (last 30 days)
        $recentReviews = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->where('created_at', '>=', Carbon::now()->subDays(30))
            ->count();

        return [
            'total_reviews' => $totalReviews,
            'average_rating' => round($averageRating, 2),
            'recent_reviews_30_days' => $recentReviews,
            'rating_distribution' => $ratingDistribution,
            'recommendation_rate' => $this->getRecommendationRate($user)
        ];
    }

    /**
     * Get Recommendation Rate
     */
    private function getRecommendationRate($user): float
    {
        $totalReviews = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->count();

        $recommendedReviews = Review::where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->where('would_recommend', true)
            ->count();

        return $totalReviews > 0 ? round(($recommendedReviews / $totalReviews) * 100, 2) : 0;
    }

    /**
     * Get Recent Activity
     */
    private function getRecentActivity($user): array
    {
        // Recent bookings (last 10)
        $recentBookings = Booking::with(['parent'])
            ->where('babysitter_id', $user->user_id)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->map(function ($booking) {
                $parentName = $booking->parent ? $booking->parent->first_name . ' ' . $booking->parent->last_name : 'Unknown Parent';

                return [
                    'type' => 'booking',
                    'id' => $booking->booking_id,
                    'title' => 'New Booking',
                    'description' => "Booking #{$booking->booking_id} from {$parentName}",
                    'amount' => $booking->total_amount,
                    'status' => $booking->booking_status,
                    'timestamp' => $booking->created_at,
                    'user' => [
                        'name' => $parentName,
                        'type' => 'parent'
                    ]
                ];
            });

        // Recent payouts (last 10)
        $recentPayouts = Payout::where('babysitter_id', $user->user_id)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->map(function ($payout) {
                return [
                    'type' => 'payout',
                    'id' => $payout->payout_id,
                    'title' => 'Payout Processed',
                    'description' => "Payout of {$payout->amount}",
                    'amount' => $payout->amount,
                    'status' => $payout->payout_status,
                    'timestamp' => $payout->created_at,
                    'user' => [
                        'name' => 'System',
                        'type' => 'system'
                    ]
                ];
            });

        // Recent reviews (last 10)
        $recentReviews = Review::with(['reviewer'])
            ->where('reviewed_user_id', $user->user_id)
            ->where('review_type', 'parent_to_babysitter')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->map(function ($review) {
                $reviewerName = $review->reviewer ? $review->reviewer->first_name . ' ' . $review->reviewer->last_name : 'Unknown User';

                return [
                    'type' => 'review',
                    'id' => $review->review_id,
                    'title' => 'New Review',
                    'description' => "{$review->rating}★ review from {$reviewerName}",
                    'rating' => $review->rating,
                    'timestamp' => $review->created_at,
                    'user' => [
                        'name' => $reviewerName,
                        'type' => 'parent'
                    ]
                ];
            });

        // Combine and sort all activities
        $allActivities = collect()
            ->merge($recentBookings)
            ->merge($recentPayouts)
            ->merge($recentReviews)
            ->sortByDesc('timestamp')
            ->values()
            ->take(15);

        return $allActivities->toArray();
    }

    /**
     * Get Upcoming Bookings
     */
    private function getUpcomingBookings($user): array
    {
        return Booking::with(['parent', 'occupationCategory'])
            ->where('babysitter_id', $user->user_id)
            ->whereIn('booking_status', ['confirmed', 'active'])
            ->where('start_date', '>=', Carbon::today())
            ->orderBy('start_date', 'asc')
            ->limit(5)
            ->get()
            ->map(function ($booking) {
                $parentName = $booking->parent ? $booking->parent->first_name . ' ' . $booking->parent->last_name : 'Unknown Parent';
                $categoryName = $booking->occupationCategory ? $booking->occupationCategory->category_name : 'Unknown Category';

                return [
                    'booking_id' => $booking->booking_id,
                    'parent_name' => $parentName,
                    'category_name' => $categoryName,
                    'start_date' => $booking->start_date,
                    'end_date' => $booking->end_date,
                    'total_amount' => $booking->total_amount,
                    'booking_status' => $booking->booking_status,
                    'expected_hours' => $booking->total_hours
                ];
            })
            ->toArray();
    }

    /**
     * Get Babysitter Quick Stats
     */
    public function getQuickStats(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            if (!$user || !$this->isBabysitter($user)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized access'
                ], 403);
            }

            $quickStats = DB::transaction(function () use ($user) {
                // Total earnings
                $totalEarnings = Payment::where('babysitter_id', $user->user_id)
                    ->where('payment_status', 'completed')
                    ->sum('babysitter_payout_amount');

                // Pending payouts
                $pendingPayouts = Payout::where('babysitter_id', $user->user_id)
                    ->where('payout_status', 'pending')
                    ->sum('amount');

                // Active bookings
                $activeBookings = Booking::where('babysitter_id', $user->user_id)
                    ->where('booking_status', 'active')
                    ->count();

                // Completed bookings
                $completedBookings = Booking::where('babysitter_id', $user->user_id)
                    ->where('booking_status', 'completed')
                    ->count();

                // Total reviews
                $totalReviews = Review::where('reviewed_user_id', $user->user_id)
                    ->where('review_type', 'parent_to_babysitter')
                    ->count();

                // Average rating
                $averageRating = Review::where('reviewed_user_id', $user->user_id)
                    ->where('review_type', 'parent_to_babysitter')
                    ->avg('rating') ?? 0;

                // Today's earnings
                $todayEarnings = Payment::where('babysitter_id', $user->user_id)
                    ->where('payment_status', 'completed')
                    ->whereDate('created_at', Carbon::today())
                    ->sum('babysitter_payout_amount');

                return [
                    'total_earnings' => $totalEarnings,
                    'pending_payouts' => $pendingPayouts,
                    'active_bookings' => $activeBookings,
                    'completed_bookings' => $completedBookings,
                    'total_reviews' => $totalReviews,
                    'average_rating' => round($averageRating, 2),
                    'today_earnings' => $todayEarnings,
                    'upcoming_bookings' => Booking::where('babysitter_id', $user->user_id)
                        ->where('booking_status', 'confirmed')
                        ->where('start_date', '>=', Carbon::today())
                        ->count()
                ];
            });

            return response()->json([
                'success' => true,
                'data' => $quickStats
            ]);

        } catch (\Exception $e) {
            Log::error('Babysitter Quick Stats Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch quick stats'
            ], 500);
        }
    }
}