'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  PiggyBank, Plus, TrendingUp, AlertTriangle,
  Loader2, Search, CheckCircle, XCircle
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Budget {
  id: string;
  name: string;
  category: string;
  amount: number;
  spent: number;
  period: string;
  startDate: string;
  endDate: string;
  status: string;
}

export default function BudgetsPage() {
  const [budgets, setBudgets] = useState<Budget[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    category: 'operations',
    amount: '',
    period: 'monthly',
    startDate: new Date().toISOString().split('T')[0],
    endDate: '',
  });

  const fetchBudgets = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/erp/finance');
      const data = await res.json();
      // Get budgets from summary or create empty array
      const budgetData = data.budgets || [];
      setBudgets(budgetData);
    } catch (error) {
      console.error('Failed to fetch budgets:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/finance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'budget',
          data: {
            name: formData.name,
            category: formData.category,
            amount: parseFloat(formData.amount),
            spent: 0,
            period: formData.period,
            startDate: new Date(formData.startDate),
            endDate: formData.endDate ? new Date(formData.endDate) : null,
            status: 'active',
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          name: '',
          category: 'operations',
          amount: '',
          period: 'monthly',
          startDate: new Date().toISOString().split('T')[0],
          endDate: '',
        });
        fetchBudgets();
      }
    } catch (error) {
      console.error('Failed to create budget:', error);
    } finally {
      setSubmitting(false);
    }
  };

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

  const getUtilization = (budget: Budget) => {
    if (!budget.amount) return 0;
    return Math.min(100, ((budget.spent || 0) / budget.amount) * 100);
  };

  const getStatusColor = (utilization: number) => {
    if (utilization >= 100) return 'bg-red-500';
    if (utilization >= 80) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  const categories = ['operations', 'marketing', 'development', 'hr', 'infrastructure', 'other'];

  const totalBudget = budgets.reduce((sum, b) => sum + (b.amount || 0), 0);
  const totalSpent = budgets.reduce((sum, b) => sum + (b.spent || 0), 0);
  const overBudgetCount = budgets.filter(b => (b.spent || 0) > (b.amount || 0)).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">
            <PiggyBank className="w-7 h-7 text-brand" />
            Budget Management
          </h1>
          <p className="text-gray-400 mt-1">Track and manage departmental budgets</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 Budget
        </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 Budget</p>
          <p className="text-xl font-bold text-white">{formatCurrency(totalBudget)}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Spent</p>
          <p className="text-xl font-bold text-brand">{formatCurrency(totalSpent)}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Remaining</p>
          <p className={`text-xl font-bold ${totalBudget - totalSpent >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {formatCurrency(totalBudget - totalSpent)}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Over Budget</p>
          <p className={`text-xl font-bold ${overBudgetCount > 0 ? 'text-red-400' : 'text-green-400'}`}>
            {overBudgetCount} {overBudgetCount === 1 ? 'budget' : 'budgets'}
          </p>
        </div>
      </div>

      {/* Budgets List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="grid gap-4">
          {budgets.length === 0 ? (
            <div className="text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No budgets found. Create your first budget to start tracking spending.
            </div>
          ) : (
            budgets.map((budget, index) => {
              const utilization = getUtilization(budget);
              return (
                <motion.div
                  key={budget.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.05 }}
                  className="p-4 bg-white/5 border border-white/10 rounded-lg"
                >
                  <div className="flex items-center justify-between mb-3">
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-semibold text-white">{budget.name}</h3>
                        {utilization >= 100 && (
                          <AlertTriangle className="w-4 h-4 text-red-400" />
                        )}
                      </div>
                      <div className="flex items-center gap-3 mt-1">
                        <span className="text-xs px-2 py-0.5 rounded capitalize bg-brand-deep/10 text-brand">
                          {budget.category}
                        </span>
                        <span className="text-xs text-gray-500 capitalize">
                          {budget.period}
                        </span>
                        <span className={`text-xs px-2 py-0.5 rounded capitalize ${
                          budget.status === 'active' ? 'bg-green-500/10 text-green-400' : 'bg-gray-500/10 text-gray-400'
                        }`}>
                          {budget.status}
                        </span>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-lg font-bold text-white">
                        {formatCurrency(budget.spent || 0)} <span className="text-gray-500 text-sm font-normal">/ {formatCurrency(budget.amount)}</span>
                      </p>
                      <p className={`text-sm ${utilization >= 100 ? 'text-red-400' : utilization >= 80 ? 'text-yellow-400' : 'text-green-400'}`}>
                        {utilization.toFixed(1)}% used
                      </p>
                    </div>
                  </div>
                  <div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
                    <div
                      className={`h-full transition-all duration-500 ${getStatusColor(utilization)}`}
                      style={{ width: `${Math.min(100, utilization)}%` }}
                    />
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      )}

      {/* New Budget Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Create New Budget"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Budget Name</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: 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"
              placeholder="e.g., Q1 Marketing Budget"
              required
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Category</label>
              <select
                value={formData.category}
                onChange={(e) => setFormData({ ...formData, category: 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"
              >
                {categories.map((cat) => (
                  <option key={cat} value={cat} className="capitalize">
                    {cat.charAt(0).toUpperCase() + cat.slice(1)}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Period</label>
              <select
                value={formData.period}
                onChange={(e) => setFormData({ ...formData, period: 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="monthly">Monthly</option>
                <option value="quarterly">Quarterly</option>
                <option value="yearly">Yearly</option>
                <option value="custom">Custom</option>
              </select>
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Budget Amount</label>
            <input
              type="number"
              step="0.01"
              value={formData.amount}
              onChange={(e) => setFormData({ ...formData, amount: 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"
              placeholder="0.00"
              required
            />
          </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 (Optional)</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"
              />
            </div>
          </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.name || !formData.amount}
              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" />}
              Create Budget
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
