import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  Alert,
  Button,
  Card,
  Col,
  Input,
  Progress,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import {
  AppstoreOutlined,
  BarcodeOutlined,
  InboxOutlined,
  ReloadOutlined,
  ShoppingCartOutlined,
  ShoppingOutlined,
  TeamOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { request } from '@/request';
import { selectCurrentAdmin } from '@/redux/auth/selectors';
import { canAccessEntityAction, canAccessPermission } from '@/utils/permissions';
import useMoney from '@/settings/useMoney';
import { DEFAULT_CURRENCY_CODE } from '@/constants/platformDefaults';
import { WorkflowPage } from './shared';

const stockStatus = (available, reorderLevel) => {
  if (Number(available || 0) <= 0) return { label: 'Out of stock', color: 'red', percent: 5 };
  if (Number(available || 0) <= Number(reorderLevel || 0)) return { label: 'Reorder now', color: 'orange', percent: 35 };
  return { label: 'Healthy', color: 'green', percent: 85 };
};

const recordName = (value, fallback = '-') => {
  if (!value) return fallback;
  if (typeof value === 'object') return value.name || value.title || fallback;
  return value;
};

export default function InventoryManagement() {
  const [data, setData] = useState({
    products: [],
    categories: [],
    suppliers: [],
    orders: [],
    purchases: [],
    stocks: [],
    movements: [],
  });
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({ search: '', status: undefined, branch: undefined });
  const currentAdmin = useSelector(selectCurrentAdmin);
  const { moneyFormatter } = useMoney();

  const canReadProducts = canAccessEntityAction(currentAdmin, 'product', 'read');
  const canReadOrders = canAccessEntityAction(currentAdmin, 'order', 'read');
  const canReadPurchases = canAccessEntityAction(currentAdmin, 'purchaseorder', 'read');
  const canUsePos = canAccessPermission(currentAdmin, 'inventory.pos.read');

  const load = async () => {
    setLoading(true);
    try {
      const [products, categories, suppliers, orders, purchases, stocks, movements] = await Promise.all([
        request.list({ entity: 'product', options: { page: 1, items: 200 } }),
        request.list({ entity: 'productcategory', options: { page: 1, items: 100 } }),
        request.list({ entity: 'supplier', options: { page: 1, items: 100 } }),
        request.list({ entity: 'order', options: { page: 1, items: 100 } }),
        request.list({ entity: 'purchaseorder', options: { page: 1, items: 100 } }),
        request.list({ entity: 'inventorystock', options: { page: 1, items: 200 } }),
        request.list({ entity: 'stockmovement', options: { page: 1, items: 100 } }),
      ]);
      setData({
        products: products?.result || [],
        categories: categories?.result || [],
        suppliers: suppliers?.result || [],
        orders: orders?.result || [],
        purchases: purchases?.result || [],
        stocks: stocks?.result || [],
        movements: movements?.result || [],
      });
    } catch {
      message.error('Inventory data could not be loaded.');
    } finally {
      setLoading(false);
    }
  };

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

  const branchOptions = useMemo(() => {
    const branches = data.stocks.map((stock) => stock.branch).filter(Boolean);
    return [...new Map(branches.map((branch) => [typeof branch === 'object' ? branch._id : branch, branch])).values()].map((branch) => ({
      value: typeof branch === 'object' ? branch._id : branch,
      label: recordName(branch, 'Branch'),
    }));
  }, [data.stocks]);

  const productRows = useMemo(() => {
    const query = filters.search.trim().toLowerCase();
    return data.products
      .map((product) => {
        const productStocks = data.stocks.filter((stock) => {
          const productId = typeof stock.product === 'object' ? stock.product._id : stock.product;
          return productId === product._id;
        });
        const matchingStocks = filters.branch
          ? productStocks.filter((stock) => (typeof stock.branch === 'object' ? stock.branch._id : stock.branch) === filters.branch)
          : productStocks;
        const onHand =
          matchingStocks.length > 0
            ? matchingStocks.reduce((sum, stock) => sum + Number(stock.onHand || 0), 0)
            : Number(product.stockQuantity || 0);
        const reserved = matchingStocks.reduce((sum, stock) => sum + Number(stock.reserved || 0), 0);
        const reorderLevel =
          matchingStocks.length > 0
            ? Math.max(...matchingStocks.map((stock) => Number(stock.reorderLevel || 0)))
            : Number(product.reorderLevel || 0);
        const available = onHand - reserved;
        const status = stockStatus(available, reorderLevel);
        return { ...product, onHand, reserved, available, reorderLevel, stockStatus: status, branchStockCount: productStocks.length };
      })
      .filter((product) => {
        if (filters.status && product.status !== filters.status) return false;
        if (!query) return true;
        return [product.name, product.sku, recordName(product.category), recordName(product.supplier)]
          .filter(Boolean)
          .some((value) => String(value).toLowerCase().includes(query));
      });
  }, [data.products, data.stocks, filters]);

  const lowStockRows = productRows.filter((product) => product.stockStatus.color !== 'green');
  const inventoryValue = productRows.reduce(
    (sum, product) => sum + Number(product.available || 0) * Number(product.salePrice?.amount || product.purchasePrice?.amount || 0),
    0
  );
  const pendingPurchases = data.purchases.filter((item) => !['received', 'cancelled', 'refunded'].includes(item.status)).length;
  const openOrders = data.orders.filter((item) => !['delivered', 'cancelled', 'returned', 'refunded'].includes(item.status)).length;

  const statusOptions = [
    { value: 'active', label: 'Active' },
    { value: 'draft', label: 'Draft' },
    { value: 'archived', label: 'Archived' },
  ];

  return (
    <WorkflowPage
      title="Inventory Management"
      description="Control catalog, branch stock, supplier purchasing, order fulfillment, low-stock signals, and POS readiness from one workspace."
      permission="product.read"
      extra={
        <Space wrap>
          <Button icon={<ReloadOutlined />} onClick={load}>
            Refresh
          </Button>
          <Button type="primary" disabled={!canReadProducts}>
            <Link to="/products">Manage Products</Link>
          </Button>
        </Space>
      }
    >
      <Space direction="vertical" size={18} style={{ width: '100%' }}>
        <Row gutter={[16, 16]}>
          <Col xs={12} lg={6}>
            <Card size="small">
              <Statistic title="Products" value={data.products.length} prefix={<AppstoreOutlined />} />
            </Card>
          </Col>
          <Col xs={12} lg={6}>
            <Card size="small">
              <Statistic title="Low Stock" value={lowStockRows.length} prefix={<WarningOutlined />} valueStyle={{ color: lowStockRows.length ? '#cf1322' : undefined }} />
            </Card>
          </Col>
          <Col xs={12} lg={6}>
            <Card size="small">
              <Statistic title="Inventory Value" value={moneyFormatter({ amount: inventoryValue, currency_code: DEFAULT_CURRENCY_CODE })} />
            </Card>
          </Col>
          <Col xs={12} lg={6}>
            <Card size="small">
              <Statistic title="Open Orders / Purchases" value={`${openOrders} / ${pendingPurchases}`} />
            </Card>
          </Col>
        </Row>

        {lowStockRows.length ? (
          <Alert
            type="warning"
            showIcon
            message={`${lowStockRows.length} item${lowStockRows.length === 1 ? '' : 's'} need inventory attention`}
            description="Review reorder levels, branch stock, and supplier purchase orders before POS sales are blocked."
          />
        ) : (
          <Alert type="success" showIcon message="Inventory levels look healthy" description="No stocked product is currently below its reorder threshold." />
        )}

        <Row gutter={[16, 16]}>
          {[
            { icon: <ShoppingOutlined />, title: 'Products', desc: 'Catalog, pricing, SKU, reorder levels', link: '/products', disabled: !canReadProducts },
            { icon: <ShoppingCartOutlined />, title: 'Orders', desc: 'Fulfillment, returns, delivered status', link: '/orders', disabled: !canReadOrders },
            { icon: <InboxOutlined />, title: 'Purchases', desc: 'Procurement, vendor orders, receiving', link: '/purchases', disabled: !canReadPurchases },
            { icon: <TeamOutlined />, title: 'Suppliers', desc: 'Supplier records and terms', link: '/suppliers', disabled: !canAccessEntityAction(currentAdmin, 'supplier', 'read') },
            { icon: <BarcodeOutlined />, title: 'POS', desc: 'Checkout, branch stock, receipts', link: '/pos', disabled: !canUsePos },
          ].map((item) => (
            <Col xs={24} md={12} xl={8} key={item.title}>
              <Card size="small">
                <Space align="start">
                  <span style={{ fontSize: 22, color: '#1677ff' }}>{item.icon}</span>
                  <Space direction="vertical" size={2}>
                    <Typography.Text strong>{item.title}</Typography.Text>
                    <Typography.Text type="secondary">{item.desc}</Typography.Text>
                    <Button size="small" disabled={item.disabled}>
                      <Link to={item.link}>Open</Link>
                    </Button>
                  </Space>
                </Space>
              </Card>
            </Col>
          ))}
        </Row>

        <Card title="Stock Control" loading={loading}>
          <Space wrap style={{ marginBottom: 12 }}>
            <Input.Search
              allowClear
              placeholder="Search by product, SKU, category, supplier"
              style={{ width: 320 }}
              onChange={(event) => setFilters((current) => ({ ...current, search: event.target.value }))}
            />
            <Select
              allowClear
              placeholder="Product status"
              style={{ width: 160 }}
              value={filters.status}
              onChange={(value) => setFilters((current) => ({ ...current, status: value }))}
              options={statusOptions}
            />
            <Select
              allowClear
              placeholder="Branch"
              style={{ width: 180 }}
              value={filters.branch}
              onChange={(value) => setFilters((current) => ({ ...current, branch: value }))}
              options={branchOptions}
            />
          </Space>
          <Table
            rowKey="_id"
            dataSource={productRows}
            pagination={{ pageSize: 10 }}
            columns={[
              {
                title: 'Product',
                render: (_, record) => (
                  <Space direction="vertical" size={0}>
                    <Typography.Text strong>{record.name}</Typography.Text>
                    <Typography.Text type="secondary">{record.sku || 'No SKU'} · {recordName(record.category, 'Uncategorized')}</Typography.Text>
                  </Space>
                ),
              },
              { title: 'Supplier', render: (_, record) => recordName(record.supplier) },
              {
                title: 'Available',
                render: (_, record) => (
                  <Space direction="vertical" size={2} style={{ minWidth: 140 }}>
                    <Typography.Text strong>{record.available}</Typography.Text>
                    <Progress percent={record.stockStatus.percent} size="small" strokeColor={record.stockStatus.color} showInfo={false} />
                    <Typography.Text type="secondary">On hand {record.onHand} · reserved {record.reserved}</Typography.Text>
                  </Space>
                ),
              },
              { title: 'Reorder', dataIndex: 'reorderLevel' },
              {
                title: 'Signal',
                render: (_, record) => <Tag color={record.stockStatus.color}>{record.stockStatus.label}</Tag>,
              },
              {
                title: 'Price',
                render: (_, record) =>
                  moneyFormatter({
                    amount: record.salePrice?.amount || 0,
                    currency_code: record.salePrice?.currency || DEFAULT_CURRENCY_CODE,
                  }),
              },
              {
                title: 'Action',
                render: (_, record) => (
                  <Space>
                    <Button size="small">
                      <Link to="/products">Edit</Link>
                    </Button>
                    <Button size="small" type={record.stockStatus.color !== 'green' ? 'primary' : 'default'}>
                      <Link to="/purchases">Reorder</Link>
                    </Button>
                  </Space>
                ),
              },
            ]}
          />
        </Card>

        <Row gutter={[16, 16]}>
          <Col xs={24} lg={12}>
            <Card title="Recent Purchase Orders" loading={loading}>
              <Table
                rowKey="_id"
                dataSource={data.purchases.slice(0, 6)}
                pagination={false}
                columns={[
                  { title: 'Number', dataIndex: 'number' },
                  { title: 'Vendor', render: (_, record) => recordName(record.vendor) },
                  { title: 'Status', dataIndex: 'status', render: (value) => <Tag>{value || 'draft'}</Tag> },
                ]}
              />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="Recent Stock Movements" loading={loading}>
              <Table
                rowKey="_id"
                dataSource={data.movements.slice(0, 6)}
                pagination={false}
                columns={[
                  { title: 'Product', render: (_, record) => recordName(record.product) },
                  { title: 'Type', dataIndex: 'type', render: (value) => <Tag>{value || 'adjustment'}</Tag> },
                  { title: 'Qty', dataIndex: 'quantity' },
                  { title: 'Branch', render: (_, record) => recordName(record.branch) },
                ]}
                locale={{ emptyText: 'Stock movements will appear after POS sales, purchases, or adjustments.' }}
              />
            </Card>
          </Col>
        </Row>
      </Space>
    </WorkflowPage>
  );
}
