import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  InputNumber, 
  Dropdown, 
  Alert,
  message,
  Card,
  Descriptions
} from 'antd';
import { 
  EllipsisOutlined, 
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import SequenceGeneratorAPI from './sequencegeneratorapi';

const SequenceGenerator = () => {
  const [sequences, setSequences] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [visible, setVisible] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [currentSequence, setCurrentSequence] = useState(null);
  const [form] = Form.useForm();

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

  const fetchSequences = async () => {
    setLoading(true);
    try {
      const data = await SequenceGeneratorAPI.getAll();
      setSequences(data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to fetch sequences');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    form.resetFields();
    setCurrentSequence(null);
    setEditingId(null);
    setVisible(true);
  };

  const handleEdit = (record) => {
    form.setFieldsValue(record);
    setCurrentSequence(record);
    setEditingId(record.id);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    Modal.confirm({
      title: 'Confirm Delete',
      content: 'Are you sure you want to delete this sequence?',
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          await SequenceGeneratorAPI.delete(id);
          message.success('Sequence deleted successfully');
          fetchSequences();
        } catch (err) {
          message.error(err.response?.data?.message || 'Failed to delete sequence');
        }
      }
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingId) {
        await SequenceGeneratorAPI.update(editingId, values);
        message.success('Sequence updated successfully');
      } else {
        await SequenceGeneratorAPI.create(values);
        message.success('Sequence created successfully');
      }
      
      setVisible(false);
      fetchSequences();
    } catch (err) {
      message.error(err.response?.data?.message || 'Operation failed');
    }
  };

  const columns = [
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_, record) => (
        <Dropdown
          menu={{
            items: [
              {
                key: 'edit',
                label: 'Edit',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record)
              },
              {
                key: 'delete',
                label: 'Delete',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record.id)
              }
            ]
          }}
          trigger={['click']}
        >
          <Button type="text" icon={<EllipsisOutlined />} />
        </Dropdown>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'sequence_name',
      key: 'sequence_name',
    },
    {
      title: 'Sequence Code',
      dataIndex: 'sequence_code',
      key: 'sequence_code',
    },
    {
      title: 'Current No',
      dataIndex: 'current_no',
      key: 'current_no',
    },
    {
      title: 'Demonstration',
      dataIndex: 'demonstration',
      key: 'demonstration',
    }
  ];

  return (
    <div className="sequence-generator-container">
      {error && (
        <Alert
          message="Error"
          description={error}
          type="error"
          showIcon
          closable
          onClose={() => setError(null)}
          style={{ marginBottom: 16 }}
        />
      )}

      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h2>Document Sequence</h2>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreate}
        >
          Add Sequence
        </Button>
      </div>

      <Table 
        columns={columns} 
        dataSource={sequences} 
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `Total ${total} sequences`,
        }}
      />

      <Modal
        title={<span style={{ fontWeight: 'bold' }}>Update Sequence Generator</span>}
        open={visible}
        onOk={handleSubmit}
        onCancel={() => setVisible(false)}
        confirmLoading={loading}
        width={700}
      >
        {currentSequence && (
          <div style={{ 
            marginLeft: 20, 
            marginBottom: 24,
            border: '1px solid #d9d9d9',
            borderRadius: 4,
            padding: 16,
            backgroundColor: '#fafafa'
          }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                <tr>
                  <td style={{ 
                    padding: '8px 16px', 
                    borderBottom: '1px solid #e8e8e8',
                    fontWeight: 'bold',
                    width: '30%'
                  }}>Sequence ID</td>
                  <td style={{ 
                    padding: '8px 16px', 
                    borderBottom: '1px solid #e8e8e8'
                  }}>{currentSequence.id}</td>
                </tr>
                <tr>
                  <td style={{ 
                    padding: '8px 16px', 
                    fontWeight: 'bold'
                  }}>Demonstration</td>
                  <td style={{ padding: '8px 16px' }}>
                    <div style={{ 
                      backgroundColor: '#f5f5f5',
                      padding: 8,
                      textAlign: 'center',
                      borderRadius: 4,
                      fontWeight: 'bold'
                    }}>
                      {currentSequence.demonstration}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        )}

        <Form form={form} layout="vertical" style={{ marginLeft: 20, marginRight: 20 }}>
          <Form.Item
            name="sequence_name"
            label={<span style={{ fontWeight: 'bold' }}>Name*</span>}
            rules={[{ required: true, message: 'Please input the sequence name!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="sequence_code"
            label={<span style={{ fontWeight: 'bold' }}>Sequence Code</span>}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="prefix"
            label={<span style={{ fontWeight: 'bold' }}>Prefix*</span>}
            rules={[{ required: true, message: 'Please input the prefix!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="suffix"
            label={<span style={{ fontWeight: 'bold' }}>Suffix</span>}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="seperator"
            label={<span style={{ fontWeight: 'bold' }}>Separator</span>}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="starting_no"
            label={<span style={{ fontWeight: 'bold' }}>Starting No</span>}
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="current_no"
            label={<span style={{ fontWeight: 'bold' }}>Current No</span>}
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SequenceGenerator;