import { useState, useEffect } from 'react';
import { Navbar } from '../components/Navbar';
import { DataTable } from '../components/DataTable';
import { Modal } from '../components/Modal';
import { Loading } from '../components/Loading';
import { useToast } from '../components/Toast';
import { templatesAPI } from '../api/client';

export const TemplatesPage = () => {
  const [templates, setTemplates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    language: 'en',
    body_text: '',
    is_whatsapp_template: false,
    provider_template_name: ''
  });
  const { showToast } = useToast();

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

  const loadTemplates = async () => {
    try {
      const response = await templatesAPI.list();
      setTemplates(response.data);
    } catch (error) {
      showToast('Failed to load templates', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await templatesAPI.create(formData);
      showToast('Template created successfully', 'success');
      setShowModal(false);
      setFormData({ name: '', language: 'en', body_text: '', is_whatsapp_template: false, provider_template_name: '' });
      loadTemplates();
    } catch (error) {
      showToast('Failed to create template', 'error');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this template?')) return;
    try {
      await templatesAPI.delete(id);
      showToast('Template deleted', 'success');
      loadTemplates();
    } catch (error) {
      showToast('Failed to delete template', 'error');
    }
  };

  const columns = [
    { header: 'Name', accessor: 'name' },
    { header: 'Language', accessor: 'language' },
    { header: 'WhatsApp Template', render: (row) => <span className={`badge badge-${row.is_whatsapp_template ? 'success' : 'info'}`}>{row.is_whatsapp_template ? 'Yes' : 'No'}</span> },
    { header: 'Body Preview', render: (row) => row.body_text.substring(0, 50) + '...' },
    { header: 'Actions', render: (row) => <button onClick={() => handleDelete(row.id)} className="btn btn-danger" style={{ padding: '4px 12px' }}>Delete</button> }
  ];

  if (loading) return <Loading />;

  return (
    <>
      <Navbar />
      <div className="container">
        <div className="page">
          <div className="page-header">
            <h1 className="page-title">Templates</h1>
            <button onClick={() => setShowModal(true)} className="btn btn-primary">Create Template</button>
          </div>
          <DataTable columns={columns} data={templates} />
        </div>
      </div>

      <Modal isOpen={showModal} onClose={() => setShowModal(false)} title="Create Template">
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label className="form-label">Name</label>
            <input type="text" className="form-input" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} required />
          </div>
          <div className="form-group">
            <label className="form-label">Language</label>
            <select className="form-select" value={formData.language} onChange={(e) => setFormData({ ...formData, language: e.target.value })}>
              <option value="en">English</option>
              <option value="en_US">English (United States)</option>
              <option value="es">Spanish</option>
              <option value="fr">French</option>
              <option value="ar">Arabic</option>
            </select>
          </div>
          <div className="form-group">
            <label className="form-label">Body Text (use {'{{first_name}}'} for variables)</label>
            <textarea className="form-textarea" value={formData.body_text} onChange={(e) => setFormData({ ...formData, body_text: e.target.value })} required placeholder="Hello {{first_name}}, welcome!" />
          </div>
          <div className="form-group">
            <label><input type="checkbox" className="form-checkbox" checked={formData.is_whatsapp_template} onChange={(e) => setFormData({ ...formData, is_whatsapp_template: e.target.checked })} /> Approved WhatsApp Template</label>
          </div>
          {formData.is_whatsapp_template && (
            <div className="form-group">
              <label className="form-label">Provider Template Name</label>
              <input type="text" className="form-input" value={formData.provider_template_name} onChange={(e) => setFormData({ ...formData, provider_template_name: e.target.value })} />
            </div>
          )}
          <button type="submit" className="btn btn-primary">Create</button>
        </form>
      </Modal>
    </>
  );
};
