import React, { useState, useEffect } from 'react';
import Sidebar from './OCRSidebar';
import { createTemplate, getTemplates, deleteTemplate, createOrUpdateTemplate } from '../services/api';

function OCRTemplate() {
  const [templates, setTemplates] = useState([]);
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [newTemplateName, setNewTemplateName] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [message, setMessage] = useState('');

  const fetchTemplates = async () => {
    try {
      const response = await getTemplates();
      console.log('fetchTemplates Response:', response);
      const mappedTemplates = response.map(template => ({
        template_name: template.template_name,
        variables: Object.values(template.fields || {}), // Map fields to variables
        user_id: template.user_id,
      }));
      setTemplates(mappedTemplates);
    } catch (error) {
      console.error('Error fetching templates:', error);
    }
  };
  const handleTemplateChange = (e) => {
    const templateName = e.target.value;
    if (templateName === 'new') {
      setSelectedTemplate(null);
      setNewTemplateName('');
      setIsEditing(false);
    } else {
      
      const existingTemplate = templates.find(template => template.template_name === templateName);
      setSelectedTemplate(existingTemplate || null);
      setIsEditing(!!existingTemplate);
      
    }
  };

 

  const addVariable = () => {
    const newTemplate = { ...selectedTemplate, variables: [...(selectedTemplate.variables || []), ''] };
    setSelectedTemplate(newTemplate);
  };

  const handleTemplateNameChange = (value) => {
    const newTemplate = { ...selectedTemplate, template_name: value };
    setSelectedTemplate(newTemplate);
  };

  const handleVariableChange = (variableIndex, value) => {
    const newTemplate = { ...selectedTemplate };
    newTemplate.variables[variableIndex] = value;
    setSelectedTemplate(newTemplate);
  };

  const addTemplate = () => {
    const newTemplate = { template_name: newTemplateName, variables: [''] };
    // setTemplates([...templates, newTemplate]);
    setSelectedTemplate(newTemplate);
    setIsEditing(true);
  };

  const handleSubmit = async () => {
    const template = selectedTemplate;
    const fields = {};
    template.variables.forEach((variable, i) => {
      fields[`additionalProp${i + 1}`] = variable;
    });

    try {
      console.log(template);
      // Check if the template name already exists
      const existingTemplate = templates.find(t => t.template_name === template.template_name);

  

      if (existingTemplate) {
        // Update existing template
        console.log('existingTemplate', existingTemplate.template_name);
        await createOrUpdateTemplate(template.template_name, fields, template.user_id, true);
        setMessage('Template updated successfully!');
      } else {
        console.log('Creating new template');
        // Create new template
        const newTemplate = await createOrUpdateTemplate(template.template_name, fields, template.user_id, false);
      
        setMessage('Template created successfully!');
      }
      fetchTemplates(); // Fetch templates again to update the list
    } catch (error) {
      setMessage('Handle submit Error creating/updating template.');
    }
  };

  const handleDeleteTemplate = async () => {
    const templateName = selectedTemplate.template_name;
    try {
      await deleteTemplate(templateName);
      setTemplates(templates.filter(template => template.template_name !== templateName));
      setSelectedTemplate(null);
      setMessage('Template deleted successfully!');
    } catch (error) {
      setMessage('Error deleting template.');
    }
  };

  const handleDeleteVariable = (variableIndex) => {
    const newTemplate = { ...selectedTemplate };
    newTemplate.variables.splice(variableIndex, 1);
    setSelectedTemplate(newTemplate);
  };

  // Fetch templates on component mount
  useEffect(() => {
    fetchTemplates();
  }, []);

  return (
    <div className="min-h-screen bg-gray-100 flex">
      <Sidebar />
      <div className="flex-1 p-6">
        <div className="bg-white p-6 rounded-lg shadow-lg w-full max-w-4xl mx-auto">
          <h2 className="text-xl font-semibold text-gray-700">Application Template</h2>
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">Select Template</label>
            <select
              value={selectedTemplate ? selectedTemplate.template_name : 'new'}
              onChange={handleTemplateChange}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 mb-2"
            >
              <option value="new">Create New Template</option>
              {templates.map((template, index) => (
                <option key={index} value={template.template_name}>{template.template_name}</option>
              ))}
            </select>
          </div>
          {!selectedTemplate && (
            <div className="mb-4">
              <label className="block text-gray-700 text-sm font-bold mb-2">Template Name</label>
              <input
                type="text"
                value={newTemplateName}
                onChange={(e) => setNewTemplateName(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 mb-2"
              />
              <button
                onClick={addTemplate}
                className="bg-green-500 text-white py-2 px-4 rounded-lg hover:bg-green-600 transition duration-200"
              >
                Add Template
              </button>
            </div>
          )}
          {selectedTemplate && (
            <div className="mb-4">
              <label className="block text-gray-700 text-sm font-bold mb-2">Template Name</label>
              <input
                type="text"
                value={selectedTemplate.template_name}
                onChange={(e) => handleTemplateNameChange(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 mb-2"
              />
              {selectedTemplate.variables.map((variable, varIndex) => (
                <div key={varIndex} className="mb-2 flex items-center">
                  <label className="block text-gray-700 text-sm font-bold mb-2">Variable {varIndex + 1}</label>
                  <input
                    type="text"
                    value={variable}
                    onChange={(e) => handleVariableChange(varIndex, e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 mx-2"
                  />
                  <button
                    onClick={() => handleDeleteVariable(varIndex)}
                    className="bg-red-500 text-white py-2 px-4 rounded-lg hover:bg-red-600 transition duration-200"
                  >
                    Delete Variable
                  </button>
                </div>
              ))}
              <div className="flex items-center">
                <button
                  onClick={addVariable}
                  className="bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition duration-200 mr-2"
                >
                  Add Variable
                </button>
                <button
                  onClick={handleSubmit}
                  className="bg-green-500 text-white py-2 px-4 rounded-lg hover:bg-green-600 transition duration-200 mr-2"
                >
                  Submit Template
                </button>
                <button
                  onClick={handleDeleteTemplate}
                  className="bg-red-500 text-white py-2 px-4 rounded-lg hover:bg-red-600 transition duration-200"
                >
                  Delete Template
                </button>
              </div>
            </div>
          )}
          {message && <p className="mt-4 text-gray-700">{message}</p>}
        </div>
      </div>
    </div>
  );
}

export default OCRTemplate;
