'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import Navbar from '@/components/Navbar';
import { Mail, Loader2, CheckCircle, XCircle, Clock, Shield, MessageSquare } from 'lucide-react';

interface MailEmail {
  id: number;
  account: string;
  sender_email: string;
  sender_domain: string;
  subject: string;
  received_at: string;
  llm_verdict: 'important' | 'not_important';
  notified_at: string | null;
  feedback: 'important' | 'not_important' | 'never_notify' | 'always_notify' | null;
  feedback_at: string | null;
  feedback_token: string | null;
}

const FEEDBACK_LABELS: Record<string, string> = {
  important: '重要だった',
  not_important: '普通のメール',
  never_notify: '通知しない',
  always_notify: '常に通知',
};

const ACCOUNT_LABELS: Record<string, string> = {
  gmail: 'Gmail',
  gmail_service: 'Gmail (サービス用)',
  hotmail: 'Hotmail',
  xserver1: 'Xserver (akira@keinafarm.com)',
  xserver2: 'Xserver (service@keinafarm.com)',
  xserver3: 'Xserver (midori@keinafarm.com)',
  xserver4: 'Xserver (kouseiren@keinafarm.com)',
  xserver5: 'Xserver (post@keinafarm.com)',
  xserver6: 'Xserver (sales@keinafarm.com)',
  xserver: 'Xserver (旧データ)',
};

