import { useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import {
  Alert,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Tabs,
  Typography,
  message,
} from 'antd';
import {
  BarcodeOutlined,
  CheckCircleOutlined,
  DownloadOutlined,
  PrinterOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { request } from '@/request';
import { DEMO_MODE } from '@/demo/config';
import { WorkflowPage } from './shared';
import { DEFAULT_CURRENCY_CODE } from '@/constants/platformDefaults';
import useMoney from '@/settings/useMoney';

const { Text } = Typography;

const moneyValue = (value) => (typeof value === 'object' ? Number(value?.amount || 0) : Number(value || 0));

export default function PosWorkbench() {
  const location = useLocation();
  const money = useMoney();
  const [branches, setBranches] = useState([]);
  const [products, setProducts] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [branchId, setBranchId] = useState();
  const [session, setSession] = useState(null);
  const [summary, setSummary] = useState(null);
  const [history, setHistory] = useState([]);
  const [report, setReport] = useState(null);
  const [barcodeInfo, setBarcodeInfo] = useState(null);
  const [cart, setCart] = useState([]);
  const [loading, setLoading] = useState(false);
  const [openSessionModal, setOpenSessionModal] = useState(false);
  const [checkoutForm] = Form.useForm();
  const [sessionForm] = Form.useForm();

  const load = async (nextBranchId = branchId) => {
    setLoading(true);
    const [branchRes, productRes, customerRes, sessionRes, summaryRes, historyRes, reportRes] = await Promise.all([
      request.list({ entity: 'branch', options: { page: 1, items: 100 } }),
      request.list({ entity: 'product', options: { page: 1, items: 100 } }),
      request.list({ entity: 'client', options: { page: 1, items: 100 } }),
      request.get({ entity: `pos/session/current${nextBranchId ? `?branch=${nextBranchId}` : ''}` }),
      request.get({ entity: 'pos/summary' }),
      request.get({ entity: `pos/sale/history${nextBranchId ? `?branch=${nextBranchId}` : ''}` }),
      request.get({ entity: 'pos/report' }),
    ]);

    const nextBranches = branchRes?.result || [];
    setBranches(nextBranches);
    setProducts(productRes?.result || []);
    setCustomers(customerRes?.result || []);
    const resolvedBranchId = nextBranchId || nextBranches[0]?._id;
    if (!branchId && resolvedBranchId) setBranchId(resolvedBranchId);
    setSession(sessionRes?.result || null);
    setSummary(summaryRes?.result || null);
    setHistory(historyRes?.result || []);
    setReport(reportRes?.result || null);
    setLoading(false);
  };

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

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

  const branchOptions = useMemo(
    () => branches.map((branch) => ({ value: branch._id, label: branch.name })),
    [branches]
  );

  const productOptions = useMemo(
    () =>
      products.map((product) => ({
        value: product._id,
        label: `${product.name} (${product.sku || 'No SKU'})`,
      })),
    [products]
  );

  const cartTotal = cart.reduce((sum, item) => sum + Number(item.total || 0), 0);
  const activeTab = location.pathname.includes('/history')
    ? 'history'
    : location.pathname.includes('/reports')
      ? 'reports'
      : 'checkout';

  const addToCart = (productId) => {
    const product = products.find((item) => item._id === productId);
    if (!product) return;
    const price = Number(product.salePrice?.amount || product.salePrice || 0);
    const existing = cart.find((item) => item.product === productId);
    if (existing) {
      setCart((current) =>
        current.map((item) =>
          item.product === productId
            ? { ...item, quantity: item.quantity + 1, total: (item.quantity + 1) * item.unitPrice }
            : item
        )
      );
      return;
    }
    setCart((current) => [
      ...current,
      { product: product._id, name: product.name, sku: product.sku, quantity: 1, unitPrice: price, total: price },
    ]);
  };

  const updateQuantity = (productId, quantity) => {
    setCart((current) =>
      current
        .map((item) =>
          item.product === productId
            ? { ...item, quantity, total: Number(quantity || 0) * Number(item.unitPrice || 0) }
            : item
        )
        .filter((item) => Number(item.quantity || 0) > 0)
    );
  };

  const openSession = async () => {
    const values = await sessionForm.validateFields();
    const response = await request.post({ entity: 'pos/session/open', jsonData: values });
    if (response?.success) {
      setSession(response.result);
      setOpenSessionModal(false);
      message.success('Cashier session opened');
      load(values.branch);
    }
  };

  const closeSession = async () => {
    if (!session?._id) return;
    const response = await request.post({ entity: `pos/session/${session._id}/close`, jsonData: {} });
    if (response?.success) {
      message.success('Cashier session closed');
      setSession(null);
      load(branchId);
    }
  };

  const completeCheckout = async () => {
    if (!cart.length) return message.warning('Add at least one product to the cart');
    const values = await checkoutForm.validateFields();
    const response = await request.post({
      entity: 'pos/checkout',
      jsonData: {
        branch: branchId,
        currency: DEFAULT_CURRENCY_CODE,
        items: cart.map((item) => ({ product: item.product, quantity: item.quantity, unitPrice: item.unitPrice })),
        ...values,
      },
    });
    if (response?.success) {
      message.success('Sale completed');
      setCart([]);
      checkoutForm.resetFields();
      load(branchId);
    }
  };

  const exportSales = () => {
    if (!DEMO_MODE) {
      window.open('/api/pos/sale/export', '_blank');
      return;
    }
    const rows = history.map((sale) => ({
      receiptNumber: sale.receiptNumber,
      soldAt: sale.soldAt,
      cashier: sale.cashier,
      total: moneyValue(sale.total),
      paymentMode: sale.paymentSummary?.mode,
    }));
    const csv = [
      Object.keys(rows[0] || { receiptNumber: '', soldAt: '', cashier: '', total: '', paymentMode: '' }).join(','),
      ...rows.map((row) => Object.values(row).join(',')),
    ].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'pos-sales-demo.csv';
    link.click();
    URL.revokeObjectURL(link.href);
  };

  const showBarcode = async (productId) => {
    const response = await request.get({ entity: `pos/barcode/${productId}` });
    if (response?.success) setBarcodeInfo(response.result);
  };

  return (
    <WorkflowPage
      title="Point of Sale"
      description="Run retail checkout, manage cashier sessions, track branch sales, and print receipts or barcode labels."
      permission="inventory.pos.read"
      extra={
        <Space>
          <Select
            value={branchId}
            onChange={setBranchId}
            options={branchOptions}
            placeholder="Select branch"
            style={{ minWidth: 180 }}
          />
          <Button icon={<ReloadOutlined />} onClick={() => load(branchId)}>
            Refresh
          </Button>
          <Button icon={<DownloadOutlined />} onClick={exportSales}>
            Export Sales
          </Button>
        </Space>
      }
    >
      <Space direction="vertical" size={16} style={{ width: '100%' }}>
        <Alert
          type={session ? 'success' : 'warning'}
          showIcon
          message={session ? 'Cashier session active' : 'No active cashier session for the selected branch'}
          action={
            !session ? (
              <Button size="small" type="primary" onClick={() => setOpenSessionModal(true)}>
                Open Session
              </Button>
            ) : (
              <Button size="small" danger onClick={closeSession}>
                Close Session
              </Button>
            )
          }
        />

        <Row gutter={[16, 16]}>
          <Col xs={24} md={8}>
            <Card>
              <Statistic
                title="Today's Sales"
                value={money.moneyFormatter({
                  amount: moneyValue(summary?.dailySalesTotal),
                  currency_code: summary?.dailySalesTotal?.currency || DEFAULT_CURRENCY_CODE,
                })}
              />
            </Card>
          </Col>
          <Col xs={24} md={8}>
            <Card>
              <Statistic title="Transactions" value={summary?.transactionCount || 0} />
            </Card>
          </Col>
          <Col xs={24} md={8}>
            <Card>
              <Statistic
                title="Average Basket"
                value={money.moneyFormatter({
                  amount: moneyValue(report?.averageBasketSize),
                  currency_code: report?.averageBasketSize?.currency || DEFAULT_CURRENCY_CODE,
                })}
              />
            </Card>
          </Col>
        </Row>

        <Tabs
          activeKey={activeTab}
          items={[
            {
              key: 'checkout',
              label: 'Checkout',
              children: (
                <Row gutter={[16, 16]}>
                  <Col xs={24} lg={14}>
                    <Card title="Product Lookup">
                      <Space direction="vertical" style={{ width: '100%' }} size={16}>
                        <Select
                          showSearch
                          placeholder="Search product by name or SKU"
                          options={productOptions}
                          onSelect={addToCart}
                          style={{ width: '100%' }}
                        />
                        <Table
                          rowKey="_id"
                          pagination={false}
                          dataSource={products}
                          columns={[
                            { title: 'Product', dataIndex: 'name' },
                            { title: 'SKU', dataIndex: 'sku', render: (value) => value || '-' },
                            {
                              title: 'Price',
                              render: (_, record) =>
                                money.moneyFormatter({
                                  amount: moneyValue(record.salePrice),
                                  currency_code: record.salePrice?.currency || DEFAULT_CURRENCY_CODE,
                                }),
                            },
                            {
                              title: 'Action',
                              render: (_, record) => (
                                <Space>
                                  <Button size="small" type="link" onClick={() => addToCart(record._id)}>
                                    Add
                                  </Button>
                                  <Button size="small" icon={<BarcodeOutlined />} onClick={() => showBarcode(record._id)} />
                                </Space>
                              ),
                            },
                          ]}
                        />
                      </Space>
                    </Card>
                  </Col>
                  <Col xs={24} lg={10}>
                    <Card title="Cart & Payment">
                      <Space direction="vertical" size={16} style={{ width: '100%' }}>
                        <Table
                          rowKey="product"
                          pagination={false}
                          dataSource={cart}
                          locale={{ emptyText: 'Cart is empty' }}
                          columns={[
                            { title: 'Item', dataIndex: 'name' },
                            {
                              title: 'Qty',
                              render: (_, record) => (
                                <InputNumber min={1} value={record.quantity} onChange={(value) => updateQuantity(record.product, value)} />
                              ),
                            },
                            {
                              title: 'Total',
                              render: (_, record) =>
                                money.moneyFormatter({ amount: record.total, currency_code: DEFAULT_CURRENCY_CODE }),
                            },
                          ]}
                        />
                        <Divider style={{ margin: 0 }} />
                        <Statistic
                          title="Cart Total"
                          value={money.moneyFormatter({ amount: cartTotal, currency_code: DEFAULT_CURRENCY_CODE })}
                        />
                        <Form form={checkoutForm} layout="vertical" initialValues={{ paymentMode: 'cash', amountReceived: cartTotal }}>
                          <Form.Item name="customer" label="Customer (optional)">
                            <Select
                              allowClear
                              showSearch
                              options={customers.map((customer) => ({ value: customer._id, label: customer.name }))}
                            />
                          </Form.Item>
                          <Form.Item name="paymentMode" label="Payment Mode" rules={[{ required: true }]}>
                            <Select options={[{ value: 'cash', label: 'Cash' }, { value: 'card', label: 'Card' }, { value: 'transfer', label: 'Transfer' }]} />
                          </Form.Item>
                          <Form.Item name="amountReceived" label="Amount Received">
                            <InputNumber style={{ width: '100%' }} min={0} />
                          </Form.Item>
                          <Form.Item name="paymentReference" label="Payment Reference">
                            <Input />
                          </Form.Item>
                          <Button type="primary" block icon={<CheckCircleOutlined />} disabled={!session} onClick={completeCheckout}>
                            Complete Sale
                          </Button>
                        </Form>
                      </Space>
                    </Card>
                  </Col>
                </Row>
              ),
            },
            {
              key: 'history',
              label: 'Sales History',
              children: (
                <Table
                  rowKey="_id"
                  dataSource={history}
                  loading={loading}
                  pagination={{ pageSize: 8 }}
                  columns={[
                    { title: 'Receipt', dataIndex: 'receiptNumber' },
                    { title: 'Sold At', dataIndex: 'soldAt', render: (value) => new Date(value).toLocaleString() },
                    { title: 'Payment', render: (_, record) => <Tag>{record.paymentSummary?.mode || 'cash'}</Tag> },
                    {
                      title: 'Total',
                      render: (_, record) =>
                        money.moneyFormatter({
                          amount: moneyValue(record.total),
                          currency_code: record.total?.currency || DEFAULT_CURRENCY_CODE,
                        }),
                    },
                    {
                      title: 'Receipt',
                      render: (_, record) => (
                        <Button icon={<PrinterOutlined />} size="small" onClick={() => request.post({ entity: `pos/receipt/${record._id}/reprint`, jsonData: {} })}>
                          Reprint
                        </Button>
                      ),
                    },
                  ]}
                />
              ),
            },
            {
              key: 'reports',
              label: 'POS Reports',
              children: (
                <Space direction="vertical" size={16} style={{ width: '100%' }}>
                  <Row gutter={[16, 16]}>
                    <Col xs={24} md={12}>
                      <Card title="Monthly Sales">
                        <Statistic
                          value={money.moneyFormatter({
                            amount: moneyValue(report?.monthlySalesTotal),
                            currency_code: report?.monthlySalesTotal?.currency || DEFAULT_CURRENCY_CODE,
                          })}
                        />
                      </Card>
                    </Col>
                    <Col xs={24} md={12}>
                      <Card title="Low Stock Signals">
                        <Text strong>{report?.lowStockSignals?.length || 0}</Text>
                        <div>
                          {(report?.lowStockSignals || []).slice(0, 3).map((signal, index) => (
                            <Tag key={index} color="orange" style={{ marginTop: 8 }}>
                              On hand {signal.onHand} / reorder {signal.reorderLevel}
                            </Tag>
                          ))}
                        </div>
                      </Card>
                    </Col>
                  </Row>
                  <Card title="Cashier Performance">
                    <Table
                      rowKey="cashier"
                      pagination={false}
                      dataSource={report?.cashierPerformance || []}
                      columns={[
                        { title: 'Cashier', dataIndex: 'cashier' },
                        { title: 'Transactions', dataIndex: 'transactions' },
                        {
                          title: 'Sales Total',
                          render: (_, record) => money.moneyFormatter({ amount: record.total, currency_code: DEFAULT_CURRENCY_CODE }),
                        },
                      ]}
                    />
                  </Card>
                </Space>
              ),
            },
          ]}
        />
      </Space>

      <Modal title="Open Cashier Session" open={openSessionModal} onCancel={() => setOpenSessionModal(false)} onOk={openSession}>
        <Form form={sessionForm} layout="vertical" initialValues={{ branch: branchId }}>
          <Form.Item name="branch" label="Branch" rules={[{ required: true }]}>
            <Select options={branchOptions} />
          </Form.Item>
          <Form.Item name="openingNote" label="Opening Note">
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal title="Barcode Label" open={Boolean(barcodeInfo)} onCancel={() => setBarcodeInfo(null)} footer={null}>
        {barcodeInfo ? (
          <Space direction="vertical" size={12}>
            <Text strong>{barcodeInfo.name}</Text>
            <Text code>{barcodeInfo.value}</Text>
            <Text type="secondary">{barcodeInfo.printableLabel}</Text>
          </Space>
        ) : null}
      </Modal>
    </WorkflowPage>
  );
}
