'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  DollarSign,
  TrendingUp,
  TrendingDown,
  Calendar,
  Home,
  Building,
  Download,
  Filter,
  ChevronLeft,
  ChevronRight,
  ArrowLeft,
  Loader2,
  Eye,
  PieChart,
  BarChart,
  LineChart,
  Wallet,
  CreditCard,
  Clock,
  CheckCircle,
  XCircle
} from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';

const StatCard = ({ title, value, change, icon: Icon, color, trend }) => {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all"
    >
      <div className="flex justify-between items-start mb-4">
        <div className={`w-12 h-12 ${color} rounded-xl flex items-center justify-center`}>
          <Icon className="w-6 h-6 text-white" />
        </div>
        <div className={`flex items-center gap-1 text-sm ${trend === 'up' ? 'text-green-600' : 'text-red-600'}`}>
          {trend === 'up' ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
          <span>{Math.abs(change)}%</span>
        </div>
      </div>
      <h3 className="text-sm text-gray-600 mb-1">{title}</h3>
      <div className="text-2xl font-bold text-gray-900">{value}</div>
    </motion.div>
  );
};

const PropertyProfitCard = ({ property, onViewDetails }) => {
  const formatCurrency = (amount) => {
    return amount?.toLocaleString() + ' ل.س';
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-all"
    >
      <div className="p-5">
        <div className="flex justify-between items-start mb-4">
          <div>
            <h3 className="font-bold text-gray-900 mb-1">{property.title}</h3>
            <p className="text-sm text-gray-500">{property.location}</p>
          </div>
          <span className={`px-2 py-1 rounded-lg text-xs font-medium ${
            property.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
          }`}>
            {property.status === 'active' ? 'نشط' : 'غير نشط'}
          </span>
        </div>

        <div className="grid grid-cols-2 gap-4 mb-4">
          <div className="bg-gray-50 p-3 rounded-xl text-center">
            <DollarSign className="w-5 h-5 text-amber-500 mx-auto mb-1" />
            <div className="text-xs text-gray-500">إجمالي الأرباح</div>
            <div className="text-lg font-bold text-amber-600">{formatCurrency(property.totalProfit)}</div>
          </div>
          <div className="bg-gray-50 p-3 rounded-xl text-center">
            <Calendar className="w-5 h-5 text-blue-500 mx-auto mb-1" />
            <div className="text-xs text-gray-500">عدد الحجوزات</div>
            <div className="text-lg font-bold text-blue-600">{property.totalBookings}</div>
          </div>
        </div>

        <div className="space-y-2 mb-4">
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">هذا الشهر</span>
            <span className="font-medium text-gray-900">{formatCurrency(property.monthlyProfit)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">الأسبوع الماضي</span>
            <span className="font-medium text-gray-900">{formatCurrency(property.weeklyProfit)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">متوسط السعر اليومي</span>
            <span className="font-medium text-gray-900">{formatCurrency(property.avgDailyPrice)}</span>
          </div>
        </div>

        <button
          onClick={() => onViewDetails(property)}
          className="w-full bg-gray-100 text-gray-700 py-2 rounded-xl text-sm font-medium hover:bg-gray-200 transition-colors flex items-center justify-center gap-2"
        >
          <Eye className="w-4 h-4" />
          عرض التفاصيل
        </button>
      </div>
    </motion.div>
  );
};

const ProfitDetailsModal = ({ property, isOpen, onClose }) => {
  if (!isOpen || !property) return null;

  const formatCurrency = (amount) => {
    return amount?.toLocaleString() + ' ل.س';
  };

  const monthlyData = [
    { month: 'يناير', profit: 1250000 },
    { month: 'فبراير', profit: 1500000 },
    { month: 'مارس', profit: 1800000 },
    { month: 'إبريل', profit: 2100000 },
    { month: 'مايو', profit: 2500000 },
    { month: 'يونيو', profit: 2300000 }
  ];

  const maxProfit = Math.max(...monthlyData.map(d => d.profit));

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, y: 20 }}
        animate={{ scale: 1, y: 0 }}
        exit={{ scale: 0.9, y: 20 }}
        className="bg-white rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="sticky top-0 bg-gradient-to-r from-amber-500 to-amber-600 p-6 text-white">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-xl font-bold">{property.title}</h2>
              <p className="text-amber-100 text-sm mt-1">{property.location}</p>
            </div>
            <button onClick={onClose} className="p-1 hover:bg-white/20 rounded-full">
              <XCircle className="w-6 h-6" />
            </button>
          </div>
        </div>

        <div className="p-6 space-y-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-amber-50 p-4 rounded-xl text-center">
              <div className="text-2xl font-bold text-amber-600">{formatCurrency(property.totalProfit)}</div>
              <div className="text-xs text-gray-600 mt-1">إجمالي الأرباح</div>
            </div>
            <div className="bg-blue-50 p-4 rounded-xl text-center">
              <div className="text-2xl font-bold text-blue-600">{property.totalBookings}</div>
              <div className="text-xs text-gray-600 mt-1">عدد الحجوزات</div>
            </div>
            <div className="bg-green-50 p-4 rounded-xl text-center">
              <div className="text-2xl font-bold text-green-600">{property.occupancyRate}%</div>
              <div className="text-xs text-gray-600 mt-1">نسبة الإشغال</div>
            </div>
            <div className="bg-purple-50 p-4 rounded-xl text-center">
              <div className="text-2xl font-bold text-purple-600">{formatCurrency(property.avgDailyPrice)}</div>
              <div className="text-xs text-gray-600 mt-1">متوسط السعر اليومي</div>
            </div>
          </div>

          <div className="bg-gray-50 p-4 rounded-xl">
            <h3 className="font-bold text-gray-900 mb-4">الأرباح الشهرية</h3>
            <div className="space-y-3">
              {monthlyData.map((data, index) => (
                <div key={index}>
                  <div className="flex justify-between text-sm mb-1">
                    <span className="text-gray-600">{data.month}</span>
                    <span className="font-medium text-gray-900">{formatCurrency(data.profit)}</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${(data.profit / maxProfit) * 100}%` }}
                      transition={{ duration: 0.8, delay: index * 0.1 }}
                      className="bg-amber-500 h-2 rounded-full"
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-gray-50 p-4 rounded-xl">
            <h3 className="font-bold text-gray-900 mb-4">آخر الحجوزات</h3>
            <div className="space-y-3">
              {property.recentBookings?.map((booking, index) => (
                <div key={index} className="bg-white p-3 rounded-lg flex justify-between items-center">
                  <div>
                    <p className="font-medium text-gray-900">{booking.tenantName}</p>
                    <p className="text-xs text-gray-500">{booking.startDate} - {booking.endDate}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-bold text-amber-600">{formatCurrency(booking.amount)}</p>
                    <p className="text-xs text-gray-500">{booking.status === 'completed' ? 'مكتمل' : 'قيد التنفيذ'}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
};

export default function OwnerProfitsPage() {
  const router = useRouter();
  const [user, setUser] = useState(null);
  const [properties, setProperties] = useState([]);
  const [filteredProperties, setFilteredProperties] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedProperty, setSelectedProperty] = useState(null);
  const [dateRange, setDateRange] = useState({ start: '', end: '' });
  const [selectedPeriod, setSelectedPeriod] = useState('month'); // month, year, all

  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const userData = JSON.parse(storedUser);
      if (userData.role !== 'owner') {
        router.push('/');
      } else {
        setUser(userData);
        loadProfitsData();
      }
    } else {
      router.push('/auth/choose-role');
    }
  }, [router]);

  const loadProfitsData = () => {
    const storedProfits = localStorage.getItem('ownerProfits');
    if (storedProfits) {
      setProperties(JSON.parse(storedProfits));
      setFilteredProperties(JSON.parse(storedProfits));
    } else {
      const mockProperties = [
        {
          id: 1,
          title: 'فيلا فاخرة في المزة',
          location: 'دمشق، المزة',
          status: 'active',
          totalProfit: 12500000,
          totalBookings: 24,
          monthlyProfit: 3200000,
          weeklyProfit: 850000,
          avgDailyPrice: 500000,
          occupancyRate: 78,
          recentBookings: [
            { tenantName: 'أحمد محمد', startDate: '2024-03-10', endDate: '2024-03-15', amount: 2500000, status: 'completed' },
            { tenantName: 'سارة أحمد', startDate: '2024-03-05', endDate: '2024-03-08', amount: 1500000, status: 'completed' }
          ]
        },
        {
          id: 2,
          title: 'شقة حديثة في الشهباء',
          location: 'حلب، الشهباء',
          status: 'active',
          totalProfit: 5800000,
          totalBookings: 18,
          monthlyProfit: 1500000,
          weeklyProfit: 400000,
          avgDailyPrice: 250000,
          occupancyRate: 65,
          recentBookings: [
            { tenantName: 'محمد علي', startDate: '2024-03-12', endDate: '2024-03-14', amount: 750000, status: 'completed' }
          ]
        },
        {
          id: 3,
          title: 'بيت عائلي في بابا عمرو',
          location: 'حمص، بابا عمرو',
          status: 'active',
          totalProfit: 8400000,
          totalBookings: 12,
          monthlyProfit: 2100000,
          weeklyProfit: 525000,
          avgDailyPrice: 350000,
          occupancyRate: 45,
          recentBookings: []
        }
      ];
      setProperties(mockProperties);
      setFilteredProperties(mockProperties);
      localStorage.setItem('ownerProfits', JSON.stringify(mockProperties));
    }
    setIsLoading(false);
  };

  const totalStats = {
    totalProfit: properties.reduce((sum, p) => sum + p.totalProfit, 0),
    totalBookings: properties.reduce((sum, p) => sum + p.totalBookings, 0),
    avgOccupancy: Math.round(properties.reduce((sum, p) => sum + p.occupancyRate, 0) / properties.length),
    activeProperties: properties.filter(p => p.status === 'active').length
  };

  const formatCurrency = (amount) => {
    if (amount >= 1000000) {
      return (amount / 1000000).toFixed(1) + ' مليون ل.س';
    }
    return amount?.toLocaleString() + ' ل.س';
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-amber-500 animate-spin mx-auto mb-4" />
          <p className="text-gray-600">جاري تحميل بيانات الأرباح...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <Toaster position="top-center" reverseOrder={false} />
      
      <ProfitDetailsModal
        property={selectedProperty}
        isOpen={!!selectedProperty}
        onClose={() => setSelectedProperty(null)}
      />

      <div className="container mx-auto px-4">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4"
        >
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">الأرباح والإحصائيات</h1>
            <p className="text-gray-600">مرحباً {user?.name}، إليك ملخص أرباحك</p>
          </div>
          
          <div className="flex gap-3">
            <select
              value={selectedPeriod}
              onChange={(e) => setSelectedPeriod(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500"
            >
              <option value="month">آخر 30 يوم</option>
              <option value="year">آخر 12 شهر</option>
              <option value="all">جميع الفترات</option>
            </select>
            {/* <button className="px-4 py-2 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-colors flex items-center gap-2">
              <Download className="w-5 h-5" />
              تصدير التقرير
            </button> */}
          </div>
        </motion.div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <StatCard
            title="إجمالي الأرباح"
            value={formatCurrency(totalStats.totalProfit)}
            change={12.5}
            icon={Wallet}
            color="bg-amber-500"
            trend="up"
          />
          <StatCard
            title="عدد الحجوزات"
            value={totalStats.totalBookings}
            change={8.2}
            icon={Calendar}
            color="bg-blue-500"
            trend="up"
          />
          <StatCard
            title="متوسط نسبة الإشغال"
            value={`${totalStats.avgOccupancy}%`}
            change={5.3}
            icon={PieChart}
            color="bg-green-500"
            trend="up"
          />
          <StatCard
            title="العقارات النشطة"
            value={totalStats.activeProperties}
            change={0}
            icon={Building}
            color="bg-purple-500"
            trend="up"
          />
        </div>

        <div className="mb-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold text-gray-900">أرباح العقارات</h2>
            <div className="flex gap-2">
              <button
                onClick={() => setFilteredProperties(properties)}
                className="px-3 py-1.5 bg-gray-100 rounded-lg text-sm hover:bg-gray-200 transition-colors"
              >
                عرض الكل
              </button>
            </div>
          </div>

          {filteredProperties.length === 0 ? (
            <div className="bg-white rounded-2xl p-12 text-center border-2 border-dashed border-gray-300">
              <div className="w-24 h-24 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <DollarSign className="w-12 h-12 text-amber-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">لا توجد بيانات</h3>
              <p className="text-gray-600">لا توجد أرباح مسجلة حتى الآن</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredProperties.map((property) => (
                <PropertyProfitCard
                  key={property.id}
                  property={property}
                  onViewDetails={setSelectedProperty}
                />
              ))}
            </div>
          )}
        </div>

        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.6 }}
          className="bg-gradient-to-r from-amber-500 to-amber-600 rounded-2xl p-6 text-white mt-8"
        >
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <h3 className="text-lg font-bold mb-1">احصل على المزيد من الأرباح</h3>
              <p className="text-amber-100 text-sm">أضف عقارات جديدة وحسّن أسعارك لزيادة الإشغال</p>
            </div>
            <Link
              href="/owner/properties/add"
              className="px-6 py-2 bg-white text-amber-600 rounded-xl font-medium hover:bg-amber-50 transition-colors"
            >
              إضافة عقار جديد
            </Link>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
