'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Truck, Plus, Mail, Phone, MapPin,
  Loader2, Search, Globe, Package
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Supplier {
  id: string;
  code: string;
  name: string;
  contactName?: string;
  email?: string;
  phone?: string;
  address?: string;
  website?: string;
  status: string;
  rating?: number;
  _count?: { products: number; purchaseOrders: number };
}

export default function SuppliersPage() {
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [formData, setFormData] = useState({
    code: '',
    name: '',
    contactName: '',
    email: '',
    phone: '',
    address: '',
    website: '',
  });

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

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

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

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/inventory', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'supplier',
          data: {
            code: formData.code,
            name: formData.name,
            contactName: formData.contactName || null,
            email: formData.email || null,
            phone: formData.phone || null,
            address: formData.address || null,
            website: formData.website || null,
            status: 'active',
            rating: 5,
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          code: '',
          name: '',
          contactName: '',
          email: '',
          phone: '',
          address: '',
          website: '',
        });
        fetchSuppliers();
      }
    } catch (error) {
      console.error('Failed to create supplier:', error);
    } finally {
      setSubmitting(false);
    }
  };

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

  const filteredSuppliers = suppliers.filter(sup =>
    (sup.name?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
    (sup.code?.toLowerCase() || '').includes(searchTerm.toLowerCase())
  );

  const totalProducts = suppliers.reduce((sum, s) => sum + (s._count?.products || 0), 0);
  const totalOrders = suppliers.reduce((sum, s) => sum + (s._count?.purchaseOrders || 0), 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">
            <Truck className="w-7 h-7 text-brand" />
            Suppliers
          </h1>
          <p className="text-gray-400 mt-1">Manage your supplier network</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" />
          Add Supplier
        </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 Suppliers</p>
          <p className="text-xl font-bold text-white">{suppliers.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Active</p>
          <p className="text-xl font-bold text-green-400">
            {suppliers.filter(s => s.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">
            <Package className="w-4 h-4 text-brand" />
            <p className="text-sm text-gray-400">Products Supplied</p>
          </div>
          <p className="text-xl font-bold text-brand">{totalProducts}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Orders</p>
          <p className="text-xl font-bold text-brand-secondary-light">{totalOrders}</p>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
        <input
          type="text"
          placeholder="Search suppliers..."
          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>

      {/* Suppliers List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2">
          {filteredSuppliers.length === 0 ? (
            <div className="col-span-full text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No suppliers found
            </div>
          ) : (
            filteredSuppliers.map((supplier, index) => (
              <motion.div
                key={supplier.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.03 }}
                className="p-4 bg-white/5 border border-white/10 rounded-lg hover:border-brand-deep/30 transition-colors"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-brand-deep/10 rounded-lg">
                      <Truck className="w-5 h-5 text-brand" />
                    </div>
                    <div>
                      <p className="text-xs font-mono text-gray-500">{supplier.code}</p>
                      <h3 className="font-semibold text-white">{supplier.name}</h3>
                    </div>
                  </div>
                  <span className={`text-xs px-2 py-1 rounded ${getStatusColor(supplier.status)}`}>
                    {supplier.status}
                  </span>
                </div>
                {supplier.contactName && (
                  <p className="text-sm text-gray-400 mb-2">Contact: {supplier.contactName}</p>
                )}
                <div className="space-y-1">
                  {supplier.email && (
                    <div className="flex items-center gap-2 text-xs text-gray-500">
                      <Mail className="w-3 h-3" />
                      <span>{supplier.email}</span>
                    </div>
                  )}
                  {supplier.phone && (
                    <div className="flex items-center gap-2 text-xs text-gray-500">
                      <Phone className="w-3 h-3" />
                      <span>{supplier.phone}</span>
                    </div>
                  )}
                  {supplier.website && (
                    <div className="flex items-center gap-2 text-xs text-gray-500">
                      <Globe className="w-3 h-3" />
                      <span>{supplier.website}</span>
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-4 mt-3 pt-3 border-t border-white/5 text-xs text-gray-500">
                  <span>{supplier._count?.products || 0} products</span>
                  <span>{supplier._count?.purchaseOrders || 0} orders</span>
                  {supplier.rating && (
                    <span className="text-yellow-400">
                      {'★'.repeat(Math.round(supplier.rating))}
                    </span>
                  )}
                </div>
              </motion.div>
            ))
          )}
        </div>
      )}

      {/* Add Supplier Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Add New Supplier"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Supplier Code</label>
              <input
                type="text"
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: 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="e.g., SUP-001"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Contact Name</label>
              <input
                type="text"
                value={formData.contactName}
                onChange={(e) => setFormData({ ...formData, contactName: 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">Company Name</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: 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">Email</label>
              <input
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: 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>
              <label className="block text-sm text-gray-400 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-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">Website</label>
            <input
              type="url"
              value={formData.website}
              onChange={(e) => setFormData({ ...formData, website: 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="https://"
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Address</label>
            <textarea
              value={formData.address}
              onChange={(e) => setFormData({ ...formData, address: 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={2}
            />
          </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.code || !formData.name}
              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" />}
              Add Supplier
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