const FEEDBACK_OPTIONS = [
  { value: 'important',    label: '重要だった',        color: 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100' },
  { value: 'not_important',label: '普通のメール',       color: 'bg-gray-50 text-gray-600 border-gray-200 hover:bg-gray-100' },
  { value: 'never_notify', label: '今後通知しない',     color: 'bg-orange-50 text-orange-700 border-orange-200 hover:bg-orange-100' },
  { value: 'always_notify',label: '常に通知してほしい', color: 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100' },
];

export default function MailHistoryPage() {
  const router = useRouter();
  const [emails, setEmails] = useState<MailEmail[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterAccount, setFilterAccount] = useState('');
  const [filterVerdict, setFilterVerdict] = useState('');

  // フィードバックモーダル
  const [feedbackModal, setFeedbackModal] = useState<MailEmail | null>(null);
  const [pendingFeedback, setPendingFeedback] = useState('');
  const [pendingScope, setPendingScope] = useState<'address' | 'domain'>('address');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    const fetchEmails = async () => {
      setLoading(true);
      try {
        const params = new URLSearchParams();
        if (filterAccount) params.set('account', filterAccount);
        if (filterVerdict) params.set('verdict', filterVerdict);
        const res = await api.get(`/mail/emails/?${params.toString()}`);
        setEmails(res.data);
      } catch (error) {
        console.error('Failed to fetch emails:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchEmails();
  }, [filterAccount, filterVerdict]);

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('ja-JP', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const openFeedbackModal = (email: MailEmail) => {
    setFeedbackModal(email);
    setPendingFeedback(email.feedback ?? '');
    setPendingScope('address');
  };

  const closeFeedbackModal = () => {
    setFeedbackModal(null);
    setPendingFeedback('');
  };

  const submitFeedback = async () => {
    if (!feedbackModal || !pendingFeedback) return;
    setSubmitting(true);
    try {
      const body: Record<string, string> = { feedback: pendingFeedback };
      if (['never_notify', 'always_notify'].includes(pendingFeedback)) {
        body.scope = pendingScope;
      }
      await api.patch(`/mail/emails/${feedbackModal.id}/feedback/`, body);
      setEmails(prev => prev.map(e =>
        e.id === feedbackModal.id
          ? { ...e, feedback: pendingFeedback as MailEmail['feedback'], feedback_at: new Date().toISOString() }
          : e
      ));
      closeFeedbackModal();
    } catch (error) {
      console.error('Failed to submit feedback:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const needsScope = ['never_notify', 'always_notify'].includes(pendingFeedback);

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* ヘッダー */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <Mail className="h-6 w-6 text-blue-600" />
            <h1 className="text-2xl font-bold text-gray-900">メール処理履歴</h1>
          </div>
          <button
            onClick={() => router.push('/mail/rules')}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors text-gray-700"
          >
            <Shield className="h-4 w-4" />
            ルール管理
          </button>
        </div>

        {/* フィルター */}
        <div className="bg-white rounded-lg shadow p-4 mb-4 flex gap-3">
          <select
            value={filterAccount}
            onChange={(e) => setFilterAccount(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm"
          >
            <option value="">全アカウント</option>
            <option value="gmail">Gmail</option>
            <option value="gmail_service">Gmail (サービス用)</option>
            <option value="hotmail">Hotmail</option>
            <option value="xserver1">Xserver (akira@keinafarm.com)</option>
            <option value="xserver2">Xserver (service@keinafarm.com)</option>
            <option value="xserver3">Xserver (midori@keinafarm.com)</option>
            <option value="xserver4">Xserver (kouseiren@keinafarm.com)</option>
            <option value="xserver5">Xserver (post@keinafarm.com)</option>
            <option value="xserver6">Xserver (sales@keinafarm.com)</option>
            <option value="xserver">Xserver (旧データ)</option>
          </select>
          <select
            value={filterVerdict}
            onChange={(e) => setFilterVerdict(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm"
          >
            <option value="">全判定</option>
            <option value="important">重要</option>
            <option value="not_important">通常</option>
          </select>
        </div>

        {/* テーブル */}
        {loading ? (
          <div className="flex justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
          </div>
        ) : emails.length === 0 ? (
          <div className="text-center py-16 text-gray-500">処理済みメールはありません</div>
        ) : (
          <div className="bg-white rounded-lg shadow overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium whitespace-nowrap">受信日時</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">送信者</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">件名</th>
                  <th className="text-center px-4 py-3 text-gray-500 font-medium whitespace-nowrap">LLM判定</th>
                  <th className="text-center px-4 py-3 text-gray-500 font-medium whitespace-nowrap">フィードバック</th>
                </tr>
              </thead>
              <tbody>
                {emails.map((email) => (
                  <tr key={email.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="px-4 py-3 text-gray-600 whitespace-nowrap">
                      <div>{formatDate(email.received_at)}</div>
                      <div className="text-xs text-gray-400">{ACCOUNT_LABELS[email.account] ?? email.account}</div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="text-gray-900 text-xs truncate max-w-[180px]">{email.sender_email}</div>
                    </td>
                    <td className="px-4 py-3 text-gray-900 max-w-xs">
                      <div className="truncate">{email.subject}</div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {email.llm_verdict === 'important' ? (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-red-50 text-red-700 text-xs font-medium">
                          <CheckCircle className="h-3 w-3" />重要
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-gray-100 text-gray-500 text-xs">
                          <XCircle className="h-3 w-3" />通常
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-2">
                        {email.feedback ? (
                          <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                            email.feedback === 'important'    ? 'bg-green-50 text-green-700' :
                            email.feedback === 'not_important'? 'bg-gray-100 text-gray-600' :
                            email.feedback === 'never_notify' ? 'bg-orange-50 text-orange-700' :
                            'bg-blue-50 text-blue-700'
                          }`}>
                            {FEEDBACK_LABELS[email.feedback] ?? email.feedback}
                          </span>
                        ) : email.llm_verdict === 'important' ? (
                          <span className="inline-flex items-center gap-1 text-amber-500 text-xs">
                            <Clock className="h-3 w-3" />未回答
                          </span>
                        ) : (
                          <span className="text-gray-400 text-xs">—</span>
                        )}
                        <button
                          onClick={() => openFeedbackModal(email)}
                          className="inline-flex items-center gap-1 text-gray-400 hover:text-blue-600 text-xs transition-colors"
                          title="フィードバックを設定"
                        >
                          <MessageSquare className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="px-4 py-3 text-xs text-gray-400 border-t border-gray-100">
              最新100件を表示
            </div>
          </div>
        )}
      </div>

      {/* フィードバックモーダル */}
      {feedbackModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={closeFeedbackModal}>
          <div className="bg-white rounded-xl shadow-xl p-6 w-80 mx-4" onClick={(e) => e.stopPropagation()}>
            <h3 className="font-semibold text-gray-900 mb-1">フィードバック</h3>
            <p className="text-xs text-gray-500 mb-1 truncate">{feedbackModal.sender_email}</p>
            <p className="text-xs text-gray-700 mb-4 truncate">{feedbackModal.subject}</p>

            <div className="space-y-2 mb-3">
              {FEEDBACK_OPTIONS.map(opt => (
                <button
                  key={opt.value}
                  onClick={() => setPendingFeedback(opt.value)}
                  className={`w-full text-left px-3 py-2 rounded-lg text-sm border transition-colors ${
                    pendingFeedback === opt.value
                      ? opt.color + ' font-medium'
                      : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>

            {needsScope && (
              <div className="mb-4 p-3 bg-gray-50 rounded-lg text-sm">
                <p className="text-xs text-gray-500 mb-2">適用範囲:</p>
                <div className="flex gap-4">
                  <label className="flex items-center gap-1.5 cursor-pointer text-gray-700">
                    <input
                      type="radio"
                      value="address"
                      checked={pendingScope === 'address'}
                      onChange={() => setPendingScope('address')}
                    />
                    このアドレス
                  </label>
                  <label className="flex items-center gap-1.5 cursor-pointer text-gray-700">
                    <input
                      type="radio"
                      value="domain"
                      checked={pendingScope === 'domain'}
                      onChange={() => setPendingScope('domain')}
                    />
                    このドメイン
                  </label>
                </div>
              </div>
            )}

            <div className="flex gap-2">
              <button
                onClick={closeFeedbackModal}
                className="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700"
              >
                キャンセル
              </button>
              <button
                onClick={submitFeedback}
                disabled={!pendingFeedback || submitting}
                className="flex-1 px-3 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {submitting ? '送信中...' : '確定'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

