'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Receipt, Plus, ArrowUpRight, ArrowDownRight,
  Loader2, Search, Filter, Calendar, Download
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Transaction {
  id: string;
  type: string;
  description: string;
  amount: number;
  date: string;
  status: string;
  reference?: string;
  account?: { name: string; code: string };
}

interface Account {
  id: string;
  name: string;
  code: string;
  type: string;
}

export default function TransactionsPage() {
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  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({
    accountId: '',
    type: 'expense',
    description: '',
    amount: '',
    reference: '',
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const [txRes, accRes] = await Promise.all([
        fetch('/api/erp/finance?type=transactions&limit=100'),
        fetch('/api/erp/finance?type=accounts'),
      ]);
      const txData = await txRes.json();
      const accData = await accRes.json();
      setTransactions(txData.transactions || []);
      setAccounts(accData.accounts || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

    setSubmitting(true);
    try {
      const amount = formData.type === 'expense' || formData.type === 'payment'
        ? -Math.abs(parseFloat(formData.amount))
        : Math.abs(parseFloat(formData.amount));

      const res = await fetch('/api/erp/finance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'transaction',
          data: {
            accountId: formData.accountId,
            type: formData.type,
            description: formData.description,
            amount,
            reference: formData.reference || null,
            date: new Date().toISOString(),
            status: 'completed',
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({ accountId: '', type: 'expense', description: '', amount: '', reference: '' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create transaction:', error);
    } finally {
      setSubmitting(false);
    }
  };

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

  const formatDate = (date: string) =>
    new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });

  const transactionTypes = ['all', 'income', 'expense', 'transfer', 'payment', 'receipt'];

  const filteredTransactions = transactions.filter(tx => {
    const matchesSearch = (tx.description?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (tx.reference?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesFilter = filterType === 'all' || tx.type === filterType;
    return matchesSearch && matchesFilter;
  });

  const totals = filteredTransactions.reduce(
    (acc, tx) => {
      if ((tx.amount ?? 0) >= 0) acc.income += tx.amount ?? 0;
      else acc.expense += Math.abs(tx.amount ?? 0);
      return acc;
    },
    { income: 0, expense: 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">
            <Receipt className="w-7 h-7 text-brand" />
            Transactions
          </h1>
          <p className="text-gray-400 mt-1">View and manage all financial transactions</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 Transaction
        </button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Income</p>
          <p className="text-xl font-bold text-green-400">{formatCurrency(totals.income)}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Expenses</p>
          <p className="text-xl font-bold text-red-400">{formatCurrency(totals.expense)}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Net</p>
          <p className={`text-xl font-bold ${totals.income - totals.expense >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {formatCurrency(totals.income - totals.expense)}
          </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 transactions..."
            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 overflow-x-auto pb-2">
          {transactionTypes.map((type) => (
            <button
              key={type}
              onClick={() => setFilterType(type)}
              className={`px-3 py-2 rounded-lg text-sm capitalize whitespace-nowrap transition-colors ${
                filterType === type
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {type}
            </button>
          ))}
        </div>
      </div>

      {/* Transactions List */}
      {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">Date</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Description</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Account</th>
                  <th className="text-left p-4 text-sm text-gray-400 font-medium">Type</th>
                  <th className="text-right p-4 text-sm text-gray-400 font-medium">Amount</th>
                </tr>
              </thead>
              <tbody>
                {filteredTransactions.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="p-8 text-center text-gray-500">
                      No transactions found
                    </td>
                  </tr>
                ) : (
                  filteredTransactions.filter(tx => tx && tx.id).map((tx, index) => (
                    <motion.tr
                      key={tx.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 text-sm text-gray-400">
                        {formatDate(tx.date)}
                      </td>
                      <td className="p-4">
                        <p className="text-white">{tx.description || 'No description'}</p>
                        {tx.reference && (
                          <p className="text-xs text-gray-500">Ref: {tx.reference}</p>
                        )}
                      </td>
                      <td className="p-4 text-sm text-gray-400">
                        {tx.account?.name || 'Unknown'}
                      </td>
                      <td className="p-4">
                        <span className="text-xs px-2 py-1 rounded capitalize bg-white/5 text-gray-400">
                          {tx.type || 'transaction'}
                        </span>
                      </td>
                      <td className="p-4 text-right">
                        <span className={`flex items-center justify-end gap-1 font-medium ${
                          (tx.amount ?? 0) >= 0 ? 'text-green-400' : 'text-red-400'
                        }`}>
                          {(tx.amount ?? 0) >= 0 ? (
                            <ArrowUpRight className="w-4 h-4" />
                          ) : (
                            <ArrowDownRight className="w-4 h-4" />
                          )}
                          {formatCurrency(Math.abs(tx.amount ?? 0))}
                        </span>
                      </td>
                    </motion.tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* New Transaction Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="New Transaction"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Account</label>
            <select
              value={formData.accountId}
              onChange={(e) => setFormData({ ...formData, accountId: 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 account...</option>
              {accounts.map((acc) => (
                <option key={acc.id} value={acc.id}>
                  {acc.code} - {acc.name}
                </option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">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="income">Income</option>
                <option value="expense">Expense</option>
                <option value="transfer">Transfer</option>
                <option value="payment">Payment</option>
                <option value="receipt">Receipt</option>
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">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>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Description</label>
            <input
              type="text"
              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"
              placeholder="Transaction description"
              required
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Reference (Optional)</label>
            <input
              type="text"
              value={formData.reference}
              onChange={(e) => setFormData({ ...formData, reference: 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="Invoice #, PO #, etc."
            />
          </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.accountId || !formData.description || !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 Transaction
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
