'use client';

import { useState, useEffect } from 'react';
import { Trash2, Plus, Mail } from 'lucide-react';
import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';

interface MailSender {
  id: number;
  type: 'address' | 'domain';
  email: string | null;
  domain: string | null;
  rule: 'never_notify' | 'always_notify';
  note: string;
  created_at: string;
}

const RULE_LABEL: Record<MailSender['rule'], string> = {
  always_notify: '常に通知',
  never_notify: '通知しない',
};

const RULE_STYLE: Record<MailSender['rule'], string> = {
  always_notify: 'bg-teal-100 text-teal-700',
  never_notify: 'bg-orange-100 text-orange-700',
};

export default function MailRulesPage() {
  const [senders, setSenders] = useState<MailSender[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 追加フォーム
  const [addType, setAddType] = useState<'address' | 'domain'>('address');
  const [addRule, setAddRule] = useState<'never_notify' | 'always_notify'>('never_notify');
  const [addValue, setAddValue] = useState('');
  const [addNote, setAddNote] = useState('');
  const [adding, setAdding] = useState(false);
  const [addError, setAddError] = useState<string | null>(null);

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

  const fetchSenders = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await api.get('/mail/senders/');
      setSenders(res.data);
    } catch {
      setError('ルール一覧の取得に失敗しました');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('このルールを削除してもよいですか？')) return;
    try {
      await api.delete(`/mail/senders/${id}/`);
      setSenders((prev) => prev.filter((s) => s.id !== id));
    } catch {
      alert('削除に失敗しました');
    }
  };

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddError(null);

    if (!addValue.trim()) {
      setAddError('値を入力してください');
      return;
    }

    setAdding(true);
    try {
      const body: Record<string, string> = {
        rule: addRule,
        note: addNote.trim(),
      };
      if (addType === 'address') {
        body.email = addValue.trim();
      } else {
        body.domain = addValue.trim();
      }

      const res = await api.post('/mail/senders/', body);
      setSenders((prev) => [res.data, ...prev]);
      setAddValue('');
      setAddNote('');
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosError = err as { response?: { data?: Record<string, string[]> } };
        const data = axiosError.response?.data;
        if (data) {
          const messages = Object.values(data).flat().join(' ');
          setAddError(messages || '追加に失敗しました');
        } else {
          setAddError('追加に失敗しました');
        }
      } else {
        setAddError('追加に失敗しました');
      }
    } finally {
      setAdding(false);
    }
  };

  const formatDate = (iso: string) => {
    const d = new Date(iso);
    return d.toLocaleDateString('ja-JP', { year: 'numeric', month: '2-digit', day: '2-digit' });
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-3xl mx-auto px-4 py-8">
        <div className="flex items-center gap-3 mb-6">
          <Mail className="h-6 w-6 text-gray-600" />
          <h1 className="text-2xl font-bold text-gray-900">メール通知ルール</h1>
        </div>

        {/* 追加フォーム */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-5 mb-6">
          <h2 className="text-sm font-semibold text-gray-700 mb-4">ルールを追加</h2>
          <form onSubmit={handleAdd} className="space-y-3">
            <div className="flex gap-2 flex-wrap">
              {/* 種別（アドレス / ドメイン） */}
              <select
                value={addType}
                onChange={(e) => setAddType(e.target.value as 'address' | 'domain')}
                className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
              >
                <option value="address">アドレス</option>
                <option value="domain">ドメイン</option>
              </select>
              {/* ルール種別（常に通知 / 通知しない） */}
              <select
                value={addRule}
                onChange={(e) => setAddRule(e.target.value as 'never_notify' | 'always_notify')}
                className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
              >
                <option value="never_notify">🔇 通知しない</option>
                <option value="always_notify">🔔 常に通知</option>
              </select>
              {/* 値（アドレス or ドメイン） */}
              <input
                type="text"
                value={addValue}
                onChange={(e) => setAddValue(e.target.value)}
                placeholder={addType === 'address' ? 'promo@example.com' : 'example.com'}
                className="flex-1 min-w-40 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
            <div className="flex gap-2">
              <input
                type="text"
                value={addNote}
                onChange={(e) => setAddNote(e.target.value)}
                placeholder="メモ（任意）例: ○○の営業メール / 農協からの通知"
                className="flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
              />
              <button
                type="submit"
                disabled={adding}
                className="flex items-center gap-1.5 px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors"
              >
                <Plus className="h-4 w-4" />
                追加
              </button>
            </div>
            {addError && (
              <p className="text-sm text-red-600">{addError}</p>
            )}
          </form>
        </div>

        {/* ルール一覧 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200">
          <div className="px-5 py-3 border-b border-gray-200">
            <h2 className="text-sm font-semibold text-gray-700">
              送信者ルール一覧
              {!loading && <span className="ml-2 text-gray-400 font-normal">（{senders.length}件）</span>}
            </h2>
          </div>

          {loading && (
            <div className="p-8 text-center text-gray-400 text-sm">読み込み中...</div>
          )}

          {error && (
            <div className="p-4 text-center text-red-600 text-sm">{error}</div>
          )}

          {!loading && !error && senders.length === 0 && (
            <div className="p-8 text-center text-gray-400 text-sm">
              登録されているルールはありません
            </div>
          )}

          {!loading && !error && senders.length > 0 && (
            <div className="divide-y divide-gray-100">
              {senders.map((sender) => (
                <div key={sender.id} className="flex items-center gap-3 px-5 py-3">
                  {/* 種別バッジ */}
                  <span className={`text-xs px-2 py-0.5 rounded-full font-medium shrink-0 ${
                    sender.type === 'address'
                      ? 'bg-blue-100 text-blue-700'
                      : 'bg-purple-100 text-purple-700'
                  }`}>
                    {sender.type === 'address' ? 'アドレス' : 'ドメイン'}
                  </span>
                  {/* ルールバッジ */}
                  <span className={`text-xs px-2 py-0.5 rounded-full font-medium shrink-0 ${RULE_STYLE[sender.rule]}`}>
                    {RULE_LABEL[sender.rule]}
                  </span>
                  {/* 値・メモ */}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-800 truncate">
                      {sender.email || sender.domain}
                    </p>
                    {sender.note && (
                      <p className="text-xs text-gray-400 truncate">{sender.note}</p>
                    )}
                  </div>
                  <span className="text-xs text-gray-400 shrink-0">{formatDate(sender.created_at)}</span>
                  <button
                    onClick={() => handleDelete(sender.id)}
                    className="text-gray-300 hover:text-red-500 transition-colors shrink-0"
                    title="削除"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
