import React, { useState, useEffect } from 'react';
import {
  Mail,
  MessageSquare,
  Phone,
  Send,
  Search,
  Plus,
  Eye,
  X,
  Clock,
  RefreshCw,
  FileText,
  Bell,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { formatRelativeTime } from '../../shared/utils/format';
import { logger } from '../../shared/utils/logger';
import bookingService, { Booking } from '../../features/bookings/services/bookingService';
import userService from '../../features/auth/services/userService';
import apiClient from '../../shared/services/apiClient';
import Pagination from '../../shared/components/Pagination';

interface CommunicationTemplate {
  id: number;
  name: string;
  notification_type: string;
  channel: string;
  subject?: string;
  content: string;
  is_active: boolean;
}

interface GuestCommunication {
  id: number;
  user_id: number;
  guest_name?: string;
  communication_type: string;
  direction: string;
  subject?: string;
  content: string;
  booking_id?: number;
  is_automated: boolean;
  created_at: string;
  staff_name?: string;
}

type Tab = 'send' | 'history' | 'templates';

const GuestCommunicationPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<Tab>('send');
  const [loading, setLoading] = useState(false);
  
  // Send communication state
  const [guestSearch, setGuestSearch] = useState('');
  const [guestSearchResults, setGuestSearchResults] = useState<Array<{ id: number; name: string; email?: string; phone?: string }>>([]);
  const [selectedGuest, setSelectedGuest] = useState<{ id: number; name: string; email?: string; phone?: string } | null>(null);
  const [selectedBooking, setSelectedBooking] = useState<Booking | null>(null);
  const [communicationForm, setCommunicationForm] = useState({
    communication_type: 'email',
    subject: '',
    content: '',
    booking_id: null as number | null,
  });
  const [sending, setSending] = useState(false);

  // History state
  const [communications, setCommunications] = useState<GuestCommunication[]>([]);
  const [historyPage, setHistoryPage] = useState(1);
  const [historyTotalPages, setHistoryTotalPages] = useState(1);
  const [historyFilters, setHistoryFilters] = useState({
    search: '',
    communication_type: '',
    direction: '',
  });

  // Templates state
  const [templates, setTemplates] = useState<CommunicationTemplate[]>([]);
  const [_selectedTemplate, setSelectedTemplate] = useState<CommunicationTemplate | null>(null);
  const [showTemplateModal, setShowTemplateModal] = useState(false);

  useEffect(() => {
    if (activeTab === 'history') {
      fetchCommunications();
    } else if (activeTab === 'templates') {
      fetchTemplates();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, historyPage, historyFilters]);

  useEffect(() => {
    if (guestSearch.length >= 2) {
      const timeoutId = setTimeout(() => {
        searchGuests();
      }, 300);
      return () => clearTimeout(timeoutId);
    } else {
      setGuestSearchResults([]);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [guestSearch]);

  const searchGuests = async () => {
    try {
      const response = await userService.getUsers({
        search: guestSearch,
        role: 'customer',
        limit: 10,
      });
      setGuestSearchResults(response.data.users || []);
    } catch (error) {
      logger.error('Error searching guests', error);
    }
  };

  const handleSelectGuest = async (guest: { id: number; full_name: string; email?: string; phone?: string }) => {
    setSelectedGuest(guest);
    setGuestSearch('');
    setGuestSearchResults([]);
    
    // Fetch guest's active bookings
    try {
      const response = await bookingService.getAllBookings({
        search: guest.email || guest.phone,
        limit: 10,
      });
      if (response.data?.bookings && response.data.bookings.length > 0) {
        setSelectedBooking(response.data.bookings[0]);
        setCommunicationForm({ ...communicationForm, booking_id: response.data.bookings[0].id });
      }
    } catch (error) {
      logger.error('Error fetching bookings', error);
    }
  };

  const handleSendCommunication = async () => {
    if (!selectedGuest) {
      toast.error('Please select a guest');
      return;
    }

    if (!communicationForm.content.trim()) {
      toast.error('Please enter message content');
      return;
    }

    if (communicationForm.communication_type === 'email' && !communicationForm.subject.trim()) {
      toast.error('Please enter email subject');
      return;
    }

    try {
      setSending(true);
      
      // Create guest communication record
      await apiClient.post(`/guest-profiles/${selectedGuest.id}/communications`, {
        communication_type: communicationForm.communication_type,
        direction: 'outbound',
        subject: communicationForm.subject || undefined,
        content: communicationForm.content,
        booking_id: communicationForm.booking_id || undefined,
        is_automated: false,
      });

      // Send notification
      await apiClient.post('/notifications/send', {
        user_id: selectedGuest.id,
        notification_type: 'custom',
        channel: communicationForm.communication_type === 'email' ? 'email' : 'sms',
        subject: communicationForm.subject || undefined,
        content: communicationForm.content,
        booking_id: communicationForm.booking_id || undefined,
      });

      toast.success('Communication sent successfully!');
      
      // Reset form
      setSelectedGuest(null);
      setSelectedBooking(null);
      setCommunicationForm({
        communication_type: 'email',
        subject: '',
        content: '',
        booking_id: null,
      });
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to send communication');
      logger.error('Error sending communication', error);
    } finally {
      setSending(false);
    }
  };

  const fetchCommunications = async () => {
    try {
      setLoading(true);
      const params: { page: number; limit: number; guest_id?: number } = {
        page: historyPage,
        limit: 20,
      };
      
      if (historyFilters.communication_type) {
        params.communication_type = historyFilters.communication_type;
      }
      if (historyFilters.direction) {
        params.direction = historyFilters.direction;
      }

      const response = await apiClient.get('/guest-profiles/communications', { params });
      if (response.data?.communications) {
        let filtered = response.data.communications;
        
        if (historyFilters.search) {
          const searchLower = historyFilters.search.toLowerCase();
          filtered = filtered.filter((comm: GuestCommunication) =>
            comm.guest_name?.toLowerCase().includes(searchLower) ||
            comm.subject?.toLowerCase().includes(searchLower) ||
            comm.content?.toLowerCase().includes(searchLower)
          );
        }
        
        setCommunications(filtered);
        setHistoryTotalPages(response.data.pagination?.total_pages || 1);
      }
    } catch (error: unknown) {
      toast.error('Failed to load communications');
      logger.error('Error fetching communications', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchTemplates = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/notifications/templates');
      if (response.data?.templates) {
        setTemplates(response.data.templates);
      }
    } catch (error: unknown) {
      toast.error('Failed to load templates');
      logger.error('Error fetching templates', error);
    } finally {
      setLoading(false);
    }
  };

  const handleUseTemplate = (template: CommunicationTemplate) => {
    setSelectedTemplate(template);
    setCommunicationForm({
      ...communicationForm,
      subject: template.subject || '',
      content: template.content,
      communication_type: template.channel === 'email' ? 'email' : 'sms',
    });
    setShowTemplateModal(false);
    setActiveTab('send');
  };

  const getCommunicationIcon = (type: string) => {
    switch (type) {
      case 'email':
        return Mail;
      case 'sms':
        return MessageSquare;
      case 'phone':
        return Phone;
      default:
        return Bell;
    }
  };

  const getCommunicationColor = (type: string) => {
    switch (type) {
      case 'email':
        return 'bg-blue-100 text-blue-800';
      case 'sms':
        return 'bg-green-100 text-green-800';
      case 'phone':
        return 'bg-purple-100 text-purple-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      {/* Header */}
      <div className="mb-6 sm:mb-8">
        <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
          <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600 rounded-full"></div>
          <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
            Guest Communication
          </h1>
        </div>
        <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">
          Send messages, emails, and manage communication templates
        </p>
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-slate-200">
        <nav className="-mb-px flex space-x-8">
          {[
            { id: 'send' as Tab, label: 'Send Message', icon: Send },
            { id: 'history' as Tab, label: 'History', icon: Clock },
            { id: 'templates' as Tab, label: 'Templates', icon: FileText },
          ].map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center space-x-2 py-4 px-1 border-b-2 font-medium text-sm transition-colors
                  ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600'
                      : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300'
                  }
                `}
              >
                <Icon className="w-5 h-5" />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </nav>
      </div>

      {/* Send Tab */}
      {activeTab === 'send' && (
        <div className="space-y-6">
          <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-6">
            <h2 className="text-xl font-bold text-slate-900 mb-6">Send Communication</h2>
            
            {/* Guest Selection */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-slate-700 mb-2">Select Guest *</label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5" />
                <input
                  type="text"
                  value={guestSearch}
                  onChange={(e) => setGuestSearch(e.target.value)}
                  placeholder="Search by name, email, or phone..."
                  className="w-full pl-10 pr-4 py-3 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
                />
              </div>
              
              {guestSearchResults.length > 0 && (
                <div className="mt-2 border-2 border-slate-200 rounded-xl overflow-hidden max-h-60 overflow-y-auto">
                  {guestSearchResults.map((guest) => (
                    <div
                      key={guest.id}
                      onClick={() => handleSelectGuest(guest)}
                      className="p-3 hover:bg-blue-50 cursor-pointer border-b border-slate-100 last:border-b-0 transition-colors"
                    >
                      <div className="font-medium text-slate-900">{guest.full_name || guest.name}</div>
                      <div className="text-sm text-slate-600">{guest.email}</div>
                      {guest.phone && <div className="text-sm text-slate-600">{guest.phone}</div>}
                    </div>
                  ))}
                </div>
              )}

              {selectedGuest && (
                <div className="mt-3 p-4 bg-blue-50 rounded-xl border border-blue-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="font-semibold text-slate-900">{selectedGuest.full_name || selectedGuest.name}</div>
                      <div className="text-sm text-slate-600">{selectedGuest.email}</div>
                      {selectedGuest.phone && <div className="text-sm text-slate-600">{selectedGuest.phone}</div>}
                      {selectedBooking && (
                        <div className="text-sm text-blue-600 mt-2">
                          Active Booking: {selectedBooking.booking_number} - Room {selectedBooking.room?.room_number}
                        </div>
                      )}
                    </div>
                    <button
                      onClick={() => {
                        setSelectedGuest(null);
                        setSelectedBooking(null);
                        setCommunicationForm({ ...communicationForm, booking_id: null });
                      }}
                      className="p-2 text-slate-400 hover:text-slate-600"
                    >
                      <X className="w-5 h-5" />
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Communication Type */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-slate-700 mb-2">Communication Type *</label>
              <select
                value={communicationForm.communication_type}
                onChange={(e) => setCommunicationForm({ ...communicationForm, communication_type: e.target.value })}
                className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              >
                <option value="email">Email</option>
                <option value="sms">SMS</option>
                <option value="phone">Phone Call</option>
              </select>
            </div>

            {/* Subject (for email) */}
            {communicationForm.communication_type === 'email' && (
              <div className="mb-6">
                <label className="block text-sm font-medium text-slate-700 mb-2">Subject *</label>
                <input
                  type="text"
                  value={communicationForm.subject}
                  onChange={(e) => setCommunicationForm({ ...communicationForm, subject: e.target.value })}
                  placeholder="Email subject..."
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
                />
              </div>
            )}

            {/* Content */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-slate-700 mb-2">Message *</label>
              <textarea
                value={communicationForm.content}
                onChange={(e) => setCommunicationForm({ ...communicationForm, content: e.target.value })}
                rows={8}
                placeholder="Enter your message..."
                className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              />
              {communicationForm.communication_type === 'sms' && (
                <p className="text-xs text-slate-500 mt-1">
                  {communicationForm.content.length} / 160 characters
                </p>
              )}
            </div>

            {/* Actions */}
            <div className="flex items-center gap-4">
              <button
                onClick={() => setShowTemplateModal(true)}
                className="px-4 py-2 border-2 border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors"
              >
                Use Template
              </button>
              <button
                onClick={handleSendCommunication}
                disabled={sending || !selectedGuest}
                className="flex-1 px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl hover:from-blue-700 hover:to-indigo-700 font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
              >
                {sending ? (
                  <>
                    <RefreshCw className="w-5 h-5 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="w-5 h-5" />
                    Send {communicationForm.communication_type === 'email' ? 'Email' : communicationForm.communication_type === 'sms' ? 'SMS' : 'Message'}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* History Tab */}
      {activeTab === 'history' && (
        <div className="space-y-6">
          {/* Filters */}
          <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-6">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">Search</label>
                <input
                  type="text"
                  value={historyFilters.search}
                  onChange={(e) => setHistoryFilters({ ...historyFilters, search: e.target.value })}
                  placeholder="Search communications..."
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">Type</label>
                <select
                  value={historyFilters.communication_type}
                  onChange={(e) => setHistoryFilters({ ...historyFilters, communication_type: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100"
                >
                  <option value="">All Types</option>
                  <option value="email">Email</option>
                  <option value="sms">SMS</option>
                  <option value="phone">Phone</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">Direction</label>
                <select
                  value={historyFilters.direction}
                  onChange={(e) => setHistoryFilters({ ...historyFilters, direction: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100"
                >
                  <option value="">All</option>
                  <option value="outbound">Outbound</option>
                  <option value="inbound">Inbound</option>
                </select>
              </div>
            </div>
          </div>

          {/* Communications List */}
          <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 overflow-hidden">
            {loading ? (
              <div className="p-12">
                <Loading text="Loading communications..." />
              </div>
            ) : communications.length === 0 ? (
              <div className="p-12">
                <EmptyState title="No communications found" description="No communications match your filters." />
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-slate-200">
                    <thead className="bg-slate-50">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Guest</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Type</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Subject</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Direction</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Date</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-slate-200">
                      {communications.map((comm) => {
                        const Icon = getCommunicationIcon(comm.communication_type);
                        return (
                          <tr key={comm.id} className="hover:bg-slate-50">
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm font-medium text-slate-900">{comm.guest_name || 'N/A'}</div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <span className={`px-2 py-1 inline-flex text-xs font-semibold rounded-full ${getCommunicationColor(comm.communication_type)}`}>
                                <Icon className="w-3 h-3 mr-1" />
                                {comm.communication_type}
                              </span>
                            </td>
                            <td className="px-6 py-4">
                              <div className="text-sm text-slate-900">{comm.subject || 'No subject'}</div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <span className={`px-2 py-1 inline-flex text-xs font-semibold rounded-full ${
                                comm.direction === 'outbound' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'
                              }`}>
                                {comm.direction}
                              </span>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                              {formatRelativeTime(comm.created_at)}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                              <button
                                onClick={() => {
                                  // Show communication details
                                  alert(`Content: ${comm.content}`);
                                }}
                                className="text-blue-600 hover:text-blue-900"
                              >
                                <Eye className="w-4 h-4" />
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
                {historyTotalPages > 1 && (
                  <div className="px-6 py-4 border-t border-slate-200">
                    <Pagination
                      currentPage={historyPage}
                      totalPages={historyTotalPages}
                      onPageChange={setHistoryPage}
                    />
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      )}

      {/* Templates Tab */}
      {activeTab === 'templates' && (
        <div className="space-y-6">
          <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-slate-900">Communication Templates</h2>
              <button
                onClick={() => setShowTemplateModal(true)}
                className="px-4 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 font-medium flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                New Template
              </button>
            </div>

            {loading ? (
              <Loading text="Loading templates..." />
            ) : templates.length === 0 ? (
              <EmptyState title="No templates found" description="Create your first communication template." />
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {templates.map((template) => {
                  const Icon = getCommunicationIcon(template.channel);
                  return (
                    <div
                      key={template.id}
                      className="p-4 border-2 border-slate-200 rounded-xl hover:border-blue-300 hover:shadow-lg transition-all cursor-pointer"
                      onClick={() => handleUseTemplate(template)}
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className={`px-2 py-1 inline-flex text-xs font-semibold rounded-full ${getCommunicationColor(template.channel)}`}>
                          <Icon className="w-3 h-3 mr-1" />
                          {template.channel}
                        </span>
                        {template.is_active ? (
                          <span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Active</span>
                        ) : (
                          <span className="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">Inactive</span>
                        )}
                      </div>
                      <h3 className="font-bold text-slate-900 mb-1">{template.name}</h3>
                      {template.subject && <p className="text-sm text-slate-600 mb-2">{template.subject}</p>}
                      <p className="text-sm text-slate-500 line-clamp-2">{template.content}</p>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Template Selection Modal */}
      {showTemplateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-slate-200">
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold text-slate-900">Select Template</h2>
                <button
                  onClick={() => setShowTemplateModal(false)}
                  className="text-slate-400 hover:text-slate-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>
            <div className="p-6">
              {templates.length === 0 ? (
                <EmptyState title="No templates available" />
              ) : (
                <div className="space-y-3">
                  {templates.map((template) => {
                    const Icon = getCommunicationIcon(template.channel);
                    return (
                      <div
                        key={template.id}
                        onClick={() => {
                          handleUseTemplate(template);
                          setShowTemplateModal(false);
                        }}
                        className="p-4 border-2 border-slate-200 rounded-xl hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all"
                      >
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="font-bold text-slate-900">{template.name}</h3>
                          <span className={`px-2 py-1 inline-flex text-xs font-semibold rounded-full ${getCommunicationColor(template.channel)}`}>
                            <Icon className="w-3 h-3 mr-1" />
                            {template.channel}
                          </span>
                        </div>
                        {template.subject && <p className="text-sm text-slate-600 mb-2">{template.subject}</p>}
                        <p className="text-sm text-slate-500">{template.content.substring(0, 100)}...</p>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default GuestCommunicationPage;

