import { useEffect, useState } from 'react';
import { TrendingUp, TrendingDown, RefreshCw } from 'lucide-react';
import api from '../services/api';
import { formatDate } from '../utils/helpers';

export default function StockMovements() {
  const [movements, setMovements] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({ type: '', start_date: '', end_date: '' });

  const fetchMovements = () => {
    setLoading(true);
    const params = {};
    if (filters.type) params.type = filters.type;
    if (filters.start_date) params.start_date = filters.start_date;
    if (filters.end_date) params.end_date = filters.end_date;

    api.get('/stock', { params })
      .then((res) => setMovements(res.data.movements))
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchMovements();
  }, []);

  const typeIcons = {
    in: { icon: TrendingUp, color: 'text-green-600 bg-green-50' },
    out: { icon: TrendingDown, color: 'text-red-600 bg-red-50' },
    adjustment: { icon: RefreshCw, color: 'text-blue-600 bg-blue-50' },
  };

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Stock Movements</h1>
        <p className="text-gray-500 mt-1">Track all inventory changes</p>
      </div>

      <div className="card mb-6">
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
          <div>
            <label className="label">Type</label>
            <select
              className="input"
              value={filters.type}
              onChange={(e) => setFilters({ ...filters, type: e.target.value })}
            >
              <option value="">All types</option>
              <option value="in">Stock In</option>
              <option value="out">Stock Out</option>
              <option value="adjustment">Adjustment</option>
            </select>
          </div>
          <div>
            <label className="label">Start Date</label>
            <input
              type="date"
              className="input"
              value={filters.start_date}
              onChange={(e) => setFilters({ ...filters, start_date: e.target.value })}
            />
          </div>
          <div>
            <label className="label">End Date</label>
            <input
              type="date"
              className="input"
              value={filters.end_date}
              onChange={(e) => setFilters({ ...filters, end_date: e.target.value })}
            />
          </div>
          <div className="flex items-end">
            <button onClick={fetchMovements} className="btn-primary w-full">Apply Filters</button>
          </div>
        </div>
      </div>

      <div className="card overflow-x-auto">
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-4 border-primary-600 border-t-transparent" />
          </div>
        ) : movements.length === 0 ? (
          <p className="text-center text-gray-500 py-12">No stock movements found</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b text-left text-gray-500">
                <th className="pb-3 font-medium">Date</th>
                <th className="pb-3 font-medium">Product</th>
                <th className="pb-3 font-medium">Type</th>
                <th className="pb-3 font-medium">Qty</th>
                <th className="pb-3 font-medium">Before</th>
                <th className="pb-3 font-medium">After</th>
                <th className="pb-3 font-medium">Reason</th>
                <th className="pb-3 font-medium">User</th>
              </tr>
            </thead>
            <tbody>
              {movements.map((m) => {
                const { icon: Icon, color } = typeIcons[m.type] || typeIcons.adjustment;
                return (
                  <tr key={m.id} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="py-3 text-gray-600 whitespace-nowrap">{formatDate(m.created_at)}</td>
                    <td className="py-3">
                      <p className="font-medium">{m.product_name}</p>
                      <p className="text-xs text-gray-500">{m.sku}</p>
                    </td>
                    <td className="py-3">
                      <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${color}`}>
                        <Icon size={12} />
                        {m.type}
                      </span>
                    </td>
                    <td className="py-3 font-semibold">{m.quantity}</td>
                    <td className="py-3 text-gray-600">{m.previous_quantity}</td>
                    <td className="py-3 font-medium">{m.new_quantity}</td>
                    <td className="py-3 text-gray-600">{m.reason || '—'}</td>
                    <td className="py-3 text-gray-600">{m.user_name || '—'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
