import { useState } from 'react';
import { useForm } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';

type Template = {
  id: number;
  keyName: string;
  title: string;
  body: string;
  status: string;
  isGlobal: boolean;
};

type Props = {
  templates: Template[];
};

const PLACEHOLDERS = [
  '{student_name}', '{class_name}', '{subject_name}',
  '{date}', '{school_name}', '{teacher_name}',
];

export default function Templates({ templates }: Props) {
  const [showForm, setShowForm] = useState(false);
  const [editTarget, setEditTarget] = useState<Template | null>(null);

  const createForm = useForm({ key_name: '', title: '', body: '' });
  const editForm = useForm({ title: '', body: '' });

  function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    createForm.post('/school/sms-templates', {
      onSuccess: () => { createForm.reset(); setShowForm(false); },
    });
  }

  function startEdit(t: Template) {
    setEditTarget(t);
    editForm.setData({ title: t.title, body: t.body });
  }

  function handleEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!editTarget) return;
    editForm.put(`/school/sms-templates/${editTarget.id}`, {
      onSuccess: () => setEditTarget(null),
    });
  }

  function handleDelete(t: Template) {
    if (!confirm(`حذف template «${t.title}»؟`)) return;
    editForm.delete(`/school/sms-templates/${t.id}`);
  }

  return (
    <AppLayout title="قالب‌های پیامک">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>قالب‌های پیامک</h2>
            <p>متن‌های آماده پیامک برای غیبت، کلاس آنلاین و اطلاع‌رسانی.</p>
          </div>
          <button className="btn btn-primary" type="button" onClick={() => setShowForm(!showForm)}>
            <i className="bi bi-plus-circle" /> template جدید
          </button>
        </section>

        <section className="panel-card" style={{ background: 'var(--color-primary-soft-2)' }}>
          <p style={{ marginBottom: '0.5rem', fontWeight: 600, fontSize: '0.9rem' }}>متغیرهای قابل استفاده در متن:</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
            {PLACEHOLDERS.map((p) => (
              <code key={p} style={{ background: 'white', border: '1px solid var(--color-border)', borderRadius: '6px', padding: '0.2rem 0.6rem', fontSize: '0.85rem' }}>
                {p}
              </code>
            ))}
          </div>
        </section>

        {showForm && (
          <form className="panel-card" onSubmit={handleCreate}>
            <h2>template جدید</h2>
            <div className="form-grid">
              <TextInput
                label="کلید (a-z, 0-9, _)"
                value={createForm.data.key_name}
                onChange={(e) => createForm.setData('key_name', e.target.value)}
                error={createForm.errors.key_name}
              />
              <TextInput
                label="عنوان"
                value={createForm.data.title}
                onChange={(e) => createForm.setData('title', e.target.value)}
                error={createForm.errors.title}
              />
            </div>
            <div style={{ marginBottom: '1rem' }}>
              <label style={{ display: 'block', marginBottom: '0.4rem', fontWeight: 600, fontSize: '0.9rem' }}>
                متن پیامک
              </label>
              <textarea
                value={createForm.data.body}
                onChange={(e) => createForm.setData('body', e.target.value)}
                rows={4}
                style={{
                  width: '100%', border: '1.5px solid var(--color-border)', borderRadius: 'var(--radius-sm)',
                  padding: '0.65rem 0.9rem', fontSize: '0.95rem', fontFamily: 'inherit', resize: 'vertical',
                  boxSizing: 'border-box',
                }}
              />
              {createForm.errors.body && <p style={{ color: 'var(--color-danger)', fontSize: '0.85rem' }}>{createForm.errors.body}</p>}
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={createForm.processing} type="submit">ذخیره</button>
              <button className="btn btn-ghost" type="button" onClick={() => { createForm.reset(); setShowForm(false); }}>لغو</button>
            </div>
          </form>
        )}

        {editTarget && (
          <form className="panel-card" onSubmit={handleEdit} style={{ border: '2px solid var(--color-primary)' }}>
            <h2>ویرایش — {editTarget.keyName}</h2>
            <div className="form-grid">
              <TextInput
                label="عنوان"
                value={editForm.data.title}
                onChange={(e) => editForm.setData('title', e.target.value)}
                error={editForm.errors.title}
              />
            </div>
            <div style={{ marginBottom: '1rem' }}>
              <label style={{ display: 'block', marginBottom: '0.4rem', fontWeight: 600, fontSize: '0.9rem' }}>متن پیامک</label>
              <textarea
                value={editForm.data.body}
                onChange={(e) => editForm.setData('body', e.target.value)}
                rows={4}
                style={{
                  width: '100%', border: '1.5px solid var(--color-border)', borderRadius: 'var(--radius-sm)',
                  padding: '0.65rem 0.9rem', fontSize: '0.95rem', fontFamily: 'inherit', resize: 'vertical',
                  boxSizing: 'border-box',
                }}
              />
              {editForm.errors.body && <p style={{ color: 'var(--color-danger)', fontSize: '0.85rem' }}>{editForm.errors.body}</p>}
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={editForm.processing} type="submit">ذخیره</button>
              <button className="btn btn-ghost" type="button" onClick={() => setEditTarget(null)}>لغو</button>
            </div>
          </form>
        )}

        {templates.length === 0 ? (
          <section className="panel-card">
            <p>هیچ templateی وجود ندارد. از دکمه بالا template جدید بسازید.</p>
          </section>
        ) : (
          <div className="table-wrap panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>کلید</th>
                  <th>عنوان</th>
                  <th>متن</th>
                  <th>نوع</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {templates.map((t) => (
                  <tr key={t.id}>
                    <td><code style={{ fontSize: '0.8rem' }}>{t.keyName}</code></td>
                    <td>{t.title}</td>
                    <td style={{ maxWidth: 320, color: 'var(--color-text-muted)', fontSize: '0.85rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {t.body}
                    </td>
                    <td>
                      {t.isGlobal
                        ? <span className="badge badge-muted">پیش‌فرض</span>
                        : <span className="badge badge-success">اختصاصی</span>
                      }
                    </td>
                    <td>
                      <div className="action-row--compact">
                        {!t.isGlobal && (
                          <>
                            <button className="btn btn-soft btn-sm" type="button" onClick={() => startEdit(t)}>
                              <i className="bi bi-pencil" /> ویرایش
                            </button>
                            <button className="btn btn-ghost btn-sm" type="button" onClick={() => handleDelete(t)}>
                              <i className="bi bi-trash" />
                            </button>
                          </>
                        )}
                        {t.isGlobal && <span style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>غیرقابل ویرایش</span>}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
