import React, { useEffect, useState } from 'react';
import { Calendar, Clock, CheckCircle, AlertCircle } from 'lucide-react';
import staffShiftService, { StaffShift, StaffTask } from '../../features/staffShifts/services/staffShiftService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';

const HousekeepingShiftViewPage: React.FC = () => {
  const [shifts, setShifts] = useState<StaffShift[]>([]);
  const [tasks, setTasks] = useState<StaffTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedDate, setSelectedDate] = useState(new Date());

  useEffect(() => {
    fetchShifts();
    fetchTasks();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDate]);

  const fetchShifts = async () => {
    try {
      setLoading(true);
      const dateStr = selectedDate.toISOString().split('T')[0];
      const response = await staffShiftService.getShifts({
        shift_date: dateStr,
        limit: 100,
      });
      
      if (response.status === 'success' && response.data) {
        setShifts(response.data.shifts || []);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load shifts');
    } finally {
      setLoading(false);
    }
  };

  const fetchTasks = async () => {
    try {
      const response = await staffShiftService.getTasks({
        limit: 100,
      });
      
      if (response.status === 'success' && response.data) {
        setTasks(response.data.tasks || []);
      }
    } catch (error) {
      console.error('Error fetching tasks:', error);
    }
  };

  const handleStatusUpdate = async (shiftId: number, newStatus: string) => {
    try {
      await staffShiftService.updateShift(shiftId, {
        status: newStatus,
      });
      toast.success('Shift status updated successfully');
      fetchShifts();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to update status');
    }
  };

  if (loading && shifts.length === 0) {
    return <Loading fullScreen text="Loading your shifts..." />;
  }

  const getUpcomingShifts = () => shifts.filter((s) => s.status === 'scheduled').length;
  const getCompletedShifts = () => shifts.filter((s) => s.status === 'completed').length;
  const getPendingTasks = () => tasks.filter((t) => ['pending', 'assigned'].includes(t.status)).length;

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              My Shifts
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">View and manage your shift schedule</p>
        </div>
        <input
          type="date"
          value={selectedDate.toISOString().split('T')[0]}
          onChange={(e) => setSelectedDate(new Date(e.target.value))}
          className="px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-[var(--luxury-gold)] focus:ring-4 focus:ring-yellow-100"
        />
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 animate-fade-in">
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Upcoming Shifts</p>
              <p className="text-3xl font-bold text-[var(--luxury-gold)] mt-2">{getUpcomingShifts()}</p>
            </div>
            <Calendar className="w-12 h-12 text-[var(--luxury-gold)]" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Completed</p>
              <p className="text-3xl font-bold text-green-600 mt-2">{getCompletedShifts()}</p>
            </div>
            <CheckCircle className="w-12 h-12 text-green-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Pending Tasks</p>
              <p className="text-3xl font-bold text-orange-600 mt-2">{getPendingTasks()}</p>
            </div>
            <AlertCircle className="w-12 h-12 text-orange-500" />
          </div>
        </div>
      </div>

      {/* Shifts List */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in">
        <div className="p-6">
          <h2 className="text-xl font-bold text-slate-900 mb-4">My Shifts</h2>
          {shifts.length === 0 ? (
            <div className="text-center py-12">
              <Calendar className="w-16 h-16 text-slate-400 mx-auto mb-4" />
              <p className="text-slate-600 text-lg">No shifts scheduled</p>
            </div>
          ) : (
            <div className="space-y-4">
              {shifts.map((shift) => (
                <div
                  key={shift.id}
                  className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-xl p-6 hover:shadow-lg transition-all"
                >
                  <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-lg font-bold text-slate-900">
                          {formatDate(shift.shift_date)}
                        </h3>
                        <span className={`px-3 py-1 rounded-full text-sm font-medium ${
                          shift.status === 'completed' ? 'bg-green-100 text-green-800' :
                          shift.status === 'in_progress' ? 'bg-blue-100 text-blue-800' :
                          shift.status === 'scheduled' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {shift.status.replace('_', ' ').toUpperCase()}
                        </span>
                      </div>
                      <div className="flex items-center gap-4 text-slate-600">
                        <div className="flex items-center gap-2">
                          <Clock className="w-4 h-4" />
                          <span>{shift.start_time} - {shift.end_time}</span>
                        </div>
                        {shift.department && (
                          <span className="px-2 py-1 bg-slate-100 rounded text-sm">{shift.department}</span>
                        )}
                      </div>
                      {shift.notes && (
                        <p className="text-slate-600 mt-2 text-sm">{shift.notes}</p>
                      )}
                    </div>
                    {shift.status === 'scheduled' && (
                      <select
                        value={shift.status}
                        onChange={(e) => handleStatusUpdate(shift.id, e.target.value)}
                        className="px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-[var(--luxury-gold)] cursor-pointer"
                      >
                        <option value="scheduled">Scheduled</option>
                        <option value="in_progress">Start Shift</option>
                        <option value="cancelled">Cancel</option>
                      </select>
                    )}
                    {shift.status === 'in_progress' && (
                      <button
                        onClick={() => handleStatusUpdate(shift.id, 'completed')}
                        className="px-4 py-2 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-colors"
                      >
                        End Shift
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Tasks List */}
      {tasks.length > 0 && (
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in">
          <div className="p-6">
            <h2 className="text-xl font-bold text-slate-900 mb-4">My Tasks</h2>
            <div className="space-y-3">
              {tasks.slice(0, 5).map((task) => (
                <div
                  key={task.id}
                  className="bg-slate-50 border border-slate-200 rounded-lg p-4"
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="font-semibold text-slate-900">{task.title}</h4>
                      {task.description && (
                        <p className="text-sm text-slate-600 mt-1">{task.description}</p>
                      )}
                    </div>
                    <span className={`px-3 py-1 rounded-full text-sm font-medium ${
                      task.priority === 'urgent' ? 'bg-red-100 text-red-800' :
                      task.priority === 'high' ? 'bg-orange-100 text-orange-800' :
                      'bg-blue-100 text-blue-800'
                    }`}>
                      {task.priority.toUpperCase()}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default HousekeepingShiftViewPage;

