import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { DeleteOutlined } from '@ant-design/icons';
import {
  Form,
  Table,
  InputNumber,
  Button,
  Tooltip,
  message,
  Space,
  Col,
} from 'antd';
import SwapIcon from '../../../BookingScreen/Components/UtillComponents/Pozo retail icons/PozoSwapIcon';
import Buttons from '../../../../Components/Forms/Buttons';
import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
import { GlobalCompBranchData } from '../../../../Features/BrachLogin/BranchLogin';
import {
  branchIdBasedUserData,
  getBranchBasedUserList,
} from '../../../../Features/UserAccount/userData.js';
import {
  changeBtoBQuickProductTransfer,
  GlobalBtoBQuickProductTransfer,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
const style = {
  padding: '10px',
};

const BranchTransferComponent = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const branches = useSelector(GlobalCompBranchData);
  const users = useSelector(branchIdBasedUserData);
  const { action, selectedProducts } = useSelector(
    GlobalBtoBQuickProductTransfer
  );
  const [selectedBranch, setSelectedBranch] = useState();
  const [selectedUser, setSelectedUser] = useState();

  useEffect(() => {
    if (branches?.length === 1 && action) {
      const updateBranchID = async (brId) => {
        form?.setFieldValue({ toBranch: brId });
        setSelectedBranch(brId);
        await dispatch(getBranchBasedUserList(brId))?.unwrap();
      };
      updateBranchID(branches?.[0]?.BrId);
    }
  }, [branches, action]);

  useEffect(() => {
    if (users?.length === 1 && action) {
      form?.setFieldValue({ assignedUser: users?.[0]?.UserId });
      setSelectedUser(users?.[0]?.UserId);
    }
  }, [users, action]);

  const handleSubmit = (values) => {
    console.log('Transfer Details:', {
      ...values,
      products: selectedProducts,
    });
    message.success('Transfer request submitted successfully!');
    dispatch(
      changeBtoBQuickProductTransfer({
        action: false,
        selectedProducts: [],
      })
    );
    form.resetFields();
  };

  const onChangeToBranch = async (branchId) => {
    form?.setFieldValue({ toBranch: branchId });
    setSelectedBranch(branchId);
    await dispatch(getBranchBasedUserList(branchId))?.unwrap();
  };

  const OnChangeAssignedUser = (userId) => {
    form?.setFieldValue({ assignedUser: userId });
    setSelectedUser(userId);
  };

  const handleQuantityChange = (value, record) => {
    dispatch(
      changeBtoBQuickProductTransfer({
        action: action,
        selectedProducts: selectedProducts.map((product) => {
          if (product.ProdId === record.ProdId) {
            const newTotalPrice = value * product.OrderRate;
            return {
              ...product,
              OrderQty: value,
              TotalAmt: newTotalPrice,
            };
          }
          return product;
        }),
      })
    );
  };

  const handleDeleteProduct = (ProdId) => {
    dispatch(
      changeBtoBQuickProductTransfer({
        action: action,
        selectedProducts: selectedProducts.filter(
          (product) => product.ProdId !== ProdId
        ),
      })
    );
    message.success('Product removed from transfer list');
  };

  const calculateGrandTotal = () => {
    return selectedProducts.reduce(
      (total, product) => total + product.TotalAmt,
      0
    );
  };

  const columns = [
    {
      title: 'Sl.No',
      dataIndex: 'ProdId',
      key: 'ProdId',
      width: 5,
      align: 'center',
      render: (t, o, index) => <a style={{ color: 'black' }}>{index + 1}</a>,
    },
    {
      title: 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: 200,
    },
    {
      title: 'Quantity',
      dataIndex: 'OrderQty',
      key: 'OrderQty',
      width: 50,
      render: (text, record) => (
        console.log('text', record),
        (
          <InputNumber
            min={1}
            max={100}
            defaultValue={text}
            value={text}
            onChange={(value) => handleQuantityChange(value, record)}
            style={{ width: '100%' }}
          />
        )
      ),
    },
    {
      title: 'Rate',
      dataIndex: 'OrderRate',
      key: 'OrderRate',
      width: 50,
      render: (text) => `₹${text}`,
    },
    {
      title: 'Total Price',
      dataIndex: 'TotalAmt',
      key: 'TotalAmt',
      width: 80,
      render: (text, record) => `₹${record.OrderQty * record.OrderRate}`,
    },
    {
      title: 'Action',
      key: 'action',
      width: 1,
      align: 'center',
      render: (_, record) => (
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDeleteProduct(record.ProdId)}
        />
      ),
    },
  ];

  return (
    <div style={style}>
      <Space>
        <SwapIcon style={{ color: '#1890ff' }} />
        <p>Branch to Branch Product Transfer</p>
      </Space>
      <div style={{ marginTop: '20px' }}>
        <Col gutter={1}>
          <Col span={8}>
            <Form.Item
              name="toBranch"
              rules={[
                { required: true, message: 'Please select destination branch' },
              ]}
            >
              <DropDowns
                options={branches?.map((option) => ({
                  value: option.BrId,
                  label: option.BrName,
                }))}
                label={<label class="required">Destination branch</label>}
                isOnchanges={!!selectedBranch}
                onChangeFunction={(e) => {
                  onChangeToBranch(e);
                }}
                valueData={selectedBranch}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="assignedUser"
              rules={[{ required: true, message: 'Please select a user' }]}
            >
              <DropDowns
                options={users?.map((option) => ({
                  value: option.UserId,
                  label: option.UserName || 'No Name',
                }))}
                label={<label class="required">Assigned User</label>}
                isOnchanges={!!selectedUser}
                onChangeFunction={(e) => {
                  OnChangeAssignedUser(e);
                }}
                valueData={selectedUser}
              />
            </Form.Item>
          </Col>
        </Col>

        <Table
          columns={columns}
          dataSource={selectedProducts}
          pagination={false}
          bordered
          size="small"
          summary={() => (
            <Table.Summary.Row>
              <Table.Summary.Cell index={0} colSpan={5} align="right">
                <strong>Grand Total:</strong>
              </Table.Summary.Cell>
              <Table.Summary.Cell index={1} align="left">
                <strong>₹{calculateGrandTotal().toLocaleString()}</strong>
              </Table.Summary.Cell>
              <Table.Summary.Cell index={2} />
            </Table.Summary.Row>
          )}
        />

        <Space>
          <Buttons
            buttonText="Submit"
            color="901D77"
            handleSubmit={() => handleSubmit(form.getFieldsValue())}
            icon={<SwapIcon />}
          />
        </Space>
      </div>
    </div>
  );
};

export default BranchTransferComponent;
