import { useState, useEffect } from 'react';
import api from '../lib/api';
import {
  Calendar,
  Clock,
  User,
  Phone,
  Plus,
  CheckCircle2,
  XCircle,
  Trash2,
  Building2,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface AppointmentItem {
  _id: string;
  companyId?: string;
  companyName: string;
  customerName: string;
  customerPhone: string;
  customerEmail?: string;
  appointmentDate: string;
  appointmentTime: string;
  reason: string;
  status: 'scheduled' | 'completed' | 'cancelled';
}

interface CompanyOption {
  _id: string;
  companyName: string;
}

const Appointments = () => {
  const [appointments, setAppointments] = useState<AppointmentItem[]>([]);
  const [companies, setCompanies] = useState<CompanyOption[]>([]);
  const [selectedDate, setSelectedDate] = useState<string>(
    () => new Date().toISOString().slice(0, 10)
  );
  const [availableSlots, setAvailableSlots] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');

  const [form, setForm] = useState({
    companyId: '',
    customerName: '',
    customerPhone: '',
    appointmentDate: new Date().toISOString().slice(0, 10),
    appointmentTime: '10:00',
    reason: 'Initial Consultation',
  });

  useEffect(() => {
    let active = true;
    const loadInitial = async () => {
      try {
        const [compRes, apptRes, availRes] = await Promise.all([
          api.get<CompanyOption[]>('/company'),
          api.get<AppointmentItem[]>('/appointments'),
          api.get<{ availableSlots: string[] }>(`/appointments/availability?date=${selectedDate}`),
        ]);
        if (!active) return;
        setCompanies(compRes.data);
        if (compRes.data.length > 0) {
          setForm((prev) => ({ ...prev, companyId: compRes.data[0]._id }));
        }
        setAppointments(apptRes.data);
        setAvailableSlots(availRes.data.availableSlots);
        setLoading(false);
      } catch (err) {
        console.error('Failed to load appointments', err);
        if (active) setLoading(false);
      }
    };
    loadInitial();
    return () => {
      active = false;
    };
  }, [selectedDate]);

  const refreshData = async (dateToQuery = selectedDate) => {
    try {
      const [apptRes, availRes] = await Promise.all([
        api.get<AppointmentItem[]>('/appointments'),
        api.get<{ availableSlots: string[] }>(`/appointments/availability?date=${dateToQuery}`),
      ]);
      setAppointments(apptRes.data);
      setAvailableSlots(availRes.data.availableSlots);
    } catch (err) {
      console.error('Failed to refresh appointments', err);
    }
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg('');
    try {
      const selectedCompany = companies.find((c) => c._id === form.companyId);
      await api.post('/appointments', {
        ...form,
        companyName: selectedCompany?.companyName || 'General',
      });
      setShowModal(false);
      setForm((prev) => ({
        ...prev,
        customerName: '',
        customerPhone: '',
        reason: 'Initial Consultation',
      }));
      await refreshData(form.appointmentDate);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: string } } })?.response?.data?.error;
      setErrorMsg(msg || 'Failed to schedule appointment.');
    }
  };

  const handleStatusChange = async (id: string, status: 'scheduled' | 'completed' | 'cancelled') => {
    try {
      await api.put(`/appointments/${id}/status`, { status });
      await refreshData();
    } catch (err) {
      console.error('Failed to update status', err);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/appointments/${id}`);
      await refreshData();
    } catch (err) {
      console.error('Failed to delete appointment', err);
    }
  };

  return (
    <div className="space-y-8 pb-12">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight flex items-center gap-2">
            <Calendar className="w-6 h-6 text-indigo-400" />
            Appointments & Calendar
          </h1>
          <p className="mt-1 text-sm text-slate-400">
            Real-time bookings scheduled by your AI phone receptionist or staff.
          </p>
        </div>

        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-sm font-medium transition-colors shadow-lg shadow-indigo-500/20"
        >
          <Plus className="w-4 h-4" />
          New Appointment
        </button>
      </div>

      {/* Live Slot Availability Bar */}
      <div className="bg-white/[0.02] border border-white/10 rounded-2xl p-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
          <div>
            <h3 className="text-base font-semibold text-white">
              AI Calendar Availability Inspector
            </h3>
            <p className="text-xs text-slate-400">
              Your AI voice agent checks these open slots in real time when callers ask to book.
            </p>
          </div>
          <input
            type="date"
            value={selectedDate}
            onChange={(e) => setSelectedDate(e.target.value)}
            className="px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-sm text-white outline-none focus:ring-2 focus:ring-indigo-500"
          />
        </div>

        <div className="flex flex-wrap gap-2.5">
          {availableSlots.length === 0 ? (
            <span className="text-sm text-rose-400">No open slots remaining on {selectedDate}.</span>
          ) : (
            availableSlots.map((slot) => (
              <span
                key={slot}
                className="px-3 py-1.5 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-semibold flex items-center gap-1.5"
              >
                <Clock className="w-3.5 h-3.5" />
                {slot} Available
              </span>
            ))
          )}
        </div>
      </div>

      {/* Appointments Table */}
      <div className="bg-white/[0.02] border border-white/10 rounded-2xl overflow-hidden shadow-xl">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-white/5 border-b border-white/10">
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Caller / Client
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Company
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Date & Time
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Reason
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Status
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider text-right">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {loading ? (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-slate-400 text-sm">
                    Loading appointments...
                  </td>
                </tr>
              ) : appointments.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-14 text-center text-slate-400 text-sm">
                    No appointments booked yet. Ask the AI voice agent to schedule a consultation or click "New Appointment".
                  </td>
                </tr>
              ) : (
                appointments.map((appt) => (
                  <tr key={appt._id} className="hover:bg-white/[0.03] transition-colors">
                    <td className="py-4 px-6">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-full bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center text-indigo-400">
                          <User className="w-4 h-4" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-white">{appt.customerName}</p>
                          <p className="text-xs text-slate-400 flex items-center gap-1 mt-0.5">
                            <Phone className="w-3 h-3" /> {appt.customerPhone}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-6">
                      <span className="inline-flex items-center gap-1.5 text-sm text-slate-300">
                        <Building2 className="w-3.5 h-3.5 text-indigo-400" />
                        {appt.companyName}
                      </span>
                    </td>
                    <td className="py-4 px-6">
                      <div className="text-sm text-white font-medium">{appt.appointmentDate}</div>
                      <div className="text-xs text-indigo-400 font-semibold">
                        {appt.appointmentTime}
                      </div>
                    </td>
                    <td className="py-4 px-6 text-sm text-slate-300">{appt.reason}</td>
                    <td className="py-4 px-6">
                      {appt.status === 'scheduled' && (
                        <span className="px-2.5 py-1 rounded-md text-xs font-medium bg-indigo-500/10 text-indigo-400 border border-indigo-500/20">
                          Scheduled
                        </span>
                      )}
                      {appt.status === 'completed' && (
                        <span className="px-2.5 py-1 rounded-md text-xs font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                          Completed
                        </span>
                      )}
                      {appt.status === 'cancelled' && (
                        <span className="px-2.5 py-1 rounded-md text-xs font-medium bg-rose-500/10 text-rose-400 border border-rose-500/20">
                          Cancelled
                        </span>
                      )}
                    </td>
                    <td className="py-4 px-6 text-right">
                      <div className="flex justify-end gap-2">
                        {appt.status === 'scheduled' && (
                          <>
                            <button
                              onClick={() => handleStatusChange(appt._id, 'completed')}
                              className="p-1.5 text-emerald-400 hover:bg-emerald-500/10 rounded-lg"
                              title="Mark Completed"
                            >
                              <CheckCircle2 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleStatusChange(appt._id, 'cancelled')}
                              className="p-1.5 text-amber-400 hover:bg-amber-500/10 rounded-lg"
                              title="Cancel Appointment"
                            >
                              <XCircle className="w-4 h-4" />
                            </button>
                          </>
                        )}
                        <button
                          onClick={() => handleDelete(appt._id)}
                          className="p-1.5 text-rose-400 hover:bg-rose-500/10 rounded-lg"
                          title="Delete"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create Appointment Modal */}
      <AnimatePresence>
        {showModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-slate-900 border border-white/10 rounded-2xl p-6 max-w-md w-full shadow-2xl"
            >
              <h3 className="text-lg font-bold text-white mb-4">Schedule New Appointment</h3>
              {errorMsg && (
                <div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs">
                  {errorMsg}
                </div>
              )}
              <form onSubmit={handleCreate} className="space-y-4">
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1">Company</label>
                  <select
                    value={form.companyId}
                    onChange={(e) => setForm({ ...form, companyId: e.target.value })}
                    className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                  >
                    {companies.map((c) => (
                      <option key={c._id} value={c._id}>
                        {c.companyName}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1">
                    Customer Name
                  </label>
                  <input
                    required
                    type="text"
                    value={form.customerName}
                    onChange={(e) => setForm({ ...form, customerName: e.target.value })}
                    placeholder="John Doe"
                    className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1">
                    Customer Phone
                  </label>
                  <input
                    required
                    type="text"
                    value={form.customerPhone}
                    onChange={(e) => setForm({ ...form, customerPhone: e.target.value })}
                    placeholder="+1 555 234 5678"
                    className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                  />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-slate-400 mb-1">Date</label>
                    <input
                      required
                      type="date"
                      value={form.appointmentDate}
                      onChange={(e) => setForm({ ...form, appointmentDate: e.target.value })}
                      className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-slate-400 mb-1">Time</label>
                    <select
                      value={form.appointmentTime}
                      onChange={(e) => setForm({ ...form, appointmentTime: e.target.value })}
                      className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                    >
                      {['09:00', '10:00', '11:00', '12:00', '14:00', '15:00', '16:00', '17:00'].map(
                        (t) => (
                          <option key={t} value={t}>
                            {t}
                          </option>
                        )
                      )}
                    </select>
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1">Reason</label>
                  <input
                    type="text"
                    value={form.reason}
                    onChange={(e) => setForm({ ...form, reason: e.target.value })}
                    className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white"
                  />
                </div>
                <div className="flex justify-end gap-2 pt-3">
                  <button
                    type="button"
                    onClick={() => setShowModal(false)}
                    className="px-4 py-2 rounded-xl bg-slate-800 text-slate-300 text-sm"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-medium"
                  >
                    Confirm Booking
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default Appointments;
