'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  CreditCard, Plus, TrendingUp, TrendingDown, Building2,
  DollarSign, Loader2, Search, Filter
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Account {
  id: string;
  code: string;
  name: string;
  type: 'asset' | 'liability' | 'revenue' | 'expense' | 'equity';
  balance: number;
  currency: string;
  isActive: boolean;
  description?: string;
  _count?: { transactions: number };
}

export default function AccountsPage() {
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [formData, setFormData] = useState({
    code: '',
    name: '',
    type: 'asset',
    description: '',
    currency: 'USD',
  });

  const fetchAccounts = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/erp/finance?type=accounts');
      const data = await res.json();
      setAccounts(data.accounts || []);
    } catch (error) {
      console.error('Failed to fetch accounts:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/finance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'account',
          data: {
            ...formData,
            balance: 0,
            isActive: true,
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({ code: '', name: '', type: 'asset', description: '', currency: 'USD' });
        fetchAccounts();
      }
    } catch (error) {
      console.error('Failed to create account:', error);
    } finally {
      setSubmitting(false);
    }
  };

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

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'asset': return 'text-green-400 bg-green-500/10';
      case 'liability': return 'text-red-400 bg-red-500/10';
      case 'revenue': return 'text-brand bg-brand-deep/10';
      case 'expense': return 'text-orange-400 bg-orange-500/10';
      case 'equity': return 'text-brand-secondary-light bg-brand-secondary/10';
      default: return 'text-gray-400 bg-gray-500/10';
    }
  };

  const filteredAccounts = accounts.filter(account => {
    const matchesSearch = account.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         account.code.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesFilter = filterType === 'all' || account.type === filterType;
    return matchesSearch && matchesFilter;
  });

  const accountTypes = ['all', 'asset', 'liability', 'revenue', 'expense', 'equity'];

  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">
            <CreditCard className="w-7 h-7 text-brand" />
            Chart of Accounts
          </h1>
          <p className="text-gray-400 mt-1">Manage your financial accounts</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 Account
        </button>
      </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 accounts..."
            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">
          {accountTypes.map((type) => (
            <button
              key={type}
              onClick={() => setFilterType(type)}
              className={`px-3 py-2 rounded-lg text-sm capitalize transition-colors ${
                filterType === type
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {type}
            </button>
          ))}
        </div>
      </div>

      {/* Accounts 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">
          {filteredAccounts.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              No accounts found. Create your first account to get started.
            </div>
          ) : (
            filteredAccounts.map((account, index) => (
              <motion.div
                key={account.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 hover:border-brand-deep/30 transition-colors"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className={`p-2 rounded-lg ${getTypeColor(account.type)}`}>
                      {account.type === 'asset' || account.type === 'revenue' ? (
                        <TrendingUp className="w-5 h-5" />
                      ) : account.type === 'liability' || account.type === 'expense' ? (
                        <TrendingDown className="w-5 h-5" />
                      ) : (
                        <Building2 className="w-5 h-5" />
                      )}
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-mono text-gray-500">{account.code}</span>
                        <h3 className="font-semibold text-white">{account.name}</h3>
                      </div>
                      <div className="flex items-center gap-3 mt-1">
                        <span className={`text-xs px-2 py-0.5 rounded capitalize ${getTypeColor(account.type)}`}>
                          {account.type}
                        </span>
                        {account._count && (
                          <span className="text-xs text-gray-500">
                            {account._count.transactions} transactions
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`text-lg font-bold ${account.balance >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                      {formatCurrency(account.balance)}
                    </p>
                    <p className="text-xs text-gray-500">{account.currency}</p>
                  </div>
                </div>
              </motion.div>
            ))
          )}
        </div>
      )}

      {/* New Account Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Create New Account"
      >
        <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">Account Code</label>
              <input
                type="text"
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: 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., 1001"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Account 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="asset">Asset</option>
                <option value="liability">Liability</option>
                <option value="revenue">Revenue</option>
                <option value="expense">Expense</option>
                <option value="equity">Equity</option>
              </select>
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Account 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., Cash & Bank"
              required
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Description (Optional)</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: 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}
              placeholder="Brief description of this account"
            />
          </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.code || !formData.name}
              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 Account
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
