'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import {
  FileText,
  Search,
  Loader2,
  MoreHorizontal,
  Building2,
  Clock,
  CheckCircle,
  XCircle,
  Send,
  AlertTriangle,
} from 'lucide-react';

interface Quote {
  id: string;
  quoteNumber: string;
  customerId: string;
  status: string;
  validUntil: string;
  subtotal: number;
  discount: number;
  tax: number;
  total: number;
  customer: { name: string };
  items: Array<{ id: string }>;
  createdAt: string;
}

const statusConfig: Record<string, { icon: React.ComponentType<{ className?: string }>; color: string }> = {
  draft: { icon: FileText, color: 'text-gray-400 bg-gray-500/20' },
  sent: { icon: Send, color: 'text-blue-400 bg-blue-500/20' },
  accepted: { icon: CheckCircle, color: 'text-green-400 bg-green-500/20' },
  rejected: { icon: XCircle, color: 'text-red-400 bg-red-500/20' },
  expired: { icon: AlertTriangle, color: 'text-yellow-400 bg-yellow-500/20' },
};

export default function QuotesPage() {
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('');

  useEffect(() => {
    const fetchQuotes = async () => {
      try {
        const res = await fetch('/api/erp/crm?type=quotes');
        if (res.ok) {
          const data = await res.json();
          setQuotes(data.quotes || []);
        }
      } catch (err) {
        console.error('Failed to fetch quotes:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchQuotes();
  }, []);

  const filteredQuotes = quotes.filter((q) => {
    const matchesSearch =
      q.quoteNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      q.customer.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = !filterStatus || q.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-brand-deep" />
      </div>
    );
  }

  const totalPending = quotes
    .filter((q) => q.status === 'sent')
    .reduce((sum, q) => sum + q.total, 0);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Quotes</h1>
          <p className="text-gray-400">
            Pending Value: <span className="text-yellow-400 font-semibold">${totalPending.toLocaleString()}</span>
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-4">
        <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-5 h-5 text-gray-500" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search quotes..."
              className="w-full pl-10 pr-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
            />
          </div>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
          >
            <option value="">All Statuses</option>
            <option value="draft">Draft</option>
            <option value="sent">Sent</option>
            <option value="accepted">Accepted</option>
            <option value="rejected">Rejected</option>
            <option value="expired">Expired</option>
          </select>
        </div>
      </div>

      {/* Quotes Table */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-brand-bg-surface/30 bg-white/5">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Quote #</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Customer</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Status</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Items</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Total</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Valid Until</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-brand-bg-surface/20">
              {filteredQuotes.length === 0 ? (
                <tr>
                  <td colSpan={7} className="py-12 text-center text-gray-500">
                    No quotes found
                  </td>
                </tr>
              ) : (
                filteredQuotes.map((quote) => {
                  const statusInfo = statusConfig[quote.status] || statusConfig.draft;
                  const StatusIcon = statusInfo.icon;
                  const isExpired = new Date(quote.validUntil) < new Date() && quote.status === 'sent';

                  return (
                    <tr key={quote.id} className="hover:bg-white/5 transition-colors">
                      <td className="py-3 px-4 font-medium text-white">{quote.quoteNumber}</td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-gray-300">
                          <Building2 className="w-4 h-4 text-gray-500" />
                          {quote.customer.name}
                        </div>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs ${isExpired ? 'text-yellow-400 bg-yellow-500/20' : statusInfo.color}`}>
                          <StatusIcon className="w-3 h-3" />
                          {isExpired ? 'expired' : quote.status}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center text-gray-400">{quote.items.length}</td>
                      <td className="py-3 px-4 text-right text-green-400 font-medium">
                        ${quote.total.toLocaleString()}
                      </td>
                      <td className="py-3 px-4 text-right">
                        <span className={`flex items-center gap-1 justify-end text-sm ${isExpired ? 'text-red-400' : 'text-gray-500'}`}>
                          <Clock className="w-4 h-4" />
                          {new Date(quote.validUntil).toLocaleDateString()}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <button className="p-1 text-gray-500 hover:text-brand">
                          <MoreHorizontal className="w-5 h-5" />
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
