'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Plus,
  Search,
  Building2,
  Mail,
  Phone,
  Globe,
  X,
  Loader2,
  MoreHorizontal,
  TrendingUp,
  FileText,
} from 'lucide-react';

interface Customer {
  id: string;
  customerNumber: string;
  name: string;
  type: string;
  industry: string | null;
  website: string | null;
  phone: string | null;
  email: string | null;
  status: string;
  contacts: Array<{ firstName: string; lastName: string; email: string | null }>;
  _count: { opportunities: number; salesOrders: number };
}

export default function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({
    name: '',
    type: 'company',
    industry: '',
    website: '',
    phone: '',
    email: '',
  });

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

  useEffect(() => {
    fetchCustomers();

    const params = new URLSearchParams(window.location.search);
    if (params.get('new') === '1') {
      setModalOpen(true);
      window.history.replaceState({}, '', '/apps/crm/customers');
    }
  }, []);

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

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

      if (res.ok) {
        setModalOpen(false);
        setForm({ name: '', type: 'company', industry: '', website: '', phone: '', email: '' });
        fetchCustomers();
      }
    } catch (err) {
      console.error('Failed to create customer:', err);
    } finally {
      setSaving(false);
    }
  };

  const filteredCustomers = customers.filter((c) =>
    c.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    c.customerNumber.toLowerCase().includes(searchTerm.toLowerCase())
  );

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

  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">Customers</h1>
          <p className="text-gray-400">Manage your customer accounts</p>
        </div>
        <button
          onClick={() => setModalOpen(true)}
          className="flex items-center gap-2 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white px-4 py-2 rounded-lg hover:opacity-90 transition-opacity"
        >
          <Plus className="w-5 h-5" />
          New Customer
        </button>
      </div>

      {/* Search */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-4">
        <div className="relative">
          <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 customers..."
            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>
      </div>

      {/* Customers Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredCustomers.length === 0 ? (
          <div className="col-span-full bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-12 text-center">
            <Building2 className="w-12 h-12 text-gray-600 mx-auto mb-4" />
            <p className="text-gray-500">No customers found</p>
          </div>
        ) : (
          filteredCustomers.map((customer) => (
            <motion.div
              key={customer.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-5 hover:border-brand-deep/50 transition-all"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-gradient-to-br from-brand-deep/20 to-brand-secondary/20 border border-brand-deep/30 rounded-lg flex items-center justify-center">
                    <Building2 className="w-6 h-6 text-brand" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-white">{customer.name}</h3>
                    <p className="text-xs text-gray-500">{customer.customerNumber}</p>
                  </div>
                </div>
                <button className="p-1 text-gray-500 hover:text-brand">
                  <MoreHorizontal className="w-5 h-5" />
                </button>
              </div>

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

              <div className="flex items-center gap-4 pt-4 border-t border-brand-bg-surface/20">
                <div className="flex items-center gap-1 text-xs text-gray-500">
                  <TrendingUp className="w-4 h-4" />
                  <span>{customer._count.opportunities} opportunities</span>
                </div>
                <div className="flex items-center gap-1 text-xs text-gray-500">
                  <FileText className="w-4 h-4" />
                  <span>{customer._count.salesOrders} orders</span>
                </div>
              </div>
            </motion.div>
          ))
        )}
      </div>

      {/* New Customer Modal */}
      <AnimatePresence>
        {modalOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
            onClick={() => setModalOpen(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-bg-surface/30 rounded-xl shadow-xl w-full max-w-md"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between p-5 border-b border-brand-bg-surface/30">
                <h2 className="text-lg font-semibold text-white">New Customer</h2>
                <button onClick={() => setModalOpen(false)} className="text-gray-500 hover:text-white">
                  <X className="w-5 h-5" />
                </button>
              </div>

              <form onSubmit={handleSubmit} className="p-5 space-y-4">
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Company Name *</label>
                  <input
                    type="text"
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: e.target.value })}
                    className="w-full 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"
                    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={form.type}
                      onChange={(e) => setForm({ ...form, type: e.target.value })}
                      className="w-full 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="company">Company</option>
                      <option value="individual">Individual</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Industry</label>
                    <input
                      type="text"
                      value={form.industry}
                      onChange={(e) => setForm({ ...form, industry: e.target.value })}
                      className="w-full 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"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Email</label>
                  <input
                    type="email"
                    value={form.email}
                    onChange={(e) => setForm({ ...form, email: e.target.value })}
                    className="w-full 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"
                  />
                </div>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Phone</label>
                  <input
                    type="tel"
                    value={form.phone}
                    onChange={(e) => setForm({ ...form, phone: e.target.value })}
                    className="w-full 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"
                  />
                </div>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Website</label>
                  <input
                    type="url"
                    value={form.website}
                    onChange={(e) => setForm({ ...form, website: e.target.value })}
                    className="w-full 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"
                    placeholder="https://"
                  />
                </div>

                <div className="flex gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setModalOpen(false)}
                    className="flex-1 px-4 py-2 border border-brand-bg-surface/30 rounded-lg text-gray-400 hover:text-white hover:border-gray-500 transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={saving}
                    className="flex-1 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white rounded-lg hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2"
                  >
                    {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                    Create Customer
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
