import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Package, DollarSign, AlertTriangle, FolderOpen, TrendingUp, TrendingDown } from 'lucide-react';
import api from '../services/api';
import { formatCurrency, formatDate } from '../utils/helpers';

function StatCard({ title, value, icon: Icon, color, subtitle }) {
  const colors = {
    blue: 'bg-blue-50 text-blue-600',
    green: 'bg-green-50 text-green-600',
    red: 'bg-red-50 text-red-600',
    yellow: 'bg-yellow-50 text-yellow-600',
  };

  return (
    <div className="card">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-sm text-gray-500">{title}</p>
          <p className="text-2xl font-bold mt-1">{value}</p>
          {subtitle && <p className="text-xs text-gray-400 mt-1">{subtitle}</p>}
        </div>
        <div className={`p-3 rounded-lg ${colors[color]}`}>
          <Icon size={24} />
        </div>
      </div>
    </div>
  );
}

export default function Dashboard() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/reports/dashboard')
      .then((res) => setData(res.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-10 w-10 border-4 border-primary-600 border-t-transparent" />
      </div>
    );
  }

  const { stats, recentMovements, lowStockProducts } = data;

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-gray-500 mt-1">Overview of your inventory</p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard title="Total Products" value={stats.total_products} icon={Package} color="blue" />
        <StatCard
          title="Inventory Value"
          value={formatCurrency(stats.total_value)}
          icon={DollarSign}
          color="green"
        />
        <StatCard
          title="Low Stock Items"
          value={stats.low_stock_count}
          icon={AlertTriangle}
          color="red"
          subtitle="Needs attention"
        />
        <StatCard title="Categories" value={stats.total_categories} icon={FolderOpen} color="yellow" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Recent Stock Movements</h2>
            <Link to="/stock" className="text-sm text-primary-600 hover:underline">View all</Link>
          </div>
          {recentMovements.length === 0 ? (
            <p className="text-gray-500 text-sm">No recent movements</p>
          ) : (
            <div className="space-y-3">
              {recentMovements.map((m) => (
                <div key={m.id} className="flex items-center justify-between py-2 border-b last:border-0">
                  <div className="flex items-center gap-3">
                    {m.type === 'in' ? (
                      <TrendingUp size={18} className="text-green-500" />
                    ) : (
                      <TrendingDown size={18} className="text-red-500" />
                    )}
                    <div>
                      <p className="text-sm font-medium">{m.product_name}</p>
                      <p className="text-xs text-gray-500">{formatDate(m.created_at)}</p>
                    </div>
                  </div>
                  <span
                    className={`text-sm font-semibold ${
                      m.type === 'in' ? 'text-green-600' : 'text-red-600'
                    }`}
                  >
                    {m.type === 'in' ? '+' : '-'}{m.quantity}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Low Stock Alert</h2>
            <Link to="/products?low_stock=true" className="text-sm text-primary-600 hover:underline">
              View all
            </Link>
          </div>
          {lowStockProducts.length === 0 ? (
            <p className="text-green-600 text-sm">All products are well stocked!</p>
          ) : (
            <div className="space-y-3">
              {lowStockProducts.map((p) => (
                <div key={p.id} className="flex items-center justify-between py-2 border-b last:border-0">
                  <div>
                    <p className="text-sm font-medium">{p.name}</p>
                    <p className="text-xs text-gray-500">{p.sku}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-semibold text-red-600">{p.quantity} left</p>
                    <p className="text-xs text-gray-500">Min: {p.min_stock_level}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
