'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  UserCircle, Plus, Search, Filter, Mail, Phone, Building2,
  MapPin, Globe, MoreVertical, Edit, Trash2, Eye, X, Loader2,
  FileSpreadsheet, TrendingUp, Calendar, Ban, RotateCcw, AlertTriangle, Shield
} from 'lucide-react';
import Link from 'next/link';

interface Customer {
  id: string;
  customerNumber: string;
  name: string;
  email?: string;
  phone?: string;
  address?: string;
  city?: string;
  state?: string;
  country?: string;
  industry?: string;
  website?: string;
  status: string;
  createdAt: string;
  _count?: {
    salesOrders: number;
    opportunities: number;
    contacts: number;
  };
  contacts?: any[];
}

export default function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    country: '',
    postalCode: '',
    industry: '',
    website: '',
    notes: ''
  });

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

  const fetchCustomers = async () => {
    try {
      const res = await fetch(`/api/erp/crm/customers?search=${search}`);
      const data = await res.json();
      setCustomers(data.customers || []);
    } catch (error) {
      console.error('Failed to fetch customers:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchCustomers();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const res = await fetch('/api/erp/crm/customers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (res.ok) {
        setShowAddModal(false);
        setFormData({
          name: '', email: '', phone: '', address: '', city: '',
          state: '', country: '', postalCode: '', industry: '', website: '', notes: ''
        });
        fetchCustomers();
      }
    } catch (error) {
      console.error('Failed to create customer:', error);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string, customerName: string) => {
    try {
      // Pre-flight guardrail check
      const checkRes = await fetch(`/api/gfs/guardrails?check=delete&entity=customer&id=${id}`);
      const guardrail = await checkRes.json();

      if (guardrail.hasHistory) {
        // Has linked records — offer Mark Inactive instead
        const totalLinked = Object.values(guardrail.linkedRecords as Record<string, number>)
          .reduce((s: number, v: number) => s + v, 0);
        const doInactivate = confirm(
          `⚠️ GAAP Guardrail: Cannot delete "${customerName}" — ${totalLinked} linked record(s) exist.\n\n` +
          `Linked: ${guardrail.linkedRecords.salesOrders} orders, ${guardrail.linkedRecords.invoices} invoices, ` +
          `${guardrail.linkedRecords.opportunities} opportunities, ${guardrail.linkedRecords.quotes} quotes, ` +
          `${guardrail.linkedRecords.contacts} contacts, ${guardrail.linkedRecords.leads} leads.\n\n` +
          `Click OK to mark as INACTIVE (hides from active lists, preserves all data for audits/tax).`
        );
        if (doInactivate) {
          await fetch(`/api/erp/crm/customers/${id}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'inactivate', reason: 'Operator marked inactive via CRM UI' }),
          });
          fetchCustomers();
        }
      } else {
        // No linked records — safe to hard delete
        if (!confirm(`Delete "${customerName}"? This customer has no linked transactions and will be permanently removed.`)) return;
        await fetch(`/api/erp/crm/customers/${id}`, { method: 'DELETE' });
        fetchCustomers();
      }
    } catch (error) {
      console.error('Failed to process customer action:', error);
    }
  };

  const handleReactivate = async (id: string) => {
    try {
      await fetch(`/api/erp/crm/customers/${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'reactivate', reason: 'Reactivated via CRM UI' }),
      });
      fetchCustomers();
    } catch (error) {
      console.error('Failed to reactivate customer:', error);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-pink-500/20">
            <UserCircle className="w-6 h-6 text-pink-400" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Customers</h1>
            <p className="text-gray-400">{customers.length} total customers</p>
          </div>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded-lg flex items-center gap-2 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Customer
        </button>
      </div>

      {/* Search */}
      <form onSubmit={handleSearch} className="flex gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search customers..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-brand-bg-elevated border border-brand-deep/30 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-pink-500/50"
          />
        </div>
        <button
          type="submit"
          className="px-4 py-2 bg-brand-bg-elevated border border-brand-deep/30 rounded-lg text-gray-300 hover:text-white hover:border-pink-500/50 transition-colors"
        >
          Search
        </button>
      </form>

      {/* Customers List */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-pink-400" />
        </div>
      ) : customers.length === 0 ? (
        <div className="glass-card p-12 text-center">
          <UserCircle className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-white mb-2">No Customers Yet</h3>
          <p className="text-gray-400 mb-6">Start building your customer base</p>
          <button
            onClick={() => setShowAddModal(true)}
            className="px-6 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded-lg"
          >
            Add Your First Customer
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {customers.map((customer, idx) => (
            <motion.div
              key={customer.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.05 }}
              className="glass-card p-4 hover:border-pink-500/30 transition-all group"
            >
              <div className="flex items-start justify-between mb-3">
                <div>
                  <h3 className="font-semibold text-white group-hover:text-pink-300 transition-colors">
                    {customer.name}
                  </h3>
                  <p className="text-sm text-gray-500">{customer.customerNumber}</p>
                </div>
                <span className={`px-2 py-0.5 text-xs rounded-full ${
                  customer.status === 'active' 
                    ? 'bg-green-500/20 text-green-400' 
                    : 'bg-gray-500/20 text-gray-400'
                }`}>
                  {customer.status}
                </span>
              </div>

              <div className="space-y-2 text-sm text-gray-400 mb-4">
                {customer.email && (
                  <div className="flex items-center gap-2">
                    <Mail className="w-3.5 h-3.5" />
                    <span className="truncate">{customer.email}</span>
                  </div>
                )}
                {customer.phone && (
                  <div className="flex items-center gap-2">
                    <Phone className="w-3.5 h-3.5" />
                    <span>{customer.phone}</span>
                  </div>
                )}
                {customer.industry && (
                  <div className="flex items-center gap-2">
                    <Building2 className="w-3.5 h-3.5" />
                    <span>{customer.industry}</span>
                  </div>
                )}
              </div>

              <div className="flex items-center justify-between pt-3 border-t border-brand-deep/20">
                <div className="flex items-center gap-4 text-xs text-gray-500">
                  <span className="flex items-center gap-1">
                    <FileSpreadsheet className="w-3.5 h-3.5" />
                    {customer._count?.salesOrders || 0} orders
                  </span>
                  <span className="flex items-center gap-1">
                    <TrendingUp className="w-3.5 h-3.5" />
                    {customer._count?.opportunities || 0} opps
                  </span>
                </div>
                {customer.status === 'inactive' ? (
                  <button
                    onClick={() => handleReactivate(customer.id)}
                    className="p-1.5 text-gray-500 hover:text-green-400 transition-colors"
                    title="Reactivate Customer"
                  >
                    <RotateCcw className="w-4 h-4" />
                  </button>
                ) : (
                  <button
                    onClick={() => handleDelete(customer.id, customer.name)}
                    className="p-1.5 text-gray-500 hover:text-amber-400 transition-colors"
                    title="Delete / Mark Inactive (GAAP enforced)"
                  >
                    <Ban className="w-4 h-4" />
                  </button>
                )}
              </div>
            </motion.div>
          ))}
        </div>
      )}

      {/* Add Customer Modal */}
      <AnimatePresence>
        {showAddModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
            onClick={() => setShowAddModal(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-brand-bg-elevated border border-brand-deep/30 rounded-xl w-full max-w-lg max-h-[90vh] overflow-y-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold text-white">Add New Customer</h2>
                  <button
                    onClick={() => setShowAddModal(false)}
                    className="p-1 text-gray-400 hover:text-white"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <form onSubmit={handleSubmit} className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Company Name *</label>
                    <input
                      type="text"
                      required
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Email</label>
                      <input
                        type="email"
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Phone</label>
                      <input
                        type="tel"
                        value={formData.phone}
                        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Industry</label>
                    <select
                      value={formData.industry}
                      onChange={(e) => setFormData({ ...formData, industry: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                    >
                      <option value="">Select Industry</option>
                      <option value="Technology">Technology</option>
                      <option value="Healthcare">Healthcare</option>
                      <option value="Finance">Finance</option>
                      <option value="Manufacturing">Manufacturing</option>
                      <option value="Retail">Retail</option>
                      <option value="Services">Services</option>
                      <option value="Other">Other</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Website</label>
                    <input
                      type="url"
                      value={formData.website}
                      onChange={(e) => setFormData({ ...formData, website: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      placeholder="https://"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Address</label>
                    <input
                      type="text"
                      value={formData.address}
                      onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                    />
                  </div>

                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">City</label>
                      <input
                        type="text"
                        value={formData.city}
                        onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">State</label>
                      <input
                        type="text"
                        value={formData.state}
                        onChange={(e) => setFormData({ ...formData, state: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Country</label>
                      <input
                        type="text"
                        value={formData.country}
                        onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Notes</label>
                    <textarea
                      value={formData.notes}
                      onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                      rows={3}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-pink-500 resize-none"
                    />
                  </div>

                  <div className="flex justify-end gap-3 pt-4">
                    <button
                      type="button"
                      onClick={() => setShowAddModal(false)}
                      className="px-4 py-2 border border-brand-deep/30 rounded-lg text-gray-300 hover:text-white transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      disabled={saving}
                      className="px-4 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded-lg flex items-center gap-2 disabled:opacity-50"
                    >
                      {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                      Add Customer
                    </button>
                  </div>
                </form>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
