'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Clock, Plus, Play, Square, Coffee,
  Loader2, Search, Calendar, User
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface TimeEntry {
  id: string;
  date: string;
  clockIn: string;
  clockOut?: string;
  breakMinutes?: number;
  totalHours?: number;
  status: string;
  notes?: string;
  employee?: { firstName: string; lastName: string };
}

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

export default function TimeTrackingPage() {
  const [timeEntries, setTimeEntries] = useState<TimeEntry[]>([]);
  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 [formData, setFormData] = useState({
    employeeId: '',
    date: new Date().toISOString().split('T')[0],
    clockIn: '09:00',
    clockOut: '17:00',
    breakMinutes: '30',
    notes: '',
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const [timeRes, empRes] = await Promise.all([
        fetch('/api/erp/hr?type=time-entries'),
        fetch('/api/erp/hr?type=employees'),
      ]);
      const timeData = await timeRes.json();
      const empData = await empRes.json();
      setTimeEntries(timeData.timeEntries || []);
      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.date || !formData.clockIn) return;

    setSubmitting(true);
    try {
      const clockIn = new Date(`${formData.date}T${formData.clockIn}:00`);
      const clockOut = formData.clockOut ? new Date(`${formData.date}T${formData.clockOut}:00`) : null;

      const res = await fetch('/api/erp/hr', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'time-entry',
          data: {
            employeeId: formData.employeeId,
            date: new Date(formData.date),
            clockIn,
            clockOut,
            breakMinutes: parseInt(formData.breakMinutes) || 0,
            status: clockOut ? 'completed' : 'in-progress',
            notes: formData.notes || null,
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          employeeId: '',
          date: new Date().toISOString().split('T')[0],
          clockIn: '09:00',
          clockOut: '17:00',
          breakMinutes: '30',
          notes: '',
        });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create time entry:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const formatTime = (dateStr: string) => {
    if (!dateStr) return '--:--';
    return new Date(dateStr).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
  };

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

  const filteredEntries = timeEntries.filter(entry => {
    const empName = entry.employee ? `${entry.employee.firstName} ${entry.employee.lastName}`.toLowerCase() : '';
    return empName.includes(searchTerm.toLowerCase());
  });

  const totalHoursToday = timeEntries
    .filter(e => new Date(e.date).toDateString() === new Date().toDateString())
    .reduce((sum, e) => sum + (e.totalHours || 0), 0);

  const activeNow = timeEntries.filter(e => e.status === 'in-progress').length;

  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">
            <Clock className="w-7 h-7 text-brand" />
            Time Tracking
          </h1>
          <p className="text-gray-400 mt-1">Track employee work hours</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" />
          Log Time
        </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 Entries</p>
          <p className="text-xl font-bold text-white">{timeEntries.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <Play className="w-4 h-4 text-green-400" />
            <p className="text-sm text-gray-400">Currently Active</p>
          </div>
          <p className="text-xl font-bold text-green-400">{activeNow}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Hours Today</p>
          <p className="text-xl font-bold text-brand">{totalHoursToday.toFixed(1)}h</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Avg Hours/Entry</p>
          <p className="text-xl font-bold text-brand-secondary-light">
            {timeEntries.length > 0
              ? (timeEntries.reduce((sum, e) => sum + (e.totalHours || 0), 0) / timeEntries.length).toFixed(1)
              : '0'}h
          </p>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <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 name..."
          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>

      {/* Time Entries Table */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="bg-white/5 border border-white/10 rounded-lg overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/10">
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Employee</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Date</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Clock In</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Clock Out</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Break</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Total</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredEntries.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="p-8 text-center text-gray-500">
                      No time entries found
                    </td>
                  </tr>
                ) : (
                  filteredEntries.filter(entry => entry && entry.id).map((entry, index) => (
                    <motion.tr
                      key={entry.id}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ delay: index * 0.02 }}
                      className="border-b border-white/5 hover:bg-white/5"
                    >
                      <td className="p-4">
                        <div className="flex items-center gap-2">
                          <User className="w-4 h-4 text-gray-500" />
                          <span className="text-white">
                            {entry.employee ? `${entry.employee.firstName} ${entry.employee.lastName}` : 'Unknown'}
                          </span>
                        </div>
                      </td>
                      <td className="p-4 text-sm text-gray-400">{formatDate(entry.date)}</td>
                      <td className="p-4">
                        <span className="flex items-center gap-1 text-green-400">
                          <Play className="w-3 h-3" />
                          {formatTime(entry.clockIn)}
                        </span>
                      </td>
                      <td className="p-4">
                        {entry.clockOut ? (
                          <span className="flex items-center gap-1 text-red-400">
                            <Square className="w-3 h-3" />
                            {formatTime(entry.clockOut)}
                          </span>
                        ) : (
                          <span className="text-yellow-400">Active</span>
                        )}
                      </td>
                      <td className="p-4">
                        <span className="flex items-center gap-1 text-gray-400">
                          <Coffee className="w-3 h-3" />
                          {entry.breakMinutes ?? 0}m
                        </span>
                      </td>
                      <td className="p-4 text-brand font-medium">
                        {entry.totalHours ? `${entry.totalHours.toFixed(1)}h` : '--'}
                      </td>
                      <td className="p-4">
                        <span className={`text-xs px-2 py-1 rounded ${
                          entry.status === 'in-progress'
                            ? 'bg-green-500/10 text-green-400'
                            : 'bg-gray-500/10 text-gray-400'
                        }`}>
                          {entry.status || 'unknown'}
                        </span>
                      </td>
                    </motion.tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Log Time Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Log Time Entry"
      >
        <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} ({emp.employeeId})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Date</label>
            <input
              type="date"
              value={formData.date}
              onChange={(e) => setFormData({ ...formData, date: 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 className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Clock In</label>
              <input
                type="time"
                value={formData.clockIn}
                onChange={(e) => setFormData({ ...formData, clockIn: 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">Clock Out</label>
              <input
                type="time"
                value={formData.clockOut}
                onChange={(e) => setFormData({ ...formData, clockOut: 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"
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Break (min)</label>
              <input
                type="number"
                value={formData.breakMinutes}
                onChange={(e) => setFormData({ ...formData, breakMinutes: 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"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Notes (Optional)</label>
            <textarea
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: 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={2}
            />
          </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.date || !formData.clockIn}
              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" />}
              Log Entry
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
