import { useState, useEffect } from 'react';
import { 
  Contact, Search, Plus, User, Phone, Mail, 
  Calendar, Clock, FileText, CheckCircle2,
  LogOut, MoreVertical, X,
  BadgeCheck, MapPin, MessageSquare
} from 'lucide-react';
import api from '../../../store/api';
import { Modal, ModalBody } from '../../../components/ui/Modal';

interface VisitorLog {
  id: number;
  uid: string;
  visitor_name: string;
  visitor_type: 'parent' | 'vendor' | 'government' | 'media' | 'other';
  phone: string;
  email: string;
  id_number: string;
  purpose: string;
  person_to_visit: string;
  check_in: string;
  check_out: string | null;
  badge_number: string;
  remarks: string;
  creator_name: string;
}

export default function VisitorLog() {
  const [logs, setLogs] = useState<VisitorLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [formData, setFormData] = useState({
    visitor_name: '',
    visitor_type: 'parent',
    phone: '',
    email: '',
    id_number: '',
    purpose: '',
    person_to_visit: '',
    badge_number: '',
    remarks: ''
  });

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

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/front-office/visitors', formData);
      setShowAddModal(false);
      setFormData({
        visitor_name: '',
        visitor_type: 'parent',
        phone: '',
        email: '',
        id_number: '',
        purpose: '',
        person_to_visit: '',
        badge_number: '',
        remarks: ''
      });
      fetchLogs();
    } catch (error) {
      console.error('Error adding visitor log:', error);
    }
  };

  const handleCheckOut = async (id: number) => {
    try {
      await api.put(`/front-office/visitors/${id}/checkout`);
      fetchLogs();
    } catch (error) {
      console.error('Error checking out visitor:', error);
    }
  };

  const filteredLogs = logs.filter(log => 
    log.visitor_name.toLowerCase().includes(search.toLowerCase()) ||
    log.person_to_visit.toLowerCase().includes(search.toLowerCase()) ||
    log.purpose.toLowerCase().includes(search.toLowerCase())
  );

  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">
            <Contact className="text-primary" />
            Digital Visitor Log
          </h1>
          <p className="text-text-muted text-sm mt-1">Track and manage all campus visitors in real-time</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors shadow-sm"
        >
          <Plus size={20} />
          Add Visitor
        </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 visitors, purpose, or host..."
              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-primary/20 focus:border-primary transition-all text-sm text-text"
            />
          </div>
          <div className="flex items-center gap-2">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
              <input
                type="text"
                placeholder="Search visitors..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 pr-3 py-2 bg-background border border-border rounded-lg text-sm text-text w-48 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
              />
            </div>
          </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">Visitor Info</th>
                <th className="px-6 py-4 font-semibold">Purpose & Host</th>
                <th className="px-6 py-4 font-semibold">Time Log</th>
                <th className="px-6 py-4 font-semibold">Badge</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-primary border-t-transparent rounded-full animate-spin"></div>
                      <span>Loading logs...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                    <Contact size={48} className="mx-auto mb-4 opacity-20" />
                    <p>No visitor logs found</p>
                  </td>
                </tr>
              ) : (
                filteredLogs.map((log) => (
                  <tr key={log.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-primary/10 text-primary flex items-center justify-center font-bold">
                          {log.visitor_name[0]}
                        </div>
                        <div>
                          <p className="font-semibold text-text">{log.visitor_name}</p>
                          <div className="flex items-center gap-3 text-xs text-text-muted mt-1">
                            <span className="flex items-center gap-1"><Phone size={12} /> {log.phone}</span>
                            <span className="capitalize px-1.5 py-0.5 bg-background-alt rounded text-text-secondary border border-border">{log.visitor_type}</span>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div>
                        <p className="text-text font-medium">{log.purpose}</p>
                        <p className="text-xs text-text-muted mt-1 flex items-center gap-1">
                          <User size={12} /> Visiting: {log.person_to_visit}
                        </p>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="space-y-1.5">
                        <div className="flex items-center gap-2 text-xs text-text-secondary">
                          <Clock size={12} className="text-primary" />
                          <span className="font-medium">In:</span>
                          <span>{new Date(log.check_in).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                          <span className="text-text-muted px-1">•</span>
                          <span>{new Date(log.check_in).toLocaleDateString()}</span>
                        </div>
                        {log.check_out && (
                          <div className="flex items-center gap-2 text-xs text-text-muted">
                            <Clock size={12} className="text-text-muted opacity-60" />
                            <span className="font-medium">Out:</span>
                            <span>{new Date(log.check_out).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="px-2.5 py-1 bg-amber-500/10 text-amber-500 rounded-md border border-amber-500/20 text-xs font-bold font-mono">
                          {log.badge_number}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      {log.check_out ? (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[0.65rem] font-black uppercase bg-background-alt text-text-secondary border border-border">
                          <CheckCircle2 size={12} />
                          Checked Out
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[0.65rem] font-black uppercase bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 animate-pulse">
                          <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full"></div>
                          In Campus
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      {!log.check_out && (
                        <button
                          onClick={() => handleCheckOut(log.id)}
                          className="px-3 py-1.5 bg-background border border-red-500/20 text-red-500 rounded-lg hover:bg-red-500/10 transition-colors text-xs font-semibold flex items-center gap-1.5 ml-auto"
                        >
                          <LogOut size={14} />
                          Check Out
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Visitor Modal */}
      {showAddModal && (
        <Modal
          open={true}
          onClose={() => setShowAddModal(false)}
          title="New Visitor Registration"
          icon={User}
          maxWidth="max-w-xl"
          zIndex={1000}
        >
          <ModalBody className="p-0 max-h-[90vh] overflow-hidden">
            <form id="visitorlog-add-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">Visitor Full Name*</label>
                    <input
                      required
                      type="text"
                      value={formData.visitor_name}
                      onChange={e => setFormData({ ...formData, visitor_name: e.target.value })}
                      className="form-input"
                      placeholder="e.g. John Doe"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Visitor Type</label>
                    <select
                      value={formData.visitor_type}
                      onChange={e => setFormData({ ...formData, visitor_type: e.target.value as any })}
                      className="form-input"
                    >
                      <option value="parent">Parent/Guardian</option>
                      <option value="vendor">Vendor/Service Provider</option>
                      <option value="government">Government Official</option>
                      <option value="media">Media/Press</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">Phone Number</label>
                      <input
                        type="text"
                        value={formData.phone}
                        onChange={e => setFormData({ ...formData, phone: e.target.value })}
                        className="form-input"
                        placeholder="+263..."
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">ID/Passport No.</label>
                      <input
                        type="text"
                        value={formData.id_number}
                        onChange={e => setFormData({ ...formData, id_number: e.target.value })}
                        className="form-input"
                        placeholder="ID Number"
                      />
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Person to Visit*</label>
                    <input
                      required
                      type="text"
                      value={formData.person_to_visit}
                      onChange={e => setFormData({ ...formData, person_to_visit: e.target.value })}
                      className="form-input"
                      placeholder="e.g. Principal Moyo"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Purpose of Visit*</label>
                    <input
                      required
                      type="text"
                      value={formData.purpose}
                      onChange={e => setFormData({ ...formData, purpose: e.target.value })}
                      className="form-input"
                      placeholder="e.g. Fee enquiry"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Badge Number</label>
                    <input
                      type="text"
                      value={formData.badge_number}
                      onChange={e => setFormData({ ...formData, badge_number: e.target.value })}
                      className="form-input"
                      placeholder="Badge ID"
                    />
                  </div>
                </div>
              </div>

              <div className="mt-6">
                <label className="block text-sm font-semibold text-text-secondary mb-1.5">Remarks/Notes</label>
                <textarea
                  rows={3}
                  value={formData.remarks}
                  onChange={e => setFormData({ ...formData, remarks: e.target.value })}
                  className="form-input resize-none"
                  placeholder="Any additional notes..."
                />
              </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-primary text-white rounded-lg hover:bg-primary-dark transition-colors shadow-lg shadow-primary/20 font-semibold"
                >
                  Register Visitor
                </button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
