import React, {useState} from 'react';
import AddMonitoringModalView from './view';

const AddMonitoringModal = ({visible, onClose, onSave}) => {
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    category: null,
    responsible: null,
    deadline: null,
    assignee: null,
    implementer: null,
    attachments: [],
  });

  const [dataList, setDataList] = useState([
    {id: 1, name: 'Nguyễn Minh Đức'},
    {id: 2, name: 'Trần Văn Hùng'},
    {id: 3, name: 'Lê Thị Mai'},
    {id: 4, name: 'Phạm Quốc Khánh'},
    {id: 5, name: 'Hoàng Anh Tuấn'},
    {id: 6, name: 'Vũ Thị Hằng'},
    {id: 7, name: 'Ngô Văn Nam'},
    {id: 8, name: 'Đinh Thị Lan'},
    {id: 9, name: 'Bùi Văn Phúc'},
    {id: 10, name: 'Lý Thị Hoa'},
    {id: 11, name: 'Phan Minh Hoàng'},
    {id: 12, name: 'Tạ Thị Hương'},
    {id: 13, name: 'Đoàn Văn Dũng'},
    {id: 14, name: 'Nguyễn Thị Vân'},
    {id: 15, name: 'Trương Văn Long'},
    {id: 16, name: 'Mai Thị Ngọc'},
    {id: 17, name: 'Huỳnh Quốc Việt'},
    {id: 18, name: 'Lâm Thị Thu'},
    {id: 19, name: 'Nguyễn Hữu Tài'},
    {id: 20, name: 'Phạm Thị Kim'},
  ]);

  const [selectedItems, setSelectedItems] = useState([]);

  const updateFormData = (field, value) => {
    setFormData(prev => ({...prev, [field]: value}));
  };

  const handleSave = () => {
    if (formData.title.trim() && formData.content.trim()) {
      const workData = {
        ...formData,
        selectedImplementers: selectedItems,
        type: 'monitoring', 
      };
      onSave(workData);
      resetForm();
    } else {
      alert('Vui lòng điền đầy đủ thông tin bắt buộc');
    }
  };

  const resetForm = () => {
    setFormData({
      title: '',
      content: '',
      category: null,
      responsible: null,
      deadline: null,
      assignee: null,
      implementer: null,
      attachments: [],
    });
    setSelectedItems([]);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  const handleSelectItem = item => {
    const isSelected = selectedItems.some(selected => selected.id === item.id);
    if (isSelected) {
      setSelectedItems(prev => prev.filter(selected => selected.id !== item.id));
    } else {
      setSelectedItems(prev => [...prev, item]);
    }
  };

  const handleRemoveItem = itemId => {
    setSelectedItems(prev => prev.filter(item => item.id !== itemId));
  };

  return (
    <AddMonitoringModalView
      visible={visible}
      formData={formData}
      dataList={dataList}
      selectedItems={selectedItems}
      updateFormData={updateFormData}
      handleSave={handleSave}
      handleClose={handleClose}
      handleSelectItem={handleSelectItem}
      handleRemoveItem={handleRemoveItem}
    />
  );
};

export default AddMonitoringModal;
