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

type InboxMessage = {
  id: number;
  subject: string;
  body: string;
  createdAt: string;
  readAt: string | null;
  sender: string;
};

type SentMessage = {
  id: number;
  subject: string;
  body: string;
  createdAt: string;
  recipientCount: number;
};

type User = {
  id: number;
  name: string;
  role: string;
};

type Props = {
  inbox: InboxMessage[];
  sent: SentMessage[];
  users: User[];
};

export default function Messages({ inbox, sent, users }: Props) {
  const [tab, setTab] = useState<'inbox' | 'sent' | 'compose'>('inbox');
  const [expanded, setExpanded] = useState<number | null>(null);

  const form = useForm({
    recipient_ids: [] as number[],
    subject: '',
    body: '',
  });

  function toggleRecipient(id: number) {
    const current = form.data.recipient_ids;
    if (current.includes(id)) {
      form.setData('recipient_ids', current.filter((r) => r !== id));
    } else {
      form.setData('recipient_ids', [...current, id]);
    }
  }

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    form.post('/school/messages', {
      onSuccess: () => {
        form.reset();
        setTab('sent');
      },
    });
  }

  function handleMarkRead(id: number) {
    router.patch(`/school/messages/${id}/read`, {}, { preserveScroll: true });
  }

  const unreadCount = inbox.filter((m) => !m.readAt).length;

  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={() => setTab('compose')}>
            <i className="bi bi-pencil-square" /> پیام جدید
          </button>
        </section>

        <div className="tab-bar">
          <button
            className={`tab-btn${tab === 'inbox' ? ' active' : ''}`}
            type="button"
            onClick={() => setTab('inbox')}
          >
            صندوق ورودی
            {unreadCount > 0 && (
              <span className="badge badge-warning" style={{ marginRight: '0.4rem', fontSize: '0.75rem' }}>
                {unreadCount}
              </span>
            )}
          </button>
          <button
            className={`tab-btn${tab === 'sent' ? ' active' : ''}`}
            type="button"
            onClick={() => setTab('sent')}
          >
            ارسال‌شده
          </button>
          <button
            className={`tab-btn${tab === 'compose' ? ' active' : ''}`}
            type="button"
            onClick={() => setTab('compose')}
          >
            نوشتن پیام
          </button>
        </div>

        {tab === 'inbox' && (
          <div className="panel-card">
            {inbox.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>صندوق ورودی خالی است.</p>
            ) : (
              inbox.map((message) => (
                <div
                  key={message.id}
                  style={{
                    borderBottom: '1px solid var(--color-border)',
                    padding: '1rem 0',
                    background: message.readAt ? 'transparent' : 'var(--color-bg-soft)',
                    marginInline: '-1rem',
                    paddingInline: '1rem',
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '0.5rem' }}>
                    <div>
                      <strong style={{ fontWeight: message.readAt ? 500 : 700 }}>{message.subject}</strong>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem', marginRight: '0.75rem' }}>
                        از: {message.sender}
                      </span>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.8rem', marginRight: '0.75rem' }}>
                        {message.createdAt}
                      </span>
                      {!message.readAt && (
                        <span className="badge badge-warning" style={{ fontSize: '0.7rem' }}>جدید</span>
                      )}
                    </div>
                    <div className="action-row--compact">
                      <button
                        className="btn btn-ghost btn-sm"
                        type="button"
                        onClick={() => setExpanded(expanded === message.id ? null : message.id)}
                      >
                        {expanded === message.id ? 'بستن' : 'نمایش'}
                      </button>
                      {!message.readAt && (
                        <button
                          className="btn btn-soft btn-sm"
                          type="button"
                          onClick={() => handleMarkRead(message.id)}
                        >
                          خوانده شد
                        </button>
                      )}
                    </div>
                  </div>
                  {expanded === message.id && (
                    <div style={{ marginTop: '0.75rem', whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>
                      {message.body}
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        )}

        {tab === 'sent' && (
          <div className="panel-card">
            {sent.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>پیامی ارسال نشده است.</p>
            ) : (
              sent.map((message) => (
                <div
                  key={message.id}
                  style={{ borderBottom: '1px solid var(--color-border)', padding: '1rem 0' }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <strong>{message.subject}</strong>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem', marginRight: '0.75rem' }}>
                        {message.recipientCount} گیرنده
                      </span>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.8rem', marginRight: '0.75rem' }}>
                        {message.createdAt}
                      </span>
                    </div>
                    <button
                      className="btn btn-ghost btn-sm"
                      type="button"
                      onClick={() => setExpanded(expanded === message.id ? null : message.id)}
                    >
                      {expanded === message.id ? 'بستن' : 'نمایش'}
                    </button>
                  </div>
                  {expanded === message.id && (
                    <div style={{ marginTop: '0.75rem', whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>
                      {message.body}
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        )}

        {tab === 'compose' && (
          <form className="panel-card" onSubmit={handleSubmit}>
            <h2>نوشتن پیام جدید</h2>

            <div className="form-field">
              <span>گیرندگان</span>
              {form.errors.recipient_ids && (
                <p style={{ color: 'var(--color-danger)', fontSize: '0.85rem' }}>{form.errors.recipient_ids}</p>
              )}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '0.5rem' }}>
                {users.map((user) => (
                  <label
                    key={user.id}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '0.35rem',
                      background: form.data.recipient_ids.includes(user.id)
                        ? 'var(--color-primary-soft)'
                        : 'var(--color-bg-soft)',
                      border: `1px solid ${form.data.recipient_ids.includes(user.id) ? 'var(--color-primary)' : 'var(--color-border)'}`,
                      borderRadius: 'var(--radius-sm)',
                      padding: '0.3rem 0.7rem',
                      cursor: 'pointer',
                      fontSize: '0.875rem',
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={form.data.recipient_ids.includes(user.id)}
                      onChange={() => toggleRecipient(user.id)}
                    />
                    {user.name}
                    <span style={{ color: 'var(--color-text-muted)', fontSize: '0.75rem' }}>({user.role})</span>
                  </label>
                ))}
              </div>
              {users.length === 0 && (
                <p style={{ color: 'var(--color-text-muted)' }}>کاربری در مدرسه تعریف نشده.</p>
              )}
            </div>

            <TextInput
              label="موضوع (اختیاری)"
              value={form.data.subject}
              onChange={(e) => form.setData('subject', e.target.value)}
            />

            <label className="form-field">
              <span>متن پیام</span>
              <textarea
                className="form-textarea"
                rows={6}
                value={form.data.body}
                onChange={(e) => form.setData('body', e.target.value)}
                required
              />
              {form.errors.body && (
                <span style={{ color: 'var(--color-danger)', fontSize: '0.85rem' }}>{form.errors.body}</span>
              )}
            </label>

            <div className="action-row">
              <button className="btn btn-primary" disabled={form.processing} type="submit">
                <i className="bi bi-send" /> ارسال پیام
              </button>
              <button className="btn btn-ghost" type="button" onClick={() => { form.reset(); setTab('inbox'); }}>
                لغو
              </button>
            </div>
          </form>
        )}
      </div>
    </AppLayout>
  );
}
