/**
 * Ticket Email Address Modal Component
 * Modal for adding/editing ticket email addresses
 */

import React, { useState, useEffect } from 'react';
import { X, Loader2, ChevronDown, ChevronUp, Save, TestTube } from 'lucide-react';
import {
  useCreateTicketEmailAddress,
  useUpdateTicketEmailAddress,
  useTicketEmailAddress,
  useTestImapConnection,
  useTestSmtpConnection,
  TicketEmailAddressListItem,
  TicketEmailAddressCreate,
} from '../hooks/useTicketEmailAddresses';
import toast from 'react-hot-toast';

interface Props {
  address?: TicketEmailAddressListItem | null;
  onClose: () => void;
}

const COLOR_PRESETS = [
  '#3b82f6', // blue
  '#10b981', // green
  '#f59e0b', // amber
  '#ef4444', // red
  '#8b5cf6', // purple
  '#ec4899', // pink
  '#06b6d4', // cyan
  '#f97316', // orange
  '#14b8a6', // teal
  '#6366f1', // indigo
];

const TicketEmailAddressModal: React.FC<Props> = ({ address, onClose }) => {
  const [formData, setFormData] = useState<TicketEmailAddressCreate>({
    display_name: '',
    email_address: '',
    color: '#3b82f6',
    imap_host: '',
    imap_port: 993,
    imap_use_ssl: true,
    imap_username: '',
    imap_password: '',
    imap_folder: 'INBOX',
    smtp_host: '',
    smtp_port: 587,
    smtp_use_tls: true,
    smtp_use_ssl: false,
    smtp_username: '',
    smtp_password: '',
    is_active: true,
    is_default: false,
  });

  const [showImapSection, setShowImapSection] = useState(true);
  const [showSmtpSection, setShowSmtpSection] = useState(true);

  const createAddress = useCreateTicketEmailAddress();
  const updateAddress = useUpdateTicketEmailAddress();
  const { data: fullAddress, isLoading: isLoadingAddress } = useTicketEmailAddress(address?.id || 0);
  const testImap = useTestImapConnection();
  const testSmtp = useTestSmtpConnection();

  const isEditing = !!address;

  // Load full address details when editing
  useEffect(() => {
    if (fullAddress && isEditing) {
      setFormData({
        display_name: fullAddress.display_name,
        email_address: fullAddress.email_address,
        color: fullAddress.color,
        imap_host: fullAddress.imap_host,
        imap_port: fullAddress.imap_port,
        imap_use_ssl: fullAddress.imap_use_ssl,
        imap_username: fullAddress.imap_username,
        imap_password: '', // Don't pre-fill password for security
        imap_folder: fullAddress.imap_folder,
        smtp_host: fullAddress.smtp_host,
        smtp_port: fullAddress.smtp_port,
        smtp_use_tls: fullAddress.smtp_use_tls,
        smtp_use_ssl: fullAddress.smtp_use_ssl,
        smtp_username: fullAddress.smtp_username,
        smtp_password: '', // Don't pre-fill password for security
        is_active: fullAddress.is_active,
        is_default: fullAddress.is_default,
      });
    }
  }, [fullAddress, isEditing]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      if (isEditing && address) {
        // For updates, only send changed fields
        const updateData: Partial<TicketEmailAddressCreate> = { ...formData };
        // Remove passwords if they're empty (not changed)
        if (!updateData.imap_password) delete updateData.imap_password;
        if (!updateData.smtp_password) delete updateData.smtp_password;

        await updateAddress.mutateAsync({ id: address.id, data: updateData });
        toast.success(`${formData.display_name} updated successfully`);
      } else {
        await createAddress.mutateAsync(formData);
        toast.success(`${formData.display_name} added successfully`);
      }
      onClose();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to save email address');
    }
  };

  const handleTestImap = async () => {
    if (!address) {
      toast.error('Please save the email address first before testing');
      return;
    }

    toast.loading('Testing IMAP connection...', { id: 'test-imap' });
    try {
      const result = await testImap.mutateAsync(address.id);
      if (result.success) {
        toast.success(result.message, { id: 'test-imap' });
      } else {
        toast.error(result.message, { id: 'test-imap' });
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'IMAP test failed', { id: 'test-imap' });
    }
  };

  const handleTestSmtp = async () => {
    if (!address) {
      toast.error('Please save the email address first before testing');
      return;
    }

    toast.loading('Testing SMTP connection...', { id: 'test-smtp' });
    try {
      const result = await testSmtp.mutateAsync(address.id);
      if (result.success) {
        toast.success(result.message, { id: 'test-smtp' });
      } else {
        toast.error(result.message, { id: 'test-smtp' });
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'SMTP test failed', { id: 'test-smtp' });
    }
  };

  if (isEditing && isLoadingAddress) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-white dark:bg-gray-800 rounded-lg p-8">
          <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="bg-white dark:bg-gray-800 rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-between">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {isEditing ? 'Edit Email Address' : 'Add Email Address'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Basic Info */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Basic Information</h3>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Display Name
              </label>
              <input
                type="text"
                value={formData.display_name}
                onChange={(e) => setFormData({ ...formData, display_name: e.target.value })}
                placeholder="e.g., Support, Billing, Sales"
                required
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Email Address
              </label>
              <input
                type="email"
                value={formData.email_address}
                onChange={(e) => setFormData({ ...formData, email_address: e.target.value })}
                placeholder="support@yourcompany.com"
                required
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Color Tag
              </label>
              <div className="flex items-center gap-2">
                {COLOR_PRESETS.map((color) => (
                  <button
                    key={color}
                    type="button"
                    onClick={() => setFormData({ ...formData, color })}
                    className={`w-8 h-8 rounded-full border-2 transition-all ${
                      formData.color === color
                        ? 'border-gray-900 dark:border-white scale-110'
                        : 'border-transparent'
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
                <input
                  type="color"
                  value={formData.color}
                  onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                  className="w-8 h-8 rounded cursor-pointer"
                />
              </div>
            </div>

            <div className="flex items-center gap-4">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.is_active}
                  onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Active</span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.is_default}
                  onChange={(e) => setFormData({ ...formData, is_default: e.target.checked })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Set as Default</span>
              </label>
            </div>
          </div>

          {/* IMAP Settings */}
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg">
            <button
              type="button"
              onClick={() => setShowImapSection(!showImapSection)}
              className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
            >
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                IMAP Settings (Inbound)
              </h3>
              {showImapSection ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
            </button>

            {showImapSection && (
              <div className="px-4 pb-4 space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Host
                    </label>
                    <input
                      type="text"
                      value={formData.imap_host}
                      onChange={(e) => setFormData({ ...formData, imap_host: e.target.value })}
                      placeholder="imap.gmail.com"
                      required
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Port
                    </label>
                    <input
                      type="number"
                      value={formData.imap_port}
                      onChange={(e) => setFormData({ ...formData, imap_port: parseInt(e.target.value) })}
                      required
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Username
                  </label>
                  <input
                    type="text"
                    value={formData.imap_username}
                    onChange={(e) => setFormData({ ...formData, imap_username: e.target.value })}
                    placeholder="your@email.com"
                    required
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Password {isEditing && <span className="text-xs text-gray-500">(leave blank to keep current)</span>}
                  </label>
                  <input
                    type="password"
                    value={formData.imap_password}
                    onChange={(e) => setFormData({ ...formData, imap_password: e.target.value })}
                    placeholder={isEditing ? "••••••••" : "password"}
                    required={!isEditing}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Folder
                  </label>
                  <input
                    type="text"
                    value={formData.imap_folder}
                    onChange={(e) => setFormData({ ...formData, imap_folder: e.target.value })}
                    placeholder="INBOX"
                    required
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>

                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.imap_use_ssl}
                    onChange={(e) => setFormData({ ...formData, imap_use_ssl: e.target.checked })}
                    className="rounded border-gray-300 dark:border-gray-600"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Use SSL/TLS</span>
                </label>

                {isEditing && (
                  <button
                    type="button"
                    onClick={handleTestImap}
                    disabled={testImap.isPending}
                    className="flex items-center gap-2 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
                  >
                    <TestTube className="w-4 h-4" />
                    Test IMAP
                  </button>
                )}
              </div>
            )}
          </div>

          {/* SMTP Settings */}
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg">
            <button
              type="button"
              onClick={() => setShowSmtpSection(!showSmtpSection)}
              className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
            >
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                SMTP Settings (Outbound)
              </h3>
              {showSmtpSection ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
            </button>

            {showSmtpSection && (
              <div className="px-4 pb-4 space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Host
                    </label>
                    <input
                      type="text"
                      value={formData.smtp_host}
                      onChange={(e) => setFormData({ ...formData, smtp_host: e.target.value })}
                      placeholder="smtp.gmail.com"
                      required
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Port
                    </label>
                    <input
                      type="number"
                      value={formData.smtp_port}
                      onChange={(e) => setFormData({ ...formData, smtp_port: parseInt(e.target.value) })}
                      required
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Username
                  </label>
                  <input
                    type="text"
                    value={formData.smtp_username}
                    onChange={(e) => setFormData({ ...formData, smtp_username: e.target.value })}
                    placeholder="your@email.com"
                    required
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Password {isEditing && <span className="text-xs text-gray-500">(leave blank to keep current)</span>}
                  </label>
                  <input
                    type="password"
                    value={formData.smtp_password}
                    onChange={(e) => setFormData({ ...formData, smtp_password: e.target.value })}
                    placeholder={isEditing ? "••••••••" : "password"}
                    required={!isEditing}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>

                <div className="space-y-2">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.smtp_use_tls}
                      onChange={(e) => setFormData({ ...formData, smtp_use_tls: e.target.checked })}
                      className="rounded border-gray-300 dark:border-gray-600"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Use STARTTLS (Port 587)</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.smtp_use_ssl}
                      onChange={(e) => setFormData({ ...formData, smtp_use_ssl: e.target.checked })}
                      className="rounded border-gray-300 dark:border-gray-600"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Use SSL/TLS (Port 465)</span>
                  </label>
                </div>

                {isEditing && (
                  <button
                    type="button"
                    onClick={handleTestSmtp}
                    disabled={testSmtp.isPending}
                    className="flex items-center gap-2 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
                  >
                    <TestTube className="w-4 h-4" />
                    Test SMTP
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={createAddress.isPending || updateAddress.isPending}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
            >
              {(createAddress.isPending || updateAddress.isPending) && (
                <Loader2 className="w-4 h-4 animate-spin" />
              )}
              <Save className="w-4 h-4" />
              {isEditing ? 'Update' : 'Add'} Email Address
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default TicketEmailAddressModal;
