import React, { useState } from 'react';
import { X, Send, CheckCircle, AlertTriangle } from './Icons';

interface TelegramSettingsProps {
  onClose: () => void;
}

const TelegramSettings: React.FC<TelegramSettingsProps> = ({ onClose }) => {
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);

  const handleTestConnection = async () => {
    setTesting(true);
    setTestResult(null);

    try {
      const response = await fetch('/api/telegram/test', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();
      setTestResult(result);
    } catch (error) {
      setTestResult({
        success: false,
        message: 'Failed to test connection: ' + (error instanceof Error ? error.message : 'Unknown error')
      });
    } finally {
      setTesting(false);
    }
  };

  const handleSendTestReminder = async () => {
    setTesting(true);

    try {
      const response = await fetch('/api/telegram/check-reminders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();
      setTestResult(result);
    } catch (error) {
      setTestResult({
        success: false,
        message: 'Failed to send reminder: ' + (error instanceof Error ? error.message : 'Unknown error')
      });
    } finally {
      setTesting(false);
    }
  };

  const handleSendWeeklyReport = async () => {
    setTesting(true);

    try {
      const response = await fetch('/api/telegram/weekly-report', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();
      setTestResult(result);
    } catch (error) {
      setTestResult({
        success: false,
        message: 'Failed to send report: ' + (error instanceof Error ? error.message : 'Unknown error')
      });
    } finally {
      setTesting(false);
    }
  };

  return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
        <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <div className="flex items-center justify-between p-6 border-b">
            <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
              <Send className="h-6 w-6 text-blue-600" />
              Telegram Notifications
            </h2>
            <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 transition-colors duration-200"
            >
              <X className="h-6 w-6" />
            </button>
          </div>

          <div className="p-6 space-y-6">
            {/* Setup Instructions */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <h3 className="text-lg font-medium text-blue-900 mb-3">Setup Instructions</h3>
              <ol className="list-decimal list-inside space-y-2 text-sm text-blue-800">
                <li>Create a new bot by messaging <code className="bg-blue-100 px-1 rounded">@BotFather</code> on Telegram</li>
                <li>Send <code className="bg-blue-100 px-1 rounded">/newbot</code> and follow the instructions</li>
                <li>Copy the bot token and add it to your <code className="bg-blue-100 px-1 rounded">.env</code> file as <code className="bg-blue-100 px-1 rounded">TELEGRAM_BOT_TOKEN</code></li>
                <li>Start a chat with your bot and send any message</li>
                <li>Visit <code className="bg-blue-100 px-1 rounded text-xs">https://api.telegram.org/bot&lt;YOUR_BOT_TOKEN&gt;/getUpdates</code> to get your chat ID</li>
                <li>Add the chat ID to your <code className="bg-blue-100 px-1 rounded">.env</code> file as <code className="bg-blue-100 px-1 rounded">TELEGRAM_CHAT_ID</code></li>
                <li>Restart the server to apply the changes</li>
              </ol>
            </div>

            {/* Notification Schedule */}
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <h3 className="text-lg font-medium text-gray-900 mb-3">Notification Schedule</h3>
              <div className="space-y-2 text-sm text-gray-700">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-orange-500 rounded-full"></div>
                  <span><strong>Daily Reminders:</strong> 8:00 AM - Zones that are due or overdue</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                  <span><strong>Weekly Report:</strong> Sunday 9:00 AM - Complete lawn status summary</span>
                </div>
              </div>
            </div>

            {/* Test Buttons */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">Test Notifications</h3>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <button
                    onClick={handleTestConnection}
                    disabled={testing}
                    className="flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                >
                  <Send className="h-4 w-4" />
                  {testing ? 'Testing...' : 'Test Connection'}
                </button>

                <button
                    onClick={handleSendTestReminder}
                    disabled={testing}
                    className="flex items-center justify-center gap-2 px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                >
                  <AlertTriangle className="h-4 w-4" />
                  {testing ? 'Sending...' : 'Send Reminder'}
                </button>

                <button
                    onClick={handleSendWeeklyReport}
                    disabled={testing}
                    className="flex items-center justify-center gap-2 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                >
                  <CheckCircle className="h-4 w-4" />
                  {testing ? 'Sending...' : 'Send Report'}
                </button>
              </div>
            </div>

            {/* Test Result */}
            {testResult && (
                <div className={`p-4 rounded-lg border ${
                    testResult.success
                        ? 'bg-green-50 border-green-200 text-green-800'
                        : 'bg-red-50 border-red-200 text-red-800'
                }`}>
                  <div className="flex items-center gap-2">
                    {testResult.success ? (
                        <CheckCircle className="h-5 w-5 text-green-600" />
                    ) : (
                        <AlertTriangle className="h-5 w-5 text-red-600" />
                    )}
                    <span className="font-medium">
                  {testResult.success ? 'Success!' : 'Error'}
                </span>
                  </div>
                  <p className="mt-1 text-sm">{testResult.message}</p>
                </div>
            )}

            {/* Example Messages */}
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <h3 className="text-lg font-medium text-gray-900 mb-3">Example Messages</h3>

              <div className="space-y-4">
                <div>
                  <h4 className="font-medium text-gray-800 mb-2">Daily Reminder:</h4>
                  <div className="bg-white border rounded p-3 text-sm font-mono">
                    🌱 <strong>Lawn Mowing Reminder</strong><br/><br/>
                    🚨 <strong>OVERDUE ZONES:</strong><br/>
                    • Front Yard - 2 days overdue<br/><br/>
                    ⏰ <strong>DUE TODAY:</strong><br/>
                    • Back Garden<br/><br/>
                    Total zones needing attention: 2
                  </div>
                </div>

                <div>
                  <h4 className="font-medium text-gray-800 mb-2">Weekly Report:</h4>
                  <div className="bg-white border rounded p-3 text-sm font-mono">
                    📊 <strong>Weekly Lawn Care Report</strong><br/>
                    📅 Sunday, January 21, 2024<br/><br/>
                    🏡 <strong>ZONE STATUS:</strong><br/>
                    ✅ Up to date: 2 zones<br/>
                    🆕 New zones: 0 zones<br/>
                    ⏰ Due today: 1 zones<br/>
                    🚨 Overdue: 0 zones<br/>
                    📐 Total area: 580 sq ft<br/>
                    🌱 Mowed area: 85.2%<br/><br/>
                    📈 <strong>THIS WEEK'S ACTIVITY:</strong><br/>
                    🔄 Mowing sessions: 3<br/>
                    ⏱️ Total time: 2h 15m<br/>
                    📐 Area mowed: 1,160 sq ft<br/>
                    🎯 Zones maintained: 3
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="flex justify-end p-6 border-t">
            <button
                onClick={onClose}
                className="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors duration-200"
            >
              Close
            </button>
          </div>
        </div>
      </div>
  );
};

export default TelegramSettings;