import { useEffect, useState } from 'react';
import { Modal, Form, Select, Input, DatePicker, message } from 'antd';
import dayjs from 'dayjs';
import jwtAxios from '../../../api/axiosInstance';
import { ENDPOINTS } from '../../../api/endpoints';

interface StockAllocationModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

export const StockAllocationModal: React.FC<StockAllocationModalProps> = ({ open, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [availableLots, setAvailableLots] = useState<any[]>([]);
  const [selectedLot, setSelectedLot] = useState<any>(null);

  useEffect(() => {
    if (open) {
      fetchAvailableLots();
      form.resetFields();
      setSelectedLot(null);
      form.setFieldsValue({
        allocationDate: dayjs(),
        allocatedUnit: 'KG'
      });
    }
  }, [open, form]);

  const fetchAvailableLots = async () => {
    try {
      // Fetching all available lots (without vegetableId to get everything with remaining stock)
      const res = await jwtAxios.get(ENDPOINTS.SALES_AVAILABLE_LOTS);
      let lots = res.data?.result || [];
      // Allow lots that have available KG or available bags/units
      lots = lots.filter((lot: any) => 
        (lot.remainingQuantity && Number(lot.remainingQuantity) > 0) ||
        (lot.remainingBags && Number(lot.remainingBags) > 0)
      );
      setAvailableLots(lots);
    } catch (err: any) {
      message.error('Failed to fetch available lots');
    }
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const payload: any = {
        purchaseId: values.purchaseId,
        allocatedUnit: values.allocatedUnit,
        allocatedQty: Number(values.allocatedQty),
        allocationDate: values.allocationDate.toISOString(),
        remarks: values.remarks,
      };

      if (values.allocatedKg) {
        payload.allocatedKg = Number(values.allocatedKg);
      }

      await jwtAxios.post(ENDPOINTS.RETAIL_STOCK_ALLOCATE, payload);
      message.success('Stock allocated successfully');
      onSuccess();
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to allocate stock');
    } finally {
      setLoading(false);
    }
  };

  const isCountUnit = (u?: string) => u === 'BOX' || u === 'BAG' || u === 'THAAR' || u === 'PIECES';

  const unitOptions = selectedLot?.unit && selectedLot.unit !== 'KG'
    ? [
        { value: selectedLot.unit, label: selectedLot.unit },
        ...(selectedLot.remainingQuantity && Number(selectedLot.remainingQuantity) > 0
          ? [{ value: 'KG', label: 'KG' }]
          : []),
      ]
    : [
        { value: 'KG', label: 'KG' },
        { value: 'BOX', label: 'BOX' },
      ];

  return (
    <Modal
      title="Allocate Retail Stock"
      open={open}
      onCancel={onCancel}
      onOk={() => form.submit()}
      confirmLoading={loading}
      okText="Allocate"
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
      >
        <Form.Item
          name="purchaseId"
          label="Purchase Lot"
          rules={[{ required: true, message: 'Please select a purchase lot' }]}
        >
          <Select
            showSearch
            placeholder="Search by Lot No or Vegetable"
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())
            }
            options={availableLots.map((lot) => {
              const supplierName = lot.supplier?.name || lot.cashSupplierName || 'Cash Supplier';
              return {
                value: lot.id,
                label: `${lot.lotNo} - ${lot.vegetable?.name} (${supplierName}) (Avail: ${lot.remainingQuantity} KG${lot.remainingBags && Number(lot.remainingBags) > 0 ? ` / ${lot.remainingBags} ${lot.unit}` : ''})`,
              };
            })}
            onChange={(lotId) => {
              const lot = availableLots.find((l) => l.id === lotId);
              setSelectedLot(lot || null);
              // Default to native unit if not KG, else KG
              form.setFieldValue('allocatedUnit', lot?.unit || 'KG');
            }}
          />
        </Form.Item>

        <Form.Item
          name="allocatedUnit"
          label="Allocation Unit"
          rules={[{ required: true, message: 'Please select unit' }]}
        >
          <Select options={unitOptions} />
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.allocatedUnit !== currentValues.allocatedUnit ||
            prevValues.purchaseId !== currentValues.purchaseId
          }
        >
          {({ getFieldValue }) => {
            const unit = getFieldValue('allocatedUnit') || selectedLot?.unit || 'KG';
            const countUnit = isCountUnit(unit);
            const unitLabel =
              unit === 'THAAR' ? 'Number of Thaar' :
              unit === 'PIECES' ? 'Number of Pieces' :
              unit === 'BOX' ? 'Number of Boxes' :
              unit === 'BAG' ? 'Number of Bags' :
              'KG';

            return (
              <Form.Item
                name="allocatedQty"
                label={`Quantity (${unitLabel})`}
                rules={[
                  { required: true, message: 'Please enter quantity' },
                  () => ({
                    validator(_, value) {
                      if (!value) return Promise.resolve();
                      if (Number(value) <= 0) {
                        return Promise.reject(new Error('Quantity must be greater than 0'));
                      }
                      if (countUnit && !Number.isInteger(Number(value))) {
                        return Promise.reject(new Error(`${unit} must be a whole number`));
                      }
                      return Promise.resolve();
                    },
                  }),
                ]}
              >
                <Input
                  type="number"
                  step={countUnit ? "1" : "any"}
                  placeholder={`Enter ${unitLabel}`}
                  onChange={(e) => {
                    const qty = Number(e.target.value);
                    if (countUnit && selectedLot && qty > 0) {
                      const remBags = Number(selectedLot.remainingBags || 0);
                      const remKg = Number(selectedLot.remainingQuantity || 0);
                      if (remBags > 0 && remKg > 0) {
                        const autoKg = (qty === remBags)
                          ? remKg
                          : Number(((qty / remBags) * remKg).toFixed(3));
                        form.setFieldValue('allocatedKg', autoKg);
                      }
                    }
                  }}
                />
              </Form.Item>
            );
          }}
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.allocatedUnit !== currentValues.allocatedUnit ||
            prevValues.purchaseId !== currentValues.purchaseId
          }
        >
          {({ getFieldValue }) => {
            const unit = getFieldValue('allocatedUnit');
            const countUnit = isCountUnit(unit);
            const hasKgStock = selectedLot && Number(selectedLot.remainingQuantity || 0) > 0;
            if (countUnit && hasKgStock) {
              return (
                <Form.Item
                  name="allocatedKg"
                  label="Total Quantity in KG"
                  tooltip="Calculated automatically based on lot average weight, or edit if exact weight is known"
                  rules={[
                    () => ({
                      validator(_, value) {
                        if (!value) return Promise.resolve();
                        if (Number(value) <= 0) {
                          return Promise.reject(new Error('KG must be greater than 0'));
                        }
                        return Promise.resolve();
                      },
                    }),
                  ]}
                >
                  <Input type="number" step="any" placeholder="Enter total KG (optional if proportional weight applies)" />
                </Form.Item>
              );
            }
            return null;
          }}
        </Form.Item>

        <Form.Item
          name="allocationDate"
          label="Allocation Date"
          rules={[{ required: true, message: 'Please select allocation date' }]}
        >
          <DatePicker className="w-full" format="YYYY-MM-DD" />
        </Form.Item>

        <Form.Item name="remarks" label="Remarks">
          <Input.TextArea rows={3} placeholder="Optional remarks" />
        </Form.Item>
      </Form>
    </Modal>
  );
};
