'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';

type FeedbackValue = 'important' | 'not_important' | 'never_notify' | 'always_notify';

interface MailEmailFeedback {
  id: number;
  sender_email: string;
  sender_domain: string;
  subject: string;
  body_preview: string;
  received_at: string;
  feedback: FeedbackValue | null;
}

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

// スコープ選択が必要なフィードバック
const NEEDS_SCOPE: FeedbackValue[] = ['never_notify', 'always_notify'];

export default function FeedbackPage() {
  const params = useParams();
  const token = params.token as string;

  const [email, setEmail] = useState<MailEmailFeedback | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [selected, setSelected] = useState<FeedbackValue | null>(null);
  const [showScopeChoice, setShowScopeChoice] = useState(false);
  const [scope, setScope] = useState<'address' | 'domain'>('address');
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    const fetchEmail = async () => {
      try {
        const res = await fetch(`${API_URL}/api/mail/feedback/${token}/`);
        if (!res.ok) {
          setError(res.status === 404 ? 'このフィードバックリンクは無効です' : 'メール情報の取得に失敗しました');
          return;
        }
        const data = await res.json();
        setEmail(data);
        if (data.feedback) {
          setSelected(data.feedback);
          if (NEEDS_SCOPE.includes(data.feedback)) {
            setShowScopeChoice(true);
          }
        }
      } catch {
        setError('サーバーに接続できませんでした');
      } finally {
        setLoading(false);
      }
    };
    fetchEmail();
  }, [token]);

  const handleSelect = (value: FeedbackValue) => {
    setSelected(value);
    setShowScopeChoice(NEEDS_SCOPE.includes(value));
    setSubmitted(false);
    setError(null);
    if (!NEEDS_SCOPE.includes(value)) {
      submitFeedback(value, undefined);
    }
  };

  const submitFeedback = async (feedback: FeedbackValue, feedbackScope: 'address' | 'domain' | undefined) => {
    setSubmitting(true);
    try {
      const body: Record<string, string> = { feedback };
      if (feedbackScope) body.scope = feedbackScope;

      const res = await fetch(`${API_URL}/api/mail/feedback/${token}/`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error();
      setSubmitted(true);
      setShowScopeChoice(false);
      setEmail((prev) => (prev ? { ...prev, feedback } : prev));
    } catch {
      setError('送信に失敗しました。もう一度お試しください。');
    } finally {
      setSubmitting(false);
    }
  };

  const handleScopeConfirm = () => {
    if (selected && NEEDS_SCOPE.includes(selected)) {
      submitFeedback(selected, scope);
    }
  };

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <p className="text-gray-500">読み込み中...</p>
      </div>
    );
  }

  if (error && !email) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-lg shadow p-6 max-w-md w-full text-center">
          <p className="text-red-600">{error}</p>
        </div>
      </div>
    );
  }

  if (!email) return null;

  const feedbackLabel: Record<FeedbackValue, string> = {
    important: '✅ 重要だった',
    not_important: '📧 普通のメール',
    never_notify: '🔇 今後通知しない',
    always_notify: '🔔 常に通知してほしい',
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-start justify-center p-4 pt-8">
      <div className="bg-white rounded-lg shadow-lg w-full max-w-lg">

        {/* ヘッダー */}
        <div className="px-6 py-4 border-b border-gray-200">
          <h1 className="text-lg font-bold text-green-700">KeinaSystem</h1>
          <p className="text-xs text-gray-500 mt-0.5">メール通知フィードバック</p>
        </div>

        {/* メール情報 */}
        <div className="px-6 py-4 space-y-2 border-b border-gray-200">
          <div className="flex gap-2 text-sm">
            <span className="text-gray-500 w-14 shrink-0">送信者</span>
            <span className="text-gray-800 font-medium break-all">{email.sender_email}</span>
          </div>
          <div className="flex gap-2 text-sm">
            <span className="text-gray-500 w-14 shrink-0">件名</span>
            <span className="text-gray-800 font-medium break-all">{email.subject}</span>
          </div>
          <div className="flex gap-2 text-sm">
            <span className="text-gray-500 w-14 shrink-0">受信</span>
            <span className="text-gray-600">{formatDate(email.received_at)}</span>
          </div>
          {email.body_preview && (
            <div className="mt-3 p-3 bg-gray-50 rounded text-xs text-gray-600 whitespace-pre-wrap leading-relaxed">
              {email.body_preview}
            </div>
          )}
        </div>

        {/* フィードバック操作 */}
        <div className="px-6 py-4">
          {submitted && (
            <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded text-sm text-green-700 text-center">
              受け付けました
            </div>
          )}

          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-sm text-red-600">
              {error}
            </div>
          )}

          {/* 現在のフィードバック表示 */}
          {email.feedback && !submitted && (
            <p className="text-xs text-gray-400 mb-3">
              現在の評価: {feedbackLabel[email.feedback]}　（変更できます）
            </p>
          )}

          <div className="space-y-2">
            {/* 重要だった */}
            <button
              onClick={() => handleSelect('important')}
              disabled={submitting}
              className={`w-full text-left px-4 py-3 rounded-lg border text-sm font-medium transition-colors disabled:opacity-50 ${
                selected === 'important'
                  ? 'bg-green-50 border-green-400 text-green-700'
                  : 'border-gray-200 text-gray-700 hover:bg-gray-50'
              }`}
            >
              ✅ 重要だった
            </button>

            {/* 普通のメール */}
            <button
              onClick={() => handleSelect('not_important')}
              disabled={submitting}
              className={`w-full text-left px-4 py-3 rounded-lg border text-sm font-medium transition-colors disabled:opacity-50 ${
                selected === 'not_important'
                  ? 'bg-blue-50 border-blue-400 text-blue-700'
                  : 'border-gray-200 text-gray-700 hover:bg-gray-50'
              }`}
            >
              📧 普通のメール（通知不要）
            </button>

            {/* 常に通知してほしい */}
            <button
              onClick={() => handleSelect('always_notify')}
              disabled={submitting}
              className={`w-full text-left px-4 py-3 rounded-lg border text-sm font-medium transition-colors disabled:opacity-50 ${
                selected === 'always_notify'
                  ? 'bg-teal-50 border-teal-400 text-teal-700'
                  : 'border-gray-200 text-gray-700 hover:bg-gray-50'
              }`}
            >
              🔔 常に通知してほしい
              <span className="ml-2 text-xs font-normal text-gray-400">（LLMをスキップして即通知）</span>
            </button>

            {/* 今後通知しない */}
            <button
              onClick={() => handleSelect('never_notify')}
              disabled={submitting}
              className={`w-full text-left px-4 py-3 rounded-lg border text-sm font-medium transition-colors disabled:opacity-50 ${
                selected === 'never_notify'
                  ? 'bg-orange-50 border-orange-400 text-orange-700'
                  : 'border-gray-200 text-gray-700 hover:bg-gray-50'
              }`}
            >
              🔇 今後通知しない
            </button>

            {/* スコープ選択（常に通知 / 今後通知しない で展開） */}
            {showScopeChoice && selected && NEEDS_SCOPE.includes(selected) && (
              <div className={`ml-4 mt-1 p-4 border rounded-lg space-y-3 ${
                selected === 'always_notify'
                  ? 'bg-teal-50 border-teal-200'
                  : 'bg-orange-50 border-orange-200'
              }`}>
                <p className={`text-xs font-medium ${
                  selected === 'always_notify' ? 'text-teal-700' : 'text-orange-700'
                }`}>
                  {selected === 'always_notify' ? '常に通知する範囲を選んでください' : '通知をやめる範囲を選んでください'}
                </p>
                <label className="flex items-start gap-3 cursor-pointer">
                  <input
                    type="radio"
                    name="scope"
                    value="address"
                    checked={scope === 'address'}
                    onChange={() => setScope('address')}
                    className="mt-0.5"
                  />
                  <div>
                    <p className="text-sm text-gray-800 font-medium">このアドレスだけ</p>
                    <p className="text-xs text-gray-500">{email.sender_email}</p>
                  </div>
                </label>
                <label className="flex items-start gap-3 cursor-pointer">
                  <input
                    type="radio"
                    name="scope"
                    value="domain"
                    checked={scope === 'domain'}
                    onChange={() => setScope('domain')}
                    className="mt-0.5"
                  />
                  <div>
                    <p className="text-sm text-gray-800 font-medium">このドメインごと</p>
                    <p className="text-xs text-gray-500">{email.sender_domain}</p>
                  </div>
                </label>
                <button
                  onClick={handleScopeConfirm}
                  disabled={submitting}
                  className={`w-full py-2 text-white text-sm font-medium rounded-lg disabled:opacity-50 transition-colors ${
                    selected === 'always_notify'
                      ? 'bg-teal-500 hover:bg-teal-600'
                      : 'bg-orange-500 hover:bg-orange-600'
                  }`}
                >
                  {submitting ? '送信中...' : '確定する'}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
