'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  ScrollText, Plus, AlertTriangle, CheckCircle, Clock,
  Loader2, Search, Calendar, DollarSign, Building2
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Contract {
  id: string;
  title: string;
  contractNumber: string;
  type: string;
  party?: string;
  value?: number;
  startDate: string;
  endDate?: string;
  status: string;
  description?: string;
  autoRenew?: boolean;
  createdAt: string;
}

export default function ContractsPage() {
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [formData, setFormData] = useState({
    title: '',
    type: 'service',
    party: '',
    value: '',
    startDate: '',
    endDate: '',
    description: '',
    autoRenew: false,
  });

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

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

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

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/documents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'contract',
          data: {
            contractNumber: `CON-${Date.now().toString().slice(-8)}`,
            title: formData.title,
            type: formData.type,
            party: formData.party || null,
            value: formData.value ? parseFloat(formData.value) : null,
            startDate: new Date(formData.startDate),
            endDate: formData.endDate ? new Date(formData.endDate) : null,
            description: formData.description || null,
            autoRenew: formData.autoRenew,
            status: 'active',
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          title: '',
          type: 'service',
          party: '',
          value: '',
          startDate: '',
          endDate: '',
          description: '',
          autoRenew: false,
        });
        fetchContracts();
      }
    } catch (error) {
      console.error('Failed to create contract:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const formatCurrency = (value?: number) => {
    if (!value) return 'N/A';
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value);
  };

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

  const getDaysUntilExpiry = (endDate?: string) => {
    if (!endDate) return null;
    const days = Math.ceil((new Date(endDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24));
    return days;
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'bg-green-500/10 text-green-400';
      case 'pending': return 'bg-yellow-500/10 text-yellow-400';
      case 'expired': return 'bg-red-500/10 text-red-400';
      case 'terminated': return 'bg-gray-500/10 text-gray-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'service': return 'bg-brand-deep/10 text-brand';
      case 'vendor': return 'bg-brand-secondary/10 text-brand-secondary-light';
      case 'employment': return 'bg-blue-500/10 text-blue-400';
      case 'nda': return 'bg-orange-500/10 text-orange-400';
      case 'lease': return 'bg-green-500/10 text-green-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const filteredContracts = contracts.filter(contract => {
    const matchesSearch = (contract.title?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (contract.party?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (contract.contractNumber?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesFilter = filterStatus === 'all' || contract.status === filterStatus;
    return matchesSearch && matchesFilter;
  });

  const activeValue = contracts
    .filter(c => c.status === 'active')
    .reduce((sum, c) => sum + (c.value || 0), 0);

  const expiringCount = contracts.filter(c => {
    const days = getDaysUntilExpiry(c.endDate);
    return days !== null && days > 0 && days <= 30 && c.status === 'active';
  }).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">
            <ScrollText className="w-7 h-7 text-brand" />
            Contracts
          </h1>
          <p className="text-gray-400 mt-1">Manage contracts and agreements</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 Contract
        </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 Contracts</p>
          <p className="text-xl font-bold text-white">{contracts.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <CheckCircle className="w-4 h-4 text-green-400" />
            <p className="text-sm text-gray-400">Active</p>
          </div>
          <p className="text-xl font-bold text-green-400">
            {contracts.filter(c => c.status === 'active').length}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-yellow-400" />
            <p className="text-sm text-gray-400">Expiring Soon</p>
          </div>
          <p className="text-xl font-bold text-yellow-400">{expiringCount}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <DollarSign className="w-4 h-4 text-brand" />
            <p className="text-sm text-gray-400">Active Value</p>
          </div>
          <p className="text-xl font-bold text-brand">{formatCurrency(activeValue)}</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 contracts..."
            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">
          {['all', 'active', 'pending', 'expired', 'terminated'].map((status) => (
            <button
              key={status}
              onClick={() => setFilterStatus(status)}
              className={`px-3 py-2 rounded-lg text-sm capitalize transition-colors ${
                filterStatus === status
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {status}
            </button>
          ))}
        </div>
      </div>

      {/* Contracts List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="space-y-4">
          {filteredContracts.length === 0 ? (
            <div className="text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No contracts found
            </div>
          ) : (
            filteredContracts.map((contract, index) => {
              const daysUntilExpiry = getDaysUntilExpiry(contract.endDate);
              const isExpiringSoon = daysUntilExpiry !== null && daysUntilExpiry > 0 && daysUntilExpiry <= 30;
              
              return (
                <motion.div
                  key={contract.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.03 }}
                  className={`p-4 bg-white/5 border rounded-lg ${
                    isExpiringSoon ? 'border-yellow-500/30' : 'border-white/10'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-brand-deep/10 rounded-lg">
                        <ScrollText className="w-5 h-5 text-brand" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <p className="text-xs font-mono text-gray-500">{contract.contractNumber}</p>
                          {isExpiringSoon && (
                            <span className="flex items-center gap-1 text-xs text-yellow-400">
                              <AlertTriangle className="w-3 h-3" />
                              Expires in {daysUntilExpiry} days
                            </span>
                          )}
                        </div>
                        <h3 className="font-semibold text-white">{contract.title}</h3>
                        <div className="flex items-center gap-3 mt-1">
                          <span className={`text-xs px-2 py-0.5 rounded capitalize ${getTypeColor(contract.type)}`}>
                            {contract.type}
                          </span>
                          <span className={`text-xs px-2 py-0.5 rounded capitalize ${getStatusColor(contract.status)}`}>
                            {contract.status}
                          </span>
                          {contract.autoRenew && (
                            <span className="text-xs px-2 py-0.5 rounded bg-brand-secondary/10 text-brand-secondary-light">
                              Auto-renew
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="text-right">
                      {contract.value && (
                        <p className="text-lg font-bold text-white">{formatCurrency(contract.value)}</p>
                      )}
                      {contract.party && (
                        <p className="text-sm text-gray-400 flex items-center justify-end gap-1">
                          <Building2 className="w-3 h-3" />
                          {contract.party}
                        </p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-4 mt-3 pt-3 border-t border-white/5 text-xs text-gray-500">
                    <span className="flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      Start: {formatDate(contract.startDate)}
                    </span>
                    {contract.endDate && (
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        End: {formatDate(contract.endDate)}
                      </span>
                    )}
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      )}

      {/* New Contract Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Create New Contract"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Contract Title</label>
            <input
              type="text"
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: 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-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="service">Service Agreement</option>
                <option value="vendor">Vendor Contract</option>
                <option value="employment">Employment Contract</option>
                <option value="nda">NDA</option>
                <option value="lease">Lease Agreement</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Counterparty</label>
              <input
                type="text"
                value={formData.party}
                onChange={(e) => setFormData({ ...formData, party: 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="Company or individual name"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Contract Value</label>
            <input
              type="number"
              step="0.01"
              value={formData.value}
              onChange={(e) => setFormData({ ...formData, value: 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"
            />
          </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</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>
            <label className="block text-sm text-gray-400 mb-1">Description</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={3}
            />
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="autoRenew"
              checked={formData.autoRenew}
              onChange={(e) => setFormData({ ...formData, autoRenew: e.target.checked })}
              className="w-4 h-4 rounded border-white/10 bg-white/5 text-brand-deep focus:ring-brand-deep"
            />
            <label htmlFor="autoRenew" className="text-sm text-gray-400">
              Auto-renew contract
            </label>
          </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.title || !formData.startDate}
              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 Contract
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
