'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  CalendarDays, Plus, Check, X, Clock,
  Loader2, Search, User, AlertCircle
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface LeaveRequest {
  id: string;
  type: string;
  startDate: string;
  endDate: string;
  days: number;
  reason?: string;
  status: string;
  createdAt: string;
  approvedAt?: string;
  employee?: { firstName: string; lastName: string };
}

interface Employee {
  id: string;
  firstName: string;
  lastName: string;
  employeeId: string;
}

export default function LeaveRequestsPage() {
  const [leaveRequests, setLeaveRequests] = useState<LeaveRequest[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [formData, setFormData] = useState({
    employeeId: '',
    type: 'annual',
    startDate: '',
    endDate: '',
    reason: '',
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const [leaveRes, empRes] = await Promise.all([
        fetch('/api/erp/hr?type=leave-requests'),
        fetch('/api/erp/hr?type=employees'),
      ]);
      const leaveData = await leaveRes.json();
      const empData = await empRes.json();
      setLeaveRequests(leaveData.leaveRequests || []);
      setEmployees(empData.employees || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.employeeId || !formData.startDate || !formData.endDate) return;

    setSubmitting(true);
    try {
      const start = new Date(formData.startDate);
      const end = new Date(formData.endDate);
      const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;

      const res = await fetch('/api/erp/hr', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'leave-request',
          data: {
            employeeId: formData.employeeId,
            type: formData.type,
            startDate: start,
            endDate: end,
            days,
            reason: formData.reason || null,
            status: 'pending',
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          employeeId: '',
          type: 'annual',
          startDate: '',
          endDate: '',
          reason: '',
        });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create leave request:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleAction = async (id: string, status: 'approved' | 'rejected') => {
    try {
      const res = await fetch('/api/erp/hr', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'leave-request',
          id,
          data: { status },
        }),
      });
      if (res.ok) {
        fetchData();
      }
    } catch (error) {
      console.error('Failed to update leave request:', error);
    }
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'approved': return 'bg-green-500/10 text-green-400';
      case 'pending': return 'bg-yellow-500/10 text-yellow-400';
      case 'rejected': return 'bg-red-500/10 text-red-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'annual': return 'bg-brand-deep/10 text-brand';
      case 'sick': return 'bg-red-500/10 text-red-400';
      case 'personal': return 'bg-brand-secondary/10 text-brand-secondary-light';
      case 'bereavement': return 'bg-gray-500/10 text-gray-400';
      case 'maternity': return 'bg-pink-500/10 text-pink-400';
      case 'paternity': return 'bg-blue-500/10 text-blue-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const filteredRequests = leaveRequests.filter(req => {
    const empName = req.employee ? `${req.employee.firstName} ${req.employee.lastName}`.toLowerCase() : '';
    const matchesSearch = empName.includes(searchTerm.toLowerCase());
    const matchesFilter = filterStatus === 'all' || req.status === filterStatus;
    return matchesSearch && matchesFilter;
  });

  const pendingCount = leaveRequests.filter(r => r.status === 'pending').length;
  const approvedCount = leaveRequests.filter(r => r.status === 'approved').length;
  const totalDaysOff = leaveRequests
    .filter(r => r.status === 'approved')
    .reduce((sum, r) => sum + (r.days || 0), 0);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <CalendarDays className="w-7 h-7 text-brand" />
            Leave Requests
          </h1>
          <p className="text-gray-400 mt-1">Manage employee time off requests</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4" />
          New Request
        </button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Requests</p>
          <p className="text-xl font-bold text-white">{leaveRequests.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-yellow-400" />
            <p className="text-sm text-gray-400">Pending</p>
          </div>
          <p className="text-xl font-bold text-yellow-400">{pendingCount}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <Check className="w-4 h-4 text-green-400" />
            <p className="text-sm text-gray-400">Approved</p>
          </div>
          <p className="text-xl font-bold text-green-400">{approvedCount}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Days Off</p>
          <p className="text-xl font-bold text-brand">{totalDaysOff}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Search by employee..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep focus:outline-none"
          />
        </div>
        <div className="flex gap-2">
          {['all', 'pending', 'approved', 'rejected'].map((status) => (
            <button
              key={status}
              onClick={() => setFilterStatus(status)}
              className={`px-3 py-2 rounded-lg text-sm capitalize transition-colors ${
                filterStatus === status
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {status}
            </button>
          ))}
        </div>
      </div>

      {/* Leave Requests List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="space-y-4">
          {filteredRequests.length === 0 ? (
            <div className="text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No leave requests found
            </div>
          ) : (
            filteredRequests.filter(req => req && req.id).map((req, index) => (
              <motion.div
                key={req.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.03 }}
                className="p-4 bg-white/5 border border-white/10 rounded-lg"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="p-2 bg-brand-deep/10 rounded-lg">
                      <User className="w-6 h-6 text-brand" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-white">
                        {req.employee ? `${req.employee.firstName} ${req.employee.lastName}` : 'Unknown'}
                      </h3>
                      <div className="flex items-center gap-3 mt-1">
                        <span className={`text-xs px-2 py-0.5 rounded capitalize ${getTypeColor(req.type || 'other')}`}>
                          {req.type || 'Leave'}
                        </span>
                        <span className="text-xs text-gray-500">
                          {formatDate(req.startDate)} - {formatDate(req.endDate)}
                        </span>
                        <span className="text-xs text-gray-500">
                          ({req.days || 0} {(req.days || 0) === 1 ? 'day' : 'days'})
                        </span>
                      </div>
                      {req.reason && (
                        <p className="text-sm text-gray-400 mt-2">{req.reason}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className={`text-xs px-2 py-1 rounded capitalize ${getStatusColor(req.status)}`}>
                      {req.status || 'pending'}
                    </span>
                    {req.status === 'pending' && (
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleAction(req.id, 'approved')}
                          className="p-2 bg-green-500/10 hover:bg-green-500/20 text-green-400 rounded-lg transition-colors"
                          title="Approve"
                        >
                          <Check className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleAction(req.id, 'rejected')}
                          className="p-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 rounded-lg transition-colors"
                          title="Reject"
                        >
                          <X className="w-4 h-4" />
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </motion.div>
            ))
          )}
        </div>
      )}

      {/* New Leave Request Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="New Leave Request"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Employee</label>
            <select
              value={formData.employeeId}
              onChange={(e) => setFormData({ ...formData, employeeId: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              required
            >
              <option value="">Select employee...</option>
              {employees.map((emp) => (
                <option key={emp.id} value={emp.id}>
                  {emp.firstName} {emp.lastName}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Leave Type</label>
            <select
              value={formData.type}
              onChange={(e) => setFormData({ ...formData, type: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
            >
              <option value="annual">Annual Leave</option>
              <option value="sick">Sick Leave</option>
              <option value="personal">Personal Leave</option>
              <option value="bereavement">Bereavement</option>
              <option value="maternity">Maternity Leave</option>
              <option value="paternity">Paternity Leave</option>
              <option value="unpaid">Unpaid Leave</option>
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Start Date</label>
              <input
                type="date"
                value={formData.startDate}
                onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">End Date</label>
              <input
                type="date"
                value={formData.endDate}
                onChange={(e) => setFormData({ ...formData, endDate: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                required
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Reason (Optional)</label>
            <textarea
              value={formData.reason}
              onChange={(e) => setFormData({ ...formData, reason: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none resize-none"
              rows={3}
              placeholder="Brief explanation for the leave request..."
            />
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting || !formData.employeeId || !formData.startDate || !formData.endDate}
              className="px-4 py-2 bg-brand-deep hover:bg-brand-deep disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors flex items-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              Submit Request
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
