import { useState } from 'react';
import { FileText, Download, AlertTriangle, ArrowLeftRight } from 'lucide-react';
import api from '../services/api';
import { useAuth } from '../context/AuthContext';
import Alert from '../components/Alert';
import { formatCurrency, formatDate } from '../utils/helpers';

export default function Reports() {
  const [activeTab, setActiveTab] = useState('inventory');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [dateRange, setDateRange] = useState({ start_date: '', end_date: '' });
  const { hasRole } = useAuth();

  const canExport = hasRole('admin', 'manager');

  const tabs = [
    { id: 'inventory', label: 'Inventory Report', icon: FileText },
    { id: 'low-stock', label: 'Low Stock', icon: AlertTriangle },
    { id: 'movements', label: 'Stock Movements', icon: ArrowLeftRight },
  ];

  const fetchReport = async (type) => {
    setLoading(true);
    setError('');
    setActiveTab(type);
    try {
      let endpoint = `/reports/${type}`;
      const params = type === 'movements' ? dateRange : {};
      const res = await api.get(endpoint, { params });
      setData(res.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load report');
      setData(null);
    } finally {
      setLoading(false);
    }
  };

  const downloadCsv = async (type) => {
    try {
      const params = { type, ...dateRange };
      const res = await api.get('/reports/export/csv', {
        params,
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.download = `${type}-report.csv`;
      link.click();
      window.URL.revokeObjectURL(url);
    } catch {
      setError('Failed to download CSV');
    }
  };

  const downloadPdf = async () => {
    try {
      const res = await api.get('/reports/inventory/pdf', { responseType: 'blob' });
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.download = 'inventory-report.pdf';
      link.click();
      window.URL.revokeObjectURL(url);
    } catch {
      setError('Failed to download PDF');
    }
  };

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Reports</h1>
        <p className="text-gray-500 mt-1">Generate and export inventory reports</p>
      </div>

      <Alert type="error" message={error} onClose={() => setError('')} />

      <div className="flex flex-wrap gap-2 mb-6">
        {tabs.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            onClick={() => fetchReport(id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              activeTab === id
                ? 'bg-primary-600 text-white'
                : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50'
            }`}
          >
            <Icon size={16} />
            {label}
          </button>
        ))}
      </div>

      {activeTab === 'movements' && (
        <div className="card mb-6">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div>
              <label className="label">Start Date</label>
              <input
                type="date"
                className="input"
                value={dateRange.start_date}
                onChange={(e) => setDateRange({ ...dateRange, start_date: e.target.value })}
              />
            </div>
            <div>
              <label className="label">End Date</label>
              <input
                type="date"
                className="input"
                value={dateRange.end_date}
                onChange={(e) => setDateRange({ ...dateRange, end_date: e.target.value })}
              />
            </div>
            <div className="flex items-end">
              <button onClick={() => fetchReport('movements')} className="btn-primary w-full">
                Generate Report
              </button>
            </div>
          </div>
        </div>
      )}

      {!data && !loading && (
        <div className="card text-center py-16">
          <FileText size={48} className="mx-auto text-gray-300 mb-4" />
          <p className="text-gray-500">Select a report type above to generate</p>
        </div>
      )}

      {loading && (
        <div className="card flex justify-center py-16">
          <div className="animate-spin rounded-full h-10 w-10 border-4 border-primary-600 border-t-transparent" />
        </div>
      )}

      {data && !loading && (
        <div>
          <div className="flex flex-wrap items-center justify-between gap-4 mb-4">
            <p className="text-sm text-gray-500">
              Generated: {formatDate(data.generatedAt)}
            </p>
            {canExport && (
              <div className="flex gap-2">
                <button onClick={() => downloadCsv(activeTab === 'low-stock' ? 'low-stock' : activeTab === 'movements' ? 'movements' : 'inventory')} className="btn-secondary">
                  <Download size={16} /> Export CSV
                </button>
                {activeTab === 'inventory' && (
                  <button onClick={downloadPdf} className="btn-primary">
                    <Download size={16} /> Export PDF
                  </button>
                )}
              </div>
            )}
          </div>

          {activeTab === 'inventory' && (
            <div>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Total Products</p>
                  <p className="text-2xl font-bold mt-1">{data.totals.total_products}</p>
                </div>
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Total Quantity</p>
                  <p className="text-2xl font-bold mt-1">{data.totals.total_quantity}</p>
                </div>
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Total Value</p>
                  <p className="text-2xl font-bold mt-1">{formatCurrency(data.totals.total_value)}</p>
                </div>
              </div>
              <div className="card overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b text-left text-gray-500">
                      <th className="pb-3 font-medium">Product</th>
                      <th className="pb-3 font-medium">SKU</th>
                      <th className="pb-3 font-medium">Category</th>
                      <th className="pb-3 font-medium">Qty</th>
                      <th className="pb-3 font-medium">Price</th>
                      <th className="pb-3 font-medium">Value</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.products.map((p) => (
                      <tr key={p.id} className="border-b last:border-0">
                        <td className="py-2 font-medium">{p.name}</td>
                        <td className="py-2 text-gray-600">{p.sku}</td>
                        <td className="py-2 text-gray-600">{p.category_name || '—'}</td>
                        <td className="py-2">{p.quantity}</td>
                        <td className="py-2">{formatCurrency(p.unit_price)}</td>
                        <td className="py-2 font-medium">{formatCurrency(p.total_value)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'low-stock' && (
            <div className="card overflow-x-auto">
              <p className="text-sm text-red-600 font-medium mb-4">{data.count} items need restocking</p>
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left text-gray-500">
                    <th className="pb-3 font-medium">Product</th>
                    <th className="pb-3 font-medium">SKU</th>
                    <th className="pb-3 font-medium">Category</th>
                    <th className="pb-3 font-medium">Current</th>
                    <th className="pb-3 font-medium">Min Level</th>
                    <th className="pb-3 font-medium">Shortage</th>
                  </tr>
                </thead>
                <tbody>
                  {data.products.map((p) => (
                    <tr key={p.id} className="border-b last:border-0">
                      <td className="py-2 font-medium">{p.name}</td>
                      <td className="py-2 text-gray-600">{p.sku}</td>
                      <td className="py-2 text-gray-600">{p.category_name || '—'}</td>
                      <td className="py-2 text-red-600 font-semibold">{p.quantity}</td>
                      <td className="py-2">{p.min_stock_level}</td>
                      <td className="py-2 text-red-600">{p.shortage}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'movements' && (
            <div>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Total Movements</p>
                  <p className="text-2xl font-bold mt-1">{data.summary.total_movements}</p>
                </div>
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Stock In</p>
                  <p className="text-2xl font-bold mt-1 text-green-600">{data.summary.total_in}</p>
                </div>
                <div className="card text-center">
                  <p className="text-sm text-gray-500">Stock Out</p>
                  <p className="text-2xl font-bold mt-1 text-red-600">{data.summary.total_out}</p>
                </div>
              </div>
              <div className="card overflow-x-auto">
                <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">Reason</th>
                      <th className="pb-3 font-medium">User</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.movements.map((m) => (
                      <tr key={m.id} className="border-b last:border-0">
                        <td className="py-2 text-gray-600">{formatDate(m.created_at)}</td>
                        <td className="py-2 font-medium">{m.product_name}</td>
                        <td className="py-2 capitalize">{m.type}</td>
                        <td className="py-2">{m.quantity}</td>
                        <td className="py-2 text-gray-600">{m.reason || '—'}</td>
                        <td className="py-2 text-gray-600">{m.user_name || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
