import { useState, useEffect } from 'react'
import io from 'socket.io-client'
import axios from 'axios'
import { Car, AlertCircle, CheckCircle, XCircle, Clock, Calendar } from 'lucide-react'

// Env var logic for Vite
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';
const socket = io(API_URL);

function App() {
  const [plates, setPlates] = useState([]);
  const [detections, setDetections] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [newPlate, setNewPlate] = useState({ number: '', owner: '' });

  // History State
  const [viewMode, setViewMode] = useState('live'); // 'live' | 'history'
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [historyLogs, setHistoryLogs] = useState([]);
  const [loadingHistory, setLoadingHistory] = useState(false);

  const handleRegister = async (e) => {
    e.preventDefault();
    try {
      if (!newPlate.number) return;
      await axios.post(`${API_URL}/api/plates`, {
        number: newPlate.number.toUpperCase(),
        owner: newPlate.owner
      });
      setNewPlate({ number: '', owner: '' });
      setShowModal(false);
      fetchPlates();
    } catch (err) {
      alert('Error adding plate: ' + err.message);
    }
  };

  // Load initial data
  useEffect(() => {
    fetchPlates();
    fetchRecentDetections();

    // Socket listeners
    socket.on('new_detection', (data) => {
      console.log('New detection:', data);
      setDetections(prev => [data, ...prev].slice(0, 10)); // Keep last 10
    });

    return () => {
      socket.off('new_detection');
    };
  }, []);

  const fetchRecentDetections = async () => {
    try {
      const res = await axios.get(`${API_URL}/api/recent`);
      // Map backend AccessLog format to frontend detection format if needed
      // AccessLog: { id, plateNumber, accessStatus, timestamp }
      // Detection: { plate, status, timestamp }
      const formatted = res.data.map(log => ({
        plate: log.plateNumber,
        status: log.accessStatus,
        timestamp: log.timestamp
      }));
      setDetections(formatted);
    } catch (err) {
      console.error("Error fetching recent detections:", err);
    }
  };

  const fetchPlates = async () => {
    try {
      const res = await axios.get(`${API_URL}/api/plates`);
      setPlates(res.data);
      setLoading(false);
    } catch (err) {
      console.error(err);
      setLoading(false);
    }
  };

  const fetchHistory = async (date) => {
    setLoadingHistory(true);
    try {
      const res = await axios.get(`${API_URL}/api/history?date=${date}`);
      setHistoryLogs(res.data);
    } catch (err) {
      console.error("Error fetching history:", err);
      // alert("Failed to fetch history");
    } finally {
      setLoadingHistory(false);
    }
  };

  // Fetch history when date changes or when switching to history view
  useEffect(() => {
    if (viewMode === 'history') {
      fetchHistory(selectedDate);
    }
  }, [viewMode, selectedDate]);

  const StatusBadge = ({ status }) => {
    const colors = {
      GRANTED: 'bg-green-500/20 text-green-400 border-green-500/50',
      DENIED: 'bg-red-500/20 text-red-400 border-red-500/50',
      UNKNOWN: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/50',
      ALLOWED: 'bg-green-500/20 text-green-400 border-green-500/50',
    };

    return (
      <span className={`px-3 py-1 rounded-full text-xs font-medium border ${colors[status] || colors.UNKNOWN}`}>
        {status}
      </span>
    );
  };

  return (
    <div className="min-h-screen bg-slate-900 text-slate-100 p-8">
      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 backdrop-blur-sm">
          <div className="bg-slate-800 p-6 rounded-2xl w-full max-w-md border border-slate-700 shadow-2xl transform transition-all scale-100">
            <h3 className="text-xl font-bold mb-4">Register New Plate</h3>
            <form onSubmit={handleRegister} className="space-y-4">
              <div>
                <label className="block text-sm text-slate-400 mb-1">Plate Number</label>
                <input
                  autoFocus
                  type="text"
                  value={newPlate.number}
                  onChange={e => setNewPlate({ ...newPlate, number: e.target.value.toUpperCase() })}
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 outline-none font-mono uppercase"
                  placeholder="ABCD12"
                />
              </div>
              <div>
                <label className="block text-sm text-slate-400 mb-1">Owner Name</label>
                <input
                  type="text"
                  value={newPlate.owner}
                  onChange={e => setNewPlate({ ...newPlate, owner: e.target.value })}
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 outline-none"
                  placeholder="John Doe"
                />
              </div>
              <div className="flex space-x-3 mt-6">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="flex-1 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg font-medium transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg font-medium transition-colors"
                >
                  Register
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
      <div className="max-w-7xl mx-auto space-y-8">

        {/* Header */}
        <header className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="p-3 bg-blue-600 rounded-lg">
              <Car size={32} />
            </div>
            <div>
              <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">
                Control Patente AI
              </h1>
              <p className="text-slate-400">Real-time ALPR Monitoring System</p>
            </div>
          </div>
          <div className="flex items-center space-x-2 text-sm text-slate-400">
            <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
            <span>System Online</span>
          </div>
        </header>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

          {/* Main Feed Section (Live / History) */}
          <div className="lg:col-span-2 space-y-6">
            <h2 className="text-xl font-semibold flex items-center justify-between">
              <div className="flex items-center space-x-2">
                {viewMode === 'live' ? <Clock className="text-blue-400" /> : <Calendar className="text-purple-400" />}
                <span>{viewMode === 'live' ? 'Live Detections' : 'History Log'}</span>
              </div>

              {/* Toggle Switch */}
              <div className="flex bg-slate-800 rounded-lg p-1 border border-slate-700">
                <button
                  onClick={() => setViewMode('live')}
                  className={`px-4 py-1 rounded-md text-sm font-medium transition-all ${viewMode === 'live'
                    ? 'bg-blue-600 text-white shadow-lg'
                    : 'text-slate-400 hover:text-slate-200'
                    }`}
                >
                  Live
                </button>
                <button
                  onClick={() => setViewMode('history')}
                  className={`px-4 py-1 rounded-md text-sm font-medium transition-all ${viewMode === 'history'
                    ? 'bg-purple-600 text-white shadow-lg'
                    : 'text-slate-400 hover:text-slate-200'
                    }`}
                >
                  History
                </button>
              </div>
            </h2>

            <div className="bg-slate-800/50 rounded-2xl p-6 border border-slate-700/50 backdrop-blur-sm min-h-[400px]">

              {viewMode === 'live' ? (
                <>
                  {/* Video Feed */}
                  <div className="mb-6 rounded-xl overflow-hidden bg-black aspect-video relative border border-slate-700 shadow-lg">
                    <img
                      src="http://192.168.196.100:5001/video_feed"
                      alt="Live Camera Feed"
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        e.target.style.display = 'none';
                        e.target.nextSibling.style.display = 'flex';
                      }}
                    />
                    <div className="absolute inset-0 flex items-center justify-center text-slate-500 hidden bg-slate-900">
                      <p>Camera Offline or Connecting...</p>
                    </div>
                    <div className="absolute top-4 right-4 animate-pulse">
                      <div className="px-2 py-1 bg-red-600 rounded text-xs font-bold text-white uppercase tracking-wider">
                        LIVE
                      </div>
                    </div>
                  </div>

                  {/* Detections List */}
                  <h3 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-4">Recent Scans</h3>

                  {detections.length === 0 ? (
                    <div className="flex flex-col items-center justify-center text-slate-500 space-y-4 text-center py-8">
                      <p>No detections yet...</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {detections.map((d, i) => (
                        <div key={i} className="flex items-center justify-between p-4 bg-slate-800 border border-slate-700 rounded-xl hover:bg-slate-750 transition-colors">
                          <div className="flex items-center space-x-4">
                            <div className="p-2 bg-slate-700 rounded-lg font-mono text-xl tracking-wider font-bold">
                              {d.plate}
                            </div>
                            <div className="text-sm text-slate-400">
                              {new Date(d.timestamp).toLocaleTimeString()}
                            </div>
                          </div>
                          <StatusBadge status={d.status} />
                        </div>
                      ))}
                    </div>
                  )}
                </>
              ) : (
                /* History View */
                <div className="space-y-6">
                  <div className="flex items-center space-x-4 bg-slate-800 p-4 rounded-xl border border-slate-700">
                    <label className="text-slate-400 text-sm font-medium">Select Date:</label>
                    <input
                      type="date"
                      value={selectedDate}
                      onChange={(e) => setSelectedDate(e.target.value)}
                      className="bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-white focus:ring-2 focus:ring-purple-500 outline-none"
                    />
                  </div>

                  <div className="space-y-4">
                    {loadingHistory ? (
                      <p className="text-center text-slate-500 py-8">Loading history...</p>
                    ) : historyLogs.length === 0 ? (
                      <div className="text-center text-slate-500 py-8">
                        No records found for {selectedDate}
                      </div>
                    ) : (
                      historyLogs.map((log) => (
                        <div key={log.id} className="flex items-center justify-between p-4 bg-slate-800 border border-slate-700 rounded-xl">
                          <div className="flex items-center space-x-4">
                            <div className="p-2 bg-slate-700 rounded-lg font-mono text-xl tracking-wider font-bold">
                              {log.plateNumber}
                            </div>
                            <div className="text-sm text-slate-400">
                              {new Date(log.timestamp).toLocaleTimeString()}
                            </div>
                          </div>
                          <StatusBadge status={log.accessStatus} />
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Database / Stats */}
          <div className="space-y-6">
            <h2 className="text-xl font-semibold flex items-center space-x-2">
              <CheckCircle className="text-green-400" />
              <span>Registered Plates</span>
            </h2>

            <div className="bg-slate-800/50 rounded-2xl p-6 border border-slate-700/50 backdrop-blur-sm max-h-[600px] overflow-y-auto">
              {loading ? (
                <p className="text-center text-slate-500">Loading database...</p>
              ) : (
                <div className="space-y-3">
                  {plates.map((p) => (
                    <div key={p.id} className="flex items-center justify-between p-3 bg-slate-800/80 rounded-lg border border-slate-700/50">
                      <div>
                        <div className="font-mono font-bold text-slate-200">{p.number}</div>
                        <div className="text-xs text-slate-400">{p.owner || 'Unknown Owner'}</div>
                      </div>
                      <span className="text-xs font-medium text-green-400 bg-green-500/10 px-2 py-1 rounded">
                        {p.status}
                      </span>
                    </div>
                  ))}
                  {plates.length === 0 && (
                    <p className="text-center text-slate-500 text-sm">No plates registered.</p>
                  )}
                </div>
              )}

              <button
                className="w-full mt-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg font-medium transition-colors text-sm"
                onClick={() => setShowModal(true)}
              >
                + Register New Plate
              </button>
            </div>
          </div>
        </div>

      </div>
    </div>
  )
}

export default App
