import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { 
  MessageSquare, Search, Plus, User, Phone, Mail, 
  Calendar, Clock, FileText, CheckCircle2,
  Filter, MoreVertical, X,
  AlertCircle, AlertTriangle, Info,
  CheckCircle, Clock3, MessageCircle,
  ShieldAlert, LifeBuoy
} from 'lucide-react';
import api from '../../../store/api';

interface Complaint {
  id: number;
  uid: string;
  complainant_name: string;
  complainant_type: 'student' | 'parent' | 'staff' | 'visitor' | 'other';
  contact_phone: string;
  contact_email: string;
  category: string;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  subject: string;
  description: string;
  status: 'open' | 'investigating' | 'resolved' | 'closed' | 'rejected';
  date_received: string;
  assigned_to_name: string;
  resolution: string | null;
  resolved_by_name: string | null;
  resolved_at: string | null;
}

export default function Complaints() {
  const [complaints, setComplaints] = useState<Complaint[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [showResolveModal, setShowResolveModal] = useState<number | null>(null);
  const [resolution, setResolution] = useState('');
  const [users, setUsers] = useState<any[]>([]);
  const [formData, setFormData] = useState({
    complainant_name: '',
    complainant_type: 'parent' as 'parent' | 'student' | 'staff' | 'visitor' | 'other',
    contact_phone: '',
    contact_email: '',
    category: 'academic',
    priority: 'medium' as 'low' | 'medium' | 'high' | 'urgent',
    subject: '',
    description: '',
    assigned_to: ''
  });

  const fetchComplaints = async () => {
    try {
      setLoading(true);
      const response = await api.get('/front-office/complaints');
      setComplaints(response.data);
    } catch (error) {
      console.error('Error fetching complaints:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await api.get('/users?role=admin');
      const data = response.data.users || response.data;
      setUsers(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };

  useEffect(() => {
    fetchComplaints();
    fetchUsers();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/front-office/complaints', formData);
      setShowAddModal(false);
      setFormData({
        complainant_name: '',
        complainant_type: 'parent',
        contact_phone: '',
        contact_email: '',
        category: 'academic',
        priority: 'medium',
        subject: '',
        description: '',
        assigned_to: ''
      });
      fetchComplaints();
    } catch (error) {
      console.error('Error adding complaint:', error);
    }
  };

  const handleResolve = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!showResolveModal) return;
    try {
      await api.put(`/front-office/complaints/${showResolveModal}/resolve`, { resolution });
      setShowResolveModal(null);
      setResolution('');
      fetchComplaints();
    } catch (error) {
      console.error('Error resolving complaint:', error);
    }
  };

  const filteredComplaints = complaints.filter(c => 
    c.complainant_name.toLowerCase().includes(search.toLowerCase()) ||
    c.subject.toLowerCase().includes(search.toLowerCase()) ||
    c.category.toLowerCase().includes(search.toLowerCase())
  );

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent': return 'bg-red-500/10 text-red-500 border-red-500/20';
      case 'high': return 'bg-amber-500/10 text-amber-500 border-amber-500/20';
      case 'medium': return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
      default: return 'bg-slate-500/10 text-slate-500 border-slate-500/20';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'open': return 'bg-slate-500/10 text-slate-500 border-slate-500/20';
      case 'investigating': return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
      case 'resolved': return 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20';
      case 'rejected': return 'bg-red-500/10 text-red-500 border-red-500/20';
      case 'closed': return 'bg-slate-500/10 text-slate-400 border-slate-400/20';
      default: return 'bg-slate-500/10 text-slate-500 border-slate-500/20';
    }
  };

  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-text flex items-center gap-2">
            <LifeBuoy className="text-brand" />
            Complaints Manager
          </h1>
          <p className="text-text-muted text-sm mt-1">Grievance redressal and feedback management system</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-brand text-white rounded-lg hover:bg-brand-dark transition-colors shadow-sm font-semibold"
        >
          <Plus size={20} />
          Log Complaint
        </button>
      </div>

      <div className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
        <div className="p-4 border-b border-border flex flex-col md:flex-row gap-4 items-center justify-between bg-background-alt/50">
          <div className="relative w-full md:w-96">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={18} />
            <input
              type="text"
              placeholder="Search by complainant, subject or category..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand/20 focus:border-brand transition-all text-sm text-text"
            />
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-background-alt/50 border-b border-border text-xs uppercase tracking-wider text-text-muted font-semibold">
                <th className="px-6 py-4 font-semibold">Complainant</th>
                <th className="px-6 py-4 font-semibold">Grievance Details</th>
                <th className="px-6 py-4 font-semibold">Priority</th>
                <th className="px-6 py-4 font-semibold">Assigned To</th>
                <th className="px-6 py-4 font-semibold">Status</th>
                <th className="px-6 py-4 font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50 text-sm">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                    <div className="flex flex-col items-center gap-2">
                      <div className="w-8 h-8 border-4 border-brand border-t-transparent rounded-full animate-spin"></div>
                      <span>Loading complaints...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredComplaints.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                    <MessageCircle size={48} className="mx-auto mb-4 opacity-20" />
                    <p>No complaints found</p>
                  </td>
                </tr>
              ) : (
                filteredComplaints.map((c) => (
                  <tr key={c.id} className="hover:bg-background-alt/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-brand/10 text-brand flex items-center justify-center font-bold">
                          {c.complainant_name[0]}
                        </div>
                        <div>
                          <p className="font-semibold text-text">{c.complainant_name}</p>
                          <p className="text-xs text-text-muted mt-1 capitalize">{c.complainant_type}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="max-w-xs">
                        <p className="text-text font-semibold truncate">{c.subject}</p>
                        <p className="text-xs text-text-muted mt-1 line-clamp-1">{c.description}</p>
                        <span className="inline-block mt-2 px-1.5 py-0.5 bg-background-alt text-text-secondary rounded text-[0.65rem] font-medium uppercase border border-border">
                          {c.category}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-2.5 py-1 rounded-full text-[0.65rem] font-black uppercase border transition-all duration-200 ${getPriorityColor(c.priority)}`}>
                        {c.priority}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2 text-xs text-text-secondary">
                        <div className="w-6 h-6 rounded-full bg-background-alt flex items-center justify-center border border-border">
                          <User size={12} />
                        </div>
                        {c.assigned_to_name || 'Unassigned'}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[0.65rem] font-black uppercase border transition-all duration-200 ${getStatusColor(c.status)}`}>
                        {c.status}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      {c.status !== 'resolved' && (
                        <button
                          onClick={() => setShowResolveModal(c.id)}
                          className="px-3 py-1.5 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors text-xs font-semibold shadow-sm"
                        >
                          Resolve
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Complaint Modal */}
      {showAddModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowAddModal(false)}>
          <div className="bg-card rounded-[2.5rem] shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-4 border-b border-border flex items-center justify-between bg-background-alt/50 relative">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <ShieldAlert size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-lg font-bold text-text flex items-center gap-2">
                  <ShieldAlert className="text-brand" size={20} />
                  New Complaint Entry
                </h2>
              </div>
              <button
                onClick={() => setShowAddModal(false)}
                className="relative z-10 p-2 text-text-muted hover:text-text hover:bg-background-alt rounded-lg transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleSubmit} className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Complainant Name*</label>
                    <input
                      required
                      type="text"
                      value={formData.complainant_name}
                      onChange={e => setFormData({ ...formData, complainant_name: e.target.value })}
                      className="form-input"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Complainant Type</label>
                    <select
                      value={formData.complainant_type}
                      onChange={e => setFormData({ ...formData, complainant_type: e.target.value as any })}
                      className="form-input"
                    >
                      <option value="parent">Parent</option>
                      <option value="student">Student</option>
                      <option value="staff">Staff</option>
                      <option value="other">Other</option>
                    </select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Priority</label>
                      <select
                        value={formData.priority}
                        onChange={e => setFormData({ ...formData, priority: e.target.value as any })}
                        className="form-input"
                      >
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                        <option value="urgent">Urgent</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Category</label>
                      <select
                        value={formData.category}
                        onChange={e => setFormData({ ...formData, category: e.target.value })}
                        className="form-input"
                      >
                        <option value="academic">Academic</option>
                        <option value="facility">Facility</option>
                        <option value="behavioral">Behavioral</option>
                        <option value="financial">Financial</option>
                        <option value="transport">Transport</option>
                        <option value="other">Other</option>
                      </select>
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Subject*</label>
                    <input
                      required
                      type="text"
                      value={formData.subject}
                      onChange={e => setFormData({ ...formData, subject: e.target.value })}
                      className="form-input"
                      placeholder="Brief summary"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Assign To</label>
                    <select
                      value={formData.assigned_to}
                      onChange={e => setFormData({ ...formData, assigned_to: e.target.value })}
                      className="form-input"
                    >
                      <option value="">Select Staff</option>
                      {users.map(u => (
                        <option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>
                      ))}
                    </select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Phone</label>
                      <input
                        type="text"
                        value={formData.contact_phone}
                        onChange={e => setFormData({ ...formData, contact_phone: e.target.value })}
                        className="form-input"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Email</label>
                      <input
                        type="email"
                        value={formData.contact_email}
                        onChange={e => setFormData({ ...formData, contact_email: e.target.value })}
                        className="form-input"
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div className="mt-6">
                <label className="block text-sm font-semibold text-text-secondary mb-1.5">Description*</label>
                <textarea
                  required
                  rows={4}
                  value={formData.description}
                  onChange={e => setFormData({ ...formData, description: e.target.value })}
                  className="form-input resize-none"
                  placeholder="Provide full details of the complaint..."
                />
              </div>

              <div className="mt-8 pt-6 border-t border-border flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setShowAddModal(false)}
                  className="px-6 py-2 text-text-secondary hover:bg-background-alt rounded-lg transition-colors font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-8 py-2 bg-brand text-white rounded-lg hover:bg-brand-dark transition-colors shadow-lg shadow-brand/20 font-semibold"
                >
                  Log Complaint
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Resolve Modal */}
      {showResolveModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowResolveModal(false)}>
          <div className="bg-card rounded-[2.5rem] shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-4 border-b border-border flex items-center justify-between bg-background-alt/50 relative">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <CheckCircle2 size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-lg font-bold text-text flex items-center gap-2">
                  <CheckCircle2 className="text-emerald-600" size={20} />
                  Resolve Complaint
                </h2>
              </div>
              <button
                onClick={() => setShowResolveModal(null)}
                className="relative z-10 p-2 text-text-muted hover:text-text hover:bg-background-alt rounded-lg transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleResolve} className="p-6">
              <div>
                <label className="block text-sm font-semibold text-text-secondary mb-1.5">Resolution Details*</label>
                <textarea
                  required
                  rows={5}
                  value={resolution}
                  onChange={e => setResolution(e.target.value)}
                  className="form-input resize-none"
                  placeholder="How was this complaint resolved?"
                />
              </div>

              <div className="mt-6 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setShowResolveModal(null)}
                  className="px-4 py-2 text-text-secondary hover:bg-background-alt rounded-lg transition-colors font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors font-semibold shadow-lg shadow-emerald-500/20"
                >
                  Confirm Resolution
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}
