'use client';

import { useState, useEffect } from 'react';
import {
  Mail,
  MessageSquare,
  Settings,
  Save,
  TestTube,
  CheckCircle,
  XCircle,
  Eye,
  EyeOff,
  RefreshCw,
  ArrowLeft,
} from 'lucide-react';
import Link from 'next/link';
import ProtectedRoute from '../../protected-route';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '../../hooks/useTranslations';

interface NotificationProviders {
  email: {
    provider: 'sendgrid' | 'smtp';
    enabled: boolean;
    sendgrid?: {
      apiKey: string;
      fromEmail: string;
      fromName: string;
    };
    smtp?: {
      host: string;
      port: number;
      secure: boolean;
      username: string;
      password: string;
      fromEmail: string;
      fromName: string;
    };
  };
  sms: {
    provider: 'twilio';
    enabled: boolean;
    twilio?: {
      accountSid: string;
      authToken: string;
      phoneNumber: string;
    };
  };
}

interface FormData {
  emailNotifications: boolean;
  smsNotifications: boolean;
  appointmentReminders: boolean;
  reminderTime: number;
  notificationProviders: NotificationProviders;
}

export default function NotificationSettingsPage() {
  const { t, translationsLoaded } = useTranslations();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testingEmail, setTestingEmail] = useState(false);
  const [testingSMS, setTestingSMS] = useState(false);
  const [testEmailAddress, setTestEmailAddress] = useState('');
  const [testPhoneNumber, setTestPhoneNumber] = useState('');
  const [showApiKey, setShowApiKey] = useState(false);
  const [showAuthToken, setShowAuthToken] = useState(false);
  const [showSmtpPassword, setShowSmtpPassword] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const [formData, setFormData] = useState<FormData>({
    emailNotifications: true,
    smsNotifications: false,
    appointmentReminders: true,
    reminderTime: 30,
    notificationProviders: {
      email: {
        provider: 'sendgrid',
        enabled: false,
        sendgrid: {
          apiKey: '',
          fromEmail: '',
          fromName: '',
        },
        smtp: {
          host: '',
          port: 587,
          secure: false,
          username: '',
          password: '',
          fromEmail: '',
          fromName: '',
        },
      },
      sms: {
        provider: 'twilio',
        enabled: false,
        twilio: {
          accountSid: '',
          authToken: '',
          phoneNumber: '',
        },
      },
    },
  });

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

  const fetchSettings = async () => {
    try {
      const response = await fetch('/api/settings');
      if (response.ok) {
        const data = await response.json();
        setFormData({
          emailNotifications: data.emailNotifications ?? true,
          smsNotifications: data.smsNotifications ?? false,
          appointmentReminders: data.appointmentReminders ?? true,
          reminderTime: data.reminderTime ?? 30,
          notificationProviders: data.notificationProviders || formData.notificationProviders,
        });
      }
    } catch (error) {
      console.error('Error fetching settings:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      setMessage(null);

      const response = await fetch('/api/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        setMessage({ type: 'success', text: 'Settings saved successfully' });
      } else {
        const error = await response.json();
        setMessage({ type: 'error', text: error.error || 'Failed to save settings' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to save settings' });
    } finally {
      setSaving(false);
    }
  };

  const testEmailConnection = async () => {
    try {
      setTestingEmail(true);
      setMessage(null);

      const response = await fetch('/api/notifications/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'email',
          testEmail: testEmailAddress || undefined,
        }),
      });

      const result = await response.json();
      
      if (result.success) {
        setMessage({ 
          type: 'success', 
          text: testEmailAddress ? 'Test email sent successfully!' : 'Email connection verified!' 
        });
      } else {
        setMessage({ type: 'error', text: result.error || 'Email test failed' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to test email connection' });
    } finally {
      setTestingEmail(false);
    }
  };

  const testSMSConnection = async () => {
    try {
      setTestingSMS(true);
      setMessage(null);

      const response = await fetch('/api/notifications/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'sms',
          testPhone: testPhoneNumber || undefined,
        }),
      });

      const result = await response.json();
      
      if (result.success) {
        setMessage({ 
          type: 'success', 
          text: testPhoneNumber ? 'Test SMS sent successfully!' : 'SMS connection verified!' 
        });
      } else {
        setMessage({ type: 'error', text: result.error || 'SMS test failed' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to test SMS connection' });
    } finally {
      setTestingSMS(false);
    }
  };

  const updateEmailProvider = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      notificationProviders: {
        ...prev.notificationProviders,
        email: {
          ...prev.notificationProviders.email,
          [field]: value,
        },
      },
    }));
  };

  const updateSendgrid = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      notificationProviders: {
        ...prev.notificationProviders,
        email: {
          ...prev.notificationProviders.email,
          sendgrid: {
            ...prev.notificationProviders.email.sendgrid!,
            [field]: value,
          },
        },
      },
    }));
  };

  const updateSmtp = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      notificationProviders: {
        ...prev.notificationProviders,
        email: {
          ...prev.notificationProviders.email,
          smtp: {
            ...prev.notificationProviders.email.smtp!,
            [field]: value,
          },
        },
      },
    }));
  };

  const updateTwilio = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      notificationProviders: {
        ...prev.notificationProviders,
        sms: {
          ...prev.notificationProviders.sms,
          twilio: {
            ...prev.notificationProviders.sms.twilio!,
            [field]: value,
          },
        },
      },
    }));
  };

  const updateSmsProvider = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      notificationProviders: {
        ...prev.notificationProviders,
        sms: {
          ...prev.notificationProviders.sms,
          [field]: value,
        },
      },
    }));
  };

  if (!translationsLoaded || loading) {
    return (
      <ProtectedRoute requiredRoles={['admin']}>
        <SidebarLayout title="Notification Settings" description="Configure email and SMS providers">
          <div className="flex items-center justify-center h-64">
            <RefreshCw className="h-8 w-8 animate-spin text-gray-400" />
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute requiredRoles={['admin']}>
      <SidebarLayout title="Notification Settings" description="Configure email and SMS notification providers">
        <div className="space-y-6">
          {/* Back Link */}
          <Link 
            href="/settings" 
            className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to General Settings
          </Link>

          {/* Message */}
          {message && (
            <div className={`p-4 rounded-lg flex items-center gap-2 ${
              message.type === 'success' 
                ? 'bg-green-50 text-green-800 border border-green-200' 
                : 'bg-red-50 text-red-800 border border-red-200'
            }`}>
              {message.type === 'success' ? (
                <CheckCircle className="h-5 w-5" />
              ) : (
                <XCircle className="h-5 w-5" />
              )}
              {message.text}
            </div>
          )}

          {/* General Notification Settings */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Settings className="h-5 w-5" />
              General Settings
            </h2>
            <div className="space-y-4">
              <label className="flex items-center justify-between">
                <span className="text-gray-700">Enable Email Notifications</span>
                <input
                  type="checkbox"
                  checked={formData.emailNotifications}
                  onChange={(e) => setFormData({ ...formData, emailNotifications: e.target.checked })}
                  className="h-5 w-5 text-blue-600 rounded"
                />
              </label>
              <label className="flex items-center justify-between">
                <span className="text-gray-700">Enable SMS Notifications</span>
                <input
                  type="checkbox"
                  checked={formData.smsNotifications}
                  onChange={(e) => setFormData({ ...formData, smsNotifications: e.target.checked })}
                  className="h-5 w-5 text-blue-600 rounded"
                />
              </label>
              <label className="flex items-center justify-between">
                <span className="text-gray-700">Enable Appointment Reminders</span>
                <input
                  type="checkbox"
                  checked={formData.appointmentReminders}
                  onChange={(e) => setFormData({ ...formData, appointmentReminders: e.target.checked })}
                  className="h-5 w-5 text-blue-600 rounded"
                />
              </label>
              <div className="flex items-center justify-between">
                <span className="text-gray-700">Reminder Time (minutes before)</span>
                <input
                  type="number"
                  min="5"
                  max="1440"
                  value={formData.reminderTime}
                  onChange={(e) => setFormData({ ...formData, reminderTime: parseInt(e.target.value) || 30 })}
                  className="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          </div>

          {/* Email Provider Settings */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Mail className="h-5 w-5" />
              Email Provider
            </h2>

            <div className="space-y-4">
              <label className="flex items-center justify-between">
                <span className="text-gray-700">Enable Email Provider</span>
                <input
                  type="checkbox"
                  checked={formData.notificationProviders.email.enabled}
                  onChange={(e) => updateEmailProvider('enabled', e.target.checked)}
                  className="h-5 w-5 text-blue-600 rounded"
                />
              </label>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Provider</label>
                <select
                  value={formData.notificationProviders.email.provider}
                  onChange={(e) => updateEmailProvider('provider', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                >
                  <option value="sendgrid">SendGrid</option>
                  <option value="smtp">SMTP</option>
                </select>
              </div>

              {formData.notificationProviders.email.provider === 'sendgrid' && (
                <div className="space-y-4 pt-4 border-t border-gray-200">
                  <h3 className="font-medium text-gray-900">SendGrid Configuration</h3>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                    <div className="relative">
                      <input
                        type={showApiKey ? 'text' : 'password'}
                        value={formData.notificationProviders.email.sendgrid?.apiKey || ''}
                        onChange={(e) => updateSendgrid('apiKey', e.target.value)}
                        placeholder="SG.xxxxxxxxxx"
                        className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => setShowApiKey(!showApiKey)}
                        className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                      >
                        {showApiKey ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                      </button>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">From Email</label>
                      <input
                        type="email"
                        value={formData.notificationProviders.email.sendgrid?.fromEmail || ''}
                        onChange={(e) => updateSendgrid('fromEmail', e.target.value)}
                        placeholder="noreply@clinic.com"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">From Name</label>
                      <input
                        type="text"
                        value={formData.notificationProviders.email.sendgrid?.fromName || ''}
                        onChange={(e) => updateSendgrid('fromName', e.target.value)}
                        placeholder="My Clinic"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  </div>
                </div>
              )}

              {formData.notificationProviders.email.provider === 'smtp' && (
                <div className="space-y-4 pt-4 border-t border-gray-200">
                  <h3 className="font-medium text-gray-900">SMTP Configuration</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Host</label>
                      <input
                        type="text"
                        value={formData.notificationProviders.email.smtp?.host || ''}
                        onChange={(e) => updateSmtp('host', e.target.value)}
                        placeholder="smtp.gmail.com"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Port</label>
                      <input
                        type="number"
                        value={formData.notificationProviders.email.smtp?.port || 587}
                        onChange={(e) => updateSmtp('port', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  </div>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.notificationProviders.email.smtp?.secure || false}
                      onChange={(e) => updateSmtp('secure', e.target.checked)}
                      className="h-4 w-4 text-blue-600 rounded"
                    />
                    <span className="text-sm text-gray-700">Use SSL/TLS</span>
                  </label>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Username</label>
                      <input
                        type="text"
                        value={formData.notificationProviders.email.smtp?.username || ''}
                        onChange={(e) => updateSmtp('username', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
                      <div className="relative">
                        <input
                          type={showSmtpPassword ? 'text' : 'password'}
                          value={formData.notificationProviders.email.smtp?.password || ''}
                          onChange={(e) => updateSmtp('password', e.target.value)}
                          className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        />
                        <button
                          type="button"
                          onClick={() => setShowSmtpPassword(!showSmtpPassword)}
                          className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                          {showSmtpPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                        </button>
                      </div>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">From Email</label>
                      <input
                        type="email"
                        value={formData.notificationProviders.email.smtp?.fromEmail || ''}
                        onChange={(e) => updateSmtp('fromEmail', e.target.value)}
                        placeholder="noreply@clinic.com"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">From Name</label>
                      <input
                        type="text"
                        value={formData.notificationProviders.email.smtp?.fromName || ''}
                        onChange={(e) => updateSmtp('fromName', e.target.value)}
                        placeholder="My Clinic"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* Test Email */}
              <div className="pt-4 border-t border-gray-200">
                <h3 className="font-medium text-gray-900 mb-3">Test Email Connection</h3>
                <div className="flex gap-2">
                  <input
                    type="email"
                    value={testEmailAddress}
                    onChange={(e) => setTestEmailAddress(e.target.value)}
                    placeholder="test@example.com (optional)"
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                  <button
                    onClick={testEmailConnection}
                    disabled={testingEmail || !formData.notificationProviders.email.enabled}
                    className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {testingEmail ? (
                      <RefreshCw className="h-4 w-4 animate-spin" />
                    ) : (
                      <TestTube className="h-4 w-4" />
                    )}
                    Test
                  </button>
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  Leave empty to just verify connection, or enter an email to send a test message
                </p>
              </div>
            </div>
          </div>

          {/* SMS Provider Settings */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <MessageSquare className="h-5 w-5" />
              SMS Provider (Twilio)
            </h2>

            <div className="space-y-4">
              <label className="flex items-center justify-between">
                <span className="text-gray-700">Enable SMS Provider</span>
                <input
                  type="checkbox"
                  checked={formData.notificationProviders.sms.enabled}
                  onChange={(e) => updateSmsProvider('enabled', e.target.checked)}
                  className="h-5 w-5 text-blue-600 rounded"
                />
              </label>

              <div className="space-y-4 pt-4 border-t border-gray-200">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Account SID</label>
                  <input
                    type="text"
                    value={formData.notificationProviders.sms.twilio?.accountSid || ''}
                    onChange={(e) => updateTwilio('accountSid', e.target.value)}
                    placeholder="ACxxxxxxxxxx"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Auth Token</label>
                  <div className="relative">
                    <input
                      type={showAuthToken ? 'text' : 'password'}
                      value={formData.notificationProviders.sms.twilio?.authToken || ''}
                      onChange={(e) => updateTwilio('authToken', e.target.value)}
                      placeholder="xxxxxxxxxx"
                      className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                    />
                    <button
                      type="button"
                      onClick={() => setShowAuthToken(!showAuthToken)}
                      className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showAuthToken ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                  <input
                    type="text"
                    value={formData.notificationProviders.sms.twilio?.phoneNumber || ''}
                    onChange={(e) => updateTwilio('phoneNumber', e.target.value)}
                    placeholder="+1234567890"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                  <p className="text-xs text-gray-500 mt-1">Your Twilio phone number in E.164 format</p>
                </div>
              </div>

              {/* Test SMS */}
              <div className="pt-4 border-t border-gray-200">
                <h3 className="font-medium text-gray-900 mb-3">Test SMS Connection</h3>
                <div className="flex gap-2">
                  <input
                    type="tel"
                    value={testPhoneNumber}
                    onChange={(e) => setTestPhoneNumber(e.target.value)}
                    placeholder="+1234567890 (optional)"
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                  <button
                    onClick={testSMSConnection}
                    disabled={testingSMS || !formData.notificationProviders.sms.enabled}
                    className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {testingSMS ? (
                      <RefreshCw className="h-4 w-4 animate-spin" />
                    ) : (
                      <TestTube className="h-4 w-4" />
                    )}
                    Test
                  </button>
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  Leave empty to just verify credentials, or enter a phone number to send a test SMS
                </p>
              </div>
            </div>
          </div>

          {/* Save Button */}
          <div className="flex justify-end">
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? (
                <RefreshCw className="h-4 w-4 animate-spin" />
              ) : (
                <Save className="h-4 w-4" />
              )}
              Save Settings
            </button>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
