import { useState, useCallback, useEffect } from 'react';
import {
  ReactFlow,
  addEdge,
  Controls,
  Background,
  BackgroundVariant,
  SelectionMode
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import { FiUser, FiMail, FiCheckCircle, FiList } from 'react-icons/fi';
import { FaShuffle } from 'react-icons/fa6';
import '../assets/css/style.css';
import Tabbar from './Tabbar.tsx';
import ShowPopup from './ShowPopup.tsx';
import { nanoid } from 'nanoid';
import CustomEdge from './CustomEdge';

const initialNodes = [
  {
    key: 'customer-sign',
    id: '1',
    type: 'input',
    data: {
      label: (
        <div className='step'>
          <div className='left'>
            <img
              src='/src/assets/icons/icon-user.svg'
              width='24px'
              height='24px'
              alt=''
            />
          </div>
          <div className='right'>Customer signs up to</div>
        </div>
      )
    },
    position: { x: 250, y: 100 }
  },
  {
    id: '2',
    data: { label: 'Add Note' },
    position: { x: 250, y: 250 }
  }
];

// Nội dung cho mỗi node
const nodeContents = {
  'send-email': `
    <label for="email-subject">Subject:</label>
    <input type="text" id="email-subject" name="email-subject" placeholder="Enter subject">
    <label for="email-body">Body:</label>
    <textarea id="email-body" name="email-body" rows="4" placeholder="Enter email body"></textarea>
  `,
  'customer-sign': `
    <label for="customer-name">Customer Name:</label>
    <input type="text" id="customer-name" name="customer-name" placeholder="Enter customer name">
    <label for="customer-email">Customer Email:</label>
    <input type="email" id="customer-email" name="customer-email" placeholder="Enter customer email">
  `,
  ifelse: `
    <label for="reply-status">Reply Status:</label>
    <select id="reply-status" name="reply-status">
      <option value="replied">Replied</option>
      <option value="not-replied">Not Replied</option>
    </select>
  `,
  'contact-exists': `
    <label for="contact-id">Contact ID:</label>
    <input type="text" id="contact-id" name="contact-id" placeholder="Enter contact ID">
  `,
  'send-survey': `
    <label for="survey-question">Survey Question:</label>
    <input type="text" id="survey-question" name="survey-question" placeholder="Enter survey question">
    <label for="survey-options">Options (comma-separated):</label>
    <input type="text" id="survey-options" name="survey-options" placeholder="Option 1, Option 2, ...">
  `
};

const NoteFlow = () => {
  const [nodes, setNodes] = useState(initialNodes);
  const [edges, setEdges] = useState([
    { id: 'e1-2', source: '1', target: '2' } // Kết nối node "Add Note" với node mặc định ban đầu
  ]);
  const [showTabBar, setShowTabBar] = useState(false);
  const [lastNodeId, setLastNodeId] = useState('1');
  const [nodeToDelete, setNodeToDelete] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [selectedNodeContent, setSelectedNodeContent] = useState('');
  const [addNodeCallback, setAddNodeCallback] = useState(() => () => {});
  const [isTabbarVisible, setIsTabbarVisible] = useState(false);

  const handleAddNoteClick = () => {
    setShowTabBar(true);
    setIsTabbarVisible(true);
    setAddNodeCallback(() => (selectedNode) => {
      addNodeBetween(selectedNode, sourceId, targetId);
    });
  };
  const closeTabbar = () => {
    console.log('aaa');
    setIsTabbarVisible(false); // Ẩn tabbar khi click close
  };

  const onNodeClick = (event, node) => {
    if (node.id === '2') {
      // Check if the clicked node is "Add Note"
      setShowTabBar(true);
      setIsTabbarVisible(true);
    } else {
      // Hiển thị popup khi click vào bất kỳ node nào
      const content = nodeContents[node.key]; // Lấy nội dung tương ứng của node
      setSelectedNodeContent(content); // Cập nhật nội dung cho popup
      setShowPopup(true); // Mở popup
    }
  };

  const onNodeContextMenu = useCallback((event, node) => {
    event.preventDefault(); // Ngăn không cho menu chuột phải mặc định hiện ra
    setNodeToDelete(node);
  }, []);

  const handleNodeDelete = () => {
    if (nodeToDelete) {
      setNodes((nds) => nds.filter((node) => node.id !== nodeToDelete.id));
      setEdges((eds) =>
        eds.filter(
          (edge) =>
            edge.source !== nodeToDelete.id && edge.target !== nodeToDelete.id
        )
      );
      setNodeToDelete(null);
    }
  };

  // Function to get a unique y position
  const getUniqueYPosition = (xPosition, baseY, spacing) => {
    const existingYPositions = nodes
      .filter((node) => node.position.x === xPosition)
      .map((node) => node.position.y);

    let newYPosition = baseY;

    while (existingYPositions.includes(newYPosition)) {
      newYPosition += spacing;
    }

    return newYPosition;
  };

  const getNextYPosition = (xPosition, spacing) => {
    const nodesInColumn = nodes.filter((node) => node.position.x === xPosition);
    if (nodesInColumn.length === 0) return 0; // Return 0 if there are no nodes

    const lastNode = nodesInColumn[nodesInColumn.length - 1];
    return lastNode.position.y + spacing;
  };

  const removeEdgesRelatedToNode = (nodeId) => {
    setEdges((eds) =>
      eds.filter((edge) => edge.source !== nodeId && edge.target !== nodeId)
    );
  };

  const addNode = (option) => {
    const newNodeId = nanoid(8); // Generate a unique ID for the new node
    const addNoteNode = nodes.find((node) => node.id === '2');
    const initialX = addNoteNode.position.x;
    console.log(initialX);

    const nextY =
      nodes.length > 2
        ? getNextYPosition(initialX, 130)
        : addNoteNode.position.y;

    // Remove existing edges from addNoteNode
    setEdges((eds) =>
      eds.filter((edge) => edge.source !== '2' && edge.target !== '2')
    );

    if (option.id === '4') {
      const repliedNode = {
        id: newNodeId,
        key: option.key,
        data: { label: option.htmlNode },
        position: { x: initialX, y: nextY }
      };

      const yesNode = {
        id: nanoid(8),
        type: 'output',
        key: 'contact-exists',
        data: {
          label: (
            <div className='step'>
              <div className='left'>
                <img
                  src='/src/assets/icons/icon-check.svg'
                  width='24px'
                  height='24px'
                  alt=''
                />
              </div>
              <div className='right'>Contact Exists</div>
            </div>
          )
        },
        position: { x: initialX - 150, y: nextY + 150 }
      };

      const noNode = {
        id: nanoid(8),
        type: '',
        key: 'send-survey',
        data: {
          label: (
            <div className='step'>
              <div className='left'>
                <img
                  src='/src/assets/icons/icon-list.svg'
                  width='24px'
                  height='24px'
                  alt=''
                />
              </div>
              <div className='right'>Send survey</div>
            </div>
          )
        },
        position: { x: initialX + 150, y: nextY + 150 }
      };

      // Di chuyển node add-note sang nhánh no
      setNodes((nds) =>
        nds.map((node) =>
          node.id === '2'
            ? {
                ...node,
                position: {
                  x: noNode.position.x,
                  y: noNode.position.y + 150
                }
              }
            : node
        )
      );

      // Thêm các node mới (replied, yes, no)
      setNodes((nds) => [...nds, repliedNode, yesNode, noNode]);

      // Kết nối các edges giữa các node
      setEdges((eds) => [
        ...eds,
        {
          id: nanoid(8),
          source: repliedNode.id,
          target: yesNode.id,
          label: 'yes'
        },
        {
          id: nanoid(8),
          source: repliedNode.id,
          target: noNode.id,
          label: 'no'
        },
        { id: nanoid(8), source: lastNodeId, target: repliedNode.id },
        { id: nanoid(8), source: noNode.id, target: addNoteNode.id }
      ]);

      setLastNodeId(noNode.id);
    } else {
      console.log(option);

      // Add new node logic
      if (addNoteNode) {
        const initialX = addNoteNode.position.x;
        setNodes((nds) =>
          nds.map((node) =>
            node.id === '2'
              ? {
                  ...node,
                  position: {
                    x: initialX,
                    y: nextY + 130
                  }
                }
              : node
          )
        );
      }
      const newNode = {
        id: newNodeId,
        key: option.key,
        data: { label: option.htmlNode },
        position: {
          x: initialX,
          y: nodes.length > 2 ? nextY : addNoteNode.position.y
        }
      };

      const newEdge = {
        id: nanoid(8),
        source: lastNodeId,
        target: newNodeId
      };

      setNodes((nds) => [...nds, newNode]);
      setEdges((eds) => [
        ...eds,
        newEdge,
        { id: nanoid(8), source: newNodeId, target: addNoteNode.id }
      ]);

      // setEdges((eds) => [
      //   ...eds,
      //   {
      //     id: uuidv4(),
      //     source: lastNodeId,
      //     data: {
      //       label: <div onClick={handleAddNoteClick}>Add Note</div>, // Use HTML or React component
      //       onClick: handleAddNoteClick
      //     },
      //     target: newNodeId
      //   }
      // ]);
      // Cuộn tới node mới thêm
      setLastNodeId(newNodeId);
    }

    setShowTabBar(false);
  };

  const hidePopup = () => {
    setShowPopup(false);
  };

  const addPopup = (node) => {
    const content = nodeContents[node.id]; // Lấy nội dung từ nodeContents dựa trên ID node
    setSelectedNodeContent(content); // Cập nhật nội dung được chọn
  };

  return (
    <div style={{ height: '100vh', width: '100%', position: 'relative' }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        edgeTypes={{ custom: CustomEdge }}
        onNodeClick={onNodeClick}
        onNodeContextMenu={onNodeContextMenu}
        panOnScroll
        selectionOnDrag
        selectionMode={SelectionMode.Partial}
      >
        <Controls />
        <Background variant={BackgroundVariant.Lines} color='#ccccc' />
      </ReactFlow>

      {isTabbarVisible && (
        <Tabbar addNode={addNode} closeTabbar={closeTabbar} />
      )}

      {nodeToDelete && (
        <div
          style={{
            position: 'absolute',
            top: nodeToDelete.position.y - 12,
            left: nodeToDelete.position.x + 260,
            zIndex: 10
          }}
        >
          <button
            onClick={handleNodeDelete}
            style={{
              background: 'red',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            X
          </button>
        </div>
      )}
      {showPopup && (
        <ShowPopup
          selectedNodeContent={selectedNodeContent}
          hidePopup={() => setShowPopup(false)}
        />
      )}
    </div>
  );
};

export default NoteFlow;
