import React, { useState, useEffect } from 'react';
import Sidebar from './OCRSidebar';
import Header from './OCRHeader';
import { getTemplates, ocrProcess } from '../services/api';
import Quota from './OCRQuota';
import OCRTemplate from './OCRTemplate';
import Credentials from './ERPCredentials';
import InvoiceForm from './InvoiceForm';

const Dashboard = () => {
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [templates, setTemplates] = useState([]); // Ensure templates is initialized as an array
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [credentials, setCredentials] = useState({
    sapUrl: '',
    clientId: '',
    clientSecret: '',
    username: '',
    password: '',
    companyCode: '',
    apiKey: ''
  });

  const fetchTemplates = async (templateName = false) => {
    try {
      const response = await getTemplates(templateName);
      setTemplates(response); // Ensure response is directly set to templates
    } catch (error) {
      console.error('Error fetching templates:', error);
    }
  };

  const handleFolderSelect = (event) => {
    const files = Array.from(event.target.files);
    const validFileTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg', 'image/PNG', 'image/JPEG'];
    const filteredFiles = files.filter(file => validFileTypes.includes(file.type));
    setSelectedFiles(filteredFiles);
  };

  const handleTemplateChange = (event) => {
    const newValue = event.target.value;
    setSelectedTemplate(newValue);
    console.log("selectedTemplate:", newValue);
    // Fetch templates based on the selected template
  };

  const handleCredentialsSave = (newCredentials) => {
    setCredentials(newCredentials);
  };

  const handleSubmit = async (event) => {
    event.preventDefault(); // Prevent default form submission behavior

    if (selectedFiles.length === 0) {
      alert("Please select files containing PDF, PNG, or JPG files.");
      return;
    }

    if (!selectedTemplate) {
      alert("Please select a template.");
      return;
    }

    const formData = new FormData();
    selectedFiles.forEach(file => formData.append("files", file));
    formData.append("template_name", selectedTemplate);

    // Debugging formData
    for (let [key, value] of formData.entries()) {
      console.log(`${key}: ${value.name || value}`);
    }

    try {
      const response = await ocrProcess(formData);
      console.log("Response:", response);
      alert("Files processed successfully!");
    } catch (error) {
      console.error("Error:", error);
      alert("There was an error processing the files.");
    }
  };

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

  return (
    <div className="min-h-screen bg-gray-100 flex">
      <Sidebar />
      <div className="flex-1 p-6">
        <Header />
        <div className="bg-white p-6 rounded-lg shadow-lg w-full max-w-4xl mx-auto">
          <h1 className="text-2xl font-semibold text-gray-700 mb-4">Automate Data Input & OCR</h1>
          <p className="text-gray-600 mb-4">
            AI services that allow you to extract information from any documents and automate data input to external applications.
          </p>
          <div className="border-t border-gray-200 pt-4">
            <h2 className="text-xl font-semibold text-gray-700 mb-4">Upload PDF Folder</h2>
            <div className="mb-4">
              <input
                type="file"
                // webkitdirectory="true"
                // mozdirectory="true"
                // directory=""
                onChange={handleFolderSelect}
                multiple
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600"
              />
            </div>
            {selectedFiles.length > 0 && (
              <div className="mb-4">
                <h3 className="text-lg font-semibold text-gray-700">Detected PDF Files:</h3>
                <ul className="list-disc pl-5">
                  {selectedFiles.map((file, index) => (
                    <li key={index} className="text-gray-600">{file.name}</li>
                  ))}
                </ul>
              </div>
            )}
            <div className="mb-4">
              <label className="block text-gray-700 text-sm font-bold mb-2">Select Template</label>
              <select
                value={selectedTemplate}
                onChange={handleTemplateChange}
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600"
              >
                <option value="">Select a template</option>
                {templates.map((template, index) => (
                  <option key={index} value={template.template_name}>{template.template_name}</option>
                ))}
              </select>
            </div>
            <button
              onClick={handleSubmit}
              className="w-full bg-blue-500 text-white py-2 rounded-lg hover:bg-blue-600 transition duration-200 mb-4"
            >
              Process Files
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
