'use client';

import { ATAButton } from '@/components/agent-hierarchy/ata-flyout';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Users, UserPlus, Building2, Clock, CalendarDays,
  DollarSign, TrendingUp, AlertCircle, CheckCircle, Plus,
  Briefcase, Loader2
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface HRData {
  summary: {
    totalEmployees: number;
    fullTime: number;
    partTime: number;
    contractors: number;
    departmentCount: number;
    pendingLeaveRequests: number;
    monthlyPayroll: number;
    avgSalary: number;
  };
  departments: Array<{ id: string; name: string; code: string; headCount: number }>;
  pendingLeave: Array<{
    id: string;
    type: string;
    startDate: string;
    endDate: string;
    days: number;
    employee: { firstName: string; lastName: string };
  }>;
}

interface Department {
  id: string;
  name: string;
  code: string;
}

export default function HRDashboard() {
  const [data, setData] = useState<HRData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    departmentId: '',
    employmentType: 'full-time',
    salary: '',
    position: '',
  });

  const fetchData = () => {
    setLoading(true);
    setError(null);
    fetch('/api/erp/hr')
      .then((r) => {
        if (!r.ok) throw new Error('Failed to fetch HR data');
        return r.json();
      })
      .then((d) => {
        if (d.success === false) throw new Error(d.error || 'Failed to fetch HR data');
        setData(d);
        setDepartments(d.departments || []);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  };

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

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value || 0);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.firstName || !formData.lastName || !formData.email) return;
    
    setSubmitting(true);
    try {
      const employeeId = `EMP${Date.now().toString().slice(-6)}`;
      const res = await fetch('/api/erp/hr', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'employee',
          data: {
            employeeId,
            firstName: formData.firstName,
            lastName: formData.lastName,
            email: formData.email,
            departmentId: formData.departmentId || null,
            employmentType: formData.employmentType,
            salary: formData.salary ? parseFloat(formData.salary) : 0,
            position: formData.position || 'Employee',
            status: 'active',
            hireDate: new Date().toISOString(),
          },
        }),
      });
      
      if (res.ok) {
        setShowModal(false);
        setFormData({ firstName: '', lastName: '', email: '', departmentId: '', employmentType: 'full-time', salary: '', position: '' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to add employee:', error);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-8 w-48 bg-white/10 rounded animate-pulse" />
        <div className="grid grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="h-32 bg-white/5 rounded-lg animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-white">HR & People</h1>
          <button onClick={fetchData} className="px-4 py-2 bg-brand-deep/20 text-brand rounded-lg">
            Retry
          </button>
        </div>
        <div className="glass-card p-8 border border-red-500/30 text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400">{error}</p>
          <p className="text-gray-500 text-sm mt-2">Please try refreshing the page or check the database connection.</p>
        </div>
      </div>
    );
  }

  const summary = data?.summary || {} as HRData['summary'];

  const kpiCards = [
    {
      label: 'Total Employees',
      value: summary.totalEmployees || 0,
      icon: <Users className="w-5 h-5" />,
      color: 'purple',
    },
    {
      label: 'Departments',
      value: summary.departmentCount || 0,
      icon: <Building2 className="w-5 h-5" />,
      color: 'cyan',
    },
    {
      label: 'Monthly Payroll',
      value: formatCurrency(summary.monthlyPayroll),
      icon: <DollarSign className="w-5 h-5" />,
      color: 'green',
    },
    {
      label: 'Pending Leave',
      value: summary.pendingLeaveRequests || 0,
      icon: <CalendarDays className="w-5 h-5" />,
      color: summary.pendingLeaveRequests > 0 ? 'amber' : 'gray',
    },
  ];

  const colorClasses: Record<string, { bg: string; text: string; border: string }> = {
    cyan: { bg: 'bg-brand-deep/10', text: 'text-brand', border: 'border-brand-deep/30' },
    green: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/30' },
    purple: { bg: 'bg-brand-secondary/10', text: 'text-brand-secondary-light', border: 'border-brand-secondary/30' },
    amber: { bg: 'bg-amber-500/10', text: 'text-amber-400', border: 'border-amber-500/30' },
    gray: { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/30' },
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">HR & People</h1>
          <p className="text-gray-400 text-sm">Employee management, payroll, and time tracking</p>
        </div>
        <div className="flex items-center gap-3">
          <ATAButton agentId="agent-hr" variant="compact" />
          <button 
            onClick={() => setShowModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30"
          >
            <UserPlus className="w-4 h-4" />
            <span>Add Employee</span>
          </button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpiCards.map((card, idx) => (
          <motion.div
            key={card.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
            className={`glass-card p-4 border ${colorClasses[card.color].border}`}
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-gray-400 text-sm">{card.label}</span>
              <div className={`p-1.5 rounded ${colorClasses[card.color].bg}`}>
                <span className={colorClasses[card.color].text}>{card.icon}</span>
              </div>
            </div>
            <span className="text-2xl font-bold text-white">{card.value}</span>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Employment Breakdown */}
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <Briefcase className="w-5 h-5 text-brand-secondary-light" />
            Employment Types
          </h2>
          <div className="space-y-4">
            <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-3 h-3 rounded-full bg-brand-secondary" />
                <span className="text-gray-300">Full-Time</span>
              </div>
              <span className="text-white font-semibold">{summary.fullTime || 0}</span>
            </div>
            <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-3 h-3 rounded-full bg-brand-deep" />
                <span className="text-gray-300">Part-Time</span>
              </div>
              <span className="text-white font-semibold">{summary.partTime || 0}</span>
            </div>
            <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-3 h-3 rounded-full bg-amber-500" />
                <span className="text-gray-300">Contractors</span>
              </div>
              <span className="text-white font-semibold">{summary.contractors || 0}</span>
            </div>
          </div>
          <div className="mt-4 pt-4 border-t border-white/10">
            <p className="text-gray-500 text-sm">
              Average Salary: <span className="text-white font-medium">{formatCurrency(summary.avgSalary)}</span>
            </p>
          </div>
        </div>

        {/* Pending Leave Requests */}
        <div className="glass-card p-6 border border-white/10">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <CalendarDays className="w-5 h-5 text-amber-400" />
              Pending Leave Requests
            </h2>
          </div>
          {data?.pendingLeave?.length ? (
            <div className="space-y-3">
              {data.pendingLeave.filter(l => l && l.id).map((leave) => (
                <div key={leave.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div>
                    <p className="text-white text-sm font-medium">
                      {leave.employee?.firstName || 'Unknown'} {leave.employee?.lastName || 'Employee'}
                    </p>
                    <p className="text-gray-500 text-xs capitalize">{leave.type || 'General'} Leave</p>
                  </div>
                  <div className="text-right">
                    <p className="text-amber-400 font-medium">{leave.days} days</p>
                    <p className="text-gray-500 text-xs">
                      {new Date(leave.startDate).toLocaleDateString()}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <CheckCircle className="w-8 h-8 mx-auto mb-2 text-green-400 opacity-50" />
              <p>No pending requests</p>
            </div>
          )}
        </div>
      </div>

      {/* Departments */}
      {data?.departments && data.departments.length > 0 && (
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <Building2 className="w-5 h-5 text-brand" />
            Departments
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {data.departments.map((dept) => (
              <div key={dept.id} className="p-4 bg-white/5 rounded-lg border border-white/10">
                <p className="text-white font-medium">{dept.name}</p>
                <p className="text-gray-500 text-xs">{dept.code}</p>
                <p className="text-brand mt-2">{dept.headCount} employees</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Add Employee Modal */}
      <ERPModal isOpen={showModal} onClose={() => setShowModal(false)} title="Add New Employee">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">First Name *</label>
              <input
                type="text"
                value={formData.firstName}
                onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Last Name *</label>
              <input
                type="text"
                value={formData.lastName}
                onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
                required
              />
            </div>
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Email *</label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Position</label>
            <input
              type="text"
              value={formData.position}
              onChange={(e) => setFormData({ ...formData, position: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
              placeholder="e.g., Software Engineer"
            />
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Department</label>
            <select
              value={formData.departmentId}
              onChange={(e) => setFormData({ ...formData, departmentId: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
            >
              <option value="" className="bg-brand-bg">Select department...</option>
              {departments.map((dept) => (
                <option key={dept.id} value={dept.id} className="bg-brand-bg">
                  {dept.name}
                </option>
              ))}
            </select>
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Employment Type</label>
              <select
                value={formData.employmentType}
                onChange={(e) => setFormData({ ...formData, employmentType: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
              >
                <option value="full-time" className="bg-brand-bg">Full-Time</option>
                <option value="part-time" className="bg-brand-bg">Part-Time</option>
                <option value="contractor" className="bg-brand-bg">Contractor</option>
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Salary</label>
              <input
                type="number"
                step="0.01"
                min="0"
                value={formData.salary}
                onChange={(e) => setFormData({ ...formData, salary: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-secondary/50 focus:outline-none"
                placeholder="Annual salary"
              />
            </div>
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="flex-1 px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              {submitting ? 'Adding...' : 'Add Employee'}
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
