import React, { useState, useEffect } from 'react';
import { Factory, Product, User } from '../types';
import { 
  Plus, 
  Building2, 
  MapPin, 
  Layers, 
  Activity, 
  FileText, 
  CheckCircle2, 
  Clock, 
  Briefcase, 
  ChevronRight, 
  Image as ImageIcon,
  Tag,
  FolderPlus,
  UploadCloud,
  Trash2,
  Users,
  Gauge,
  FileSpreadsheet,
  Maximize2,
  FileCheck
} from 'lucide-react';

interface FactoriesSectionProps {
  factories: Factory[];
  user?: User | null;
  onAddFactory: (factoryData: any) => Promise<void>;
  onUpdateFactory: (id: string, factoryData: any) => Promise<void>;
  onAddProduct: (productData: any) => Promise<void>;
  products: Product[];
}

// Pre-configured Unsplash image presets to make showcase additions instant and professional
const IMAGE_PRESETS = [
  { name: 'Casual T-Shirt', url: 'https://images.unsplash.com/photo-1521572267360-ee0c2909d518?w=500&q=80' },
  { name: 'Warm Jacket', url: 'https://images.unsplash.com/photo-1551028719-00167b16eac5?w=500&q=80' },
  { name: 'Denim Jeans', url: 'https://images.unsplash.com/photo-1542272604-787c3835535d?w=500&q=80' },
  { name: 'Formal Shirt', url: 'https://images.unsplash.com/photo-1596755094514-f87e34085b2c?w=500&q=80' },
  { name: 'Knit Hoodie', url: 'https://images.unsplash.com/photo-1556911220-e15b29be8c8f?w=500&q=80' },
];

export default function FactoriesSection({ 
  factories, 
  user,
  onAddFactory, 
  onUpdateFactory,
  onAddProduct, 
  products 
}: FactoriesSectionProps) {
  
  const isRestricted = Boolean(user && user.status !== 'Approved');

  const checkRestrictedAndAlert = (): boolean => {
    if (isRestricted) {
      alert(`Account Action Restricted: Your account status is currently ${user?.status || 'Pending'}. Creating or modifying factory details requires administrator account approval from Admin Console.`);
      return true;
    }
    return false;
  };
  const [showAddFactoryModal, setShowAddFactoryModal] = useState(false);
  const [editingFactoryId, setEditingFactoryId] = useState<string | null>(null);
  const [showAddProductModal, setShowAddProductModal] = useState(false);
  const [selectedFactoryId, setSelectedFactoryId] = useState<string | null>(null);

  // Form States for Factory
  const [factoryName, setFactoryName] = useState('');
  const [factoryLocation, setFactoryLocation] = useState('');
  const [address, setAddress] = useState('');
  const [size, setSize] = useState('Medium');
  const [qcStaff, setQcStaff] = useState('');
  const [rdStaff, setRdStaff] = useState('');
  const [productionLines, setProductionLines] = useState('');
  const [annualOutput, setAnnualOutput] = useState('');
  const [leadTime, setLeadTime] = useState('30 Days');
  const [factoryType, setFactoryType] = useState('Woven');
  const [productionCapacity, setProductionCapacity] = useState('');
  const [verificationId, setVerificationId] = useState('');
  const [uploadedFileName, setUploadedFileName] = useState('');
  const [isDragging, setIsDragging] = useState(false);
  const [logoUrl, setLogoUrl] = useState('');
  const [logoFileName, setLogoFileName] = useState('');
  const [isDraggingLogo, setIsDraggingLogo] = useState(false);

  // Form States for Product Showcase
  const [productTitle, setProductTitle] = useState('');
  const [productCategory, setProductCategory] = useState('');
  const [productDescription, setProductDescription] = useState('');
  const [productImage, setProductImage] = useState(IMAGE_PRESETS[0].url);

  // Active factory details tab
  const [activeFactoryDetailId, setActiveFactoryDetailId] = useState<string | null>(null);

  // Drag and drop handlers
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const file = e.dataTransfer.files[0];
      setUploadedFileName(file.name);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setUploadedFileName(e.target.files[0].name);
    }
  };

  const handleLogoDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDraggingLogo(true);
  };

  const handleLogoDragLeave = () => {
    setIsDraggingLogo(false);
  };

  const handleLogoDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDraggingLogo(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const file = e.dataTransfer.files[0];
      setLogoFileName(file.name);
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          setLogoUrl(event.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleLogoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      setLogoFileName(file.name);
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          setLogoUrl(event.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // Handle adding or updating factory
  const handleFactorySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (checkRestrictedAndAlert()) return;
    if (!factoryName || !factoryLocation || !productionCapacity || !verificationId) {
      alert('Please fill out all required factory details.');
      return;
    }
    const factoryPayload = {
      name: factoryName,
      location: factoryLocation,
      address,
      size,
      qcStaff: qcStaff ? Number(qcStaff) : 0,
      rdStaff: rdStaff ? Number(rdStaff) : 0,
      productionLines: productionLines ? Number(productionLines) : 0,
      annualOutput,
      leadTime,
      type: factoryType,
      capacity: productionCapacity,
      verificationId: verificationId,
      verificationDoc: uploadedFileName ? (uploadedFileName.startsWith('http') ? uploadedFileName : `https://example.com/docs/${encodeURIComponent(uploadedFileName)}`) : '',
      logoUrl: logoUrl || 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=120&q=80' // Beautiful default abstract geometric logo preset
    };

    if (editingFactoryId) {
      await onUpdateFactory(editingFactoryId, factoryPayload);
    } else {
      await onAddFactory(factoryPayload);
    }

    // Reset
    setEditingFactoryId(null);
    setFactoryName('');
    setFactoryLocation('');
    setAddress('');
    setSize('Medium');
    setQcStaff('');
    setRdStaff('');
    setProductionLines('');
    setAnnualOutput('');
    setLeadTime('30 Days');
    setFactoryType('Woven');
    setProductionCapacity('');
    setVerificationId('');
    setUploadedFileName('');
    setLogoUrl('');
    setLogoFileName('');
    setShowAddFactoryModal(false);
  };

  const handleStartEditFactory = (factory: Factory) => {
    if (checkRestrictedAndAlert()) return;
    setEditingFactoryId(factory.id);
    setFactoryName(factory.name);
    setFactoryLocation(factory.location);
    setAddress(factory.address || '');
    setSize(factory.size || 'Medium');
    setQcStaff(factory.qcStaff ? String(factory.qcStaff) : '');
    setRdStaff(factory.rdStaff ? String(factory.rdStaff) : '');
    setProductionLines(factory.productionLines ? String(factory.productionLines) : '');
    setAnnualOutput(factory.annualOutput || '');
    setLeadTime(factory.leadTime || '30 Days');
    setFactoryType(factory.type || 'Woven');
    setProductionCapacity(factory.capacity);
    setVerificationId(factory.verificationId);
    setUploadedFileName(factory.verificationDoc ? factory.verificationDoc.split('/').pop() || '' : '');
    setLogoUrl(factory.logoUrl || '');
    setLogoFileName(factory.logoUrl ? 'existing_logo.png' : '');
    setShowAddFactoryModal(true);
  };

  const handleCloseFactoryModal = () => {
    setEditingFactoryId(null);
    setFactoryName('');
    setFactoryLocation('');
    setAddress('');
    setSize('Medium');
    setQcStaff('');
    setRdStaff('');
    setProductionLines('');
    setAnnualOutput('');
    setLeadTime('30 Days');
    setFactoryType('Woven');
    setProductionCapacity('');
    setVerificationId('');
    setUploadedFileName('');
    setLogoUrl('');
    setLogoFileName('');
    setShowAddFactoryModal(false);
  };

  // Handle adding product showcase
  const handleProductSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (checkRestrictedAndAlert()) return;
    if (!selectedFactoryId || !productTitle || !productCategory || !productDescription) {
      alert('Please fill out all required fields.');
      return;
    }
    await onAddProduct({
      factoryId: selectedFactoryId,
      title: productTitle,
      category: productCategory,
      description: productDescription,
      image: productImage
    });
    // Reset
    setProductTitle('');
    setProductCategory('');
    setProductDescription('');
    setProductImage(IMAGE_PRESETS[0].url);
    setShowAddProductModal(false);
    setSelectedFactoryId(null);
  };

  return (
    <div className="space-y-8">
      {/* Header and Toggle */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-sans font-bold tracking-tight text-slate-950">
            Multi-Factory Portfolios
          </h1>
          <p className="text-slate-500 text-xs">
            Manage your manufacturing facilities, trade licenses, and garment showcase catalogs.
          </p>
        </div>
        <button
          onClick={() => {
            if (checkRestrictedAndAlert()) return;
            setShowAddFactoryModal(true);
          }}
          className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold px-4 py-2.5 rounded-lg shadow-sm transition flex items-center space-x-1.5 cursor-pointer"
        >
          <Plus className="w-4 h-4" />
          <span>Add New Factory</span>
        </button>
      </div>

      {/* Factories Grid */}
      {factories.length === 0 ? (
        <div className="bg-white border-2 border-dashed border-slate-200 rounded-xl p-12 text-center max-w-xl mx-auto space-y-4">
          <div className="bg-slate-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-slate-400">
            <Building2 className="w-8 h-8" />
          </div>
          <div className="space-y-1">
            <h3 className="font-bold text-slate-800 text-sm">No factories registered</h3>
            <p className="text-xs text-slate-500">
              Create a factory entry, provide details & trade licenses to get started.
            </p>
          </div>
          <button
            onClick={() => setShowAddFactoryModal(true)}
            className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-medium px-4 py-2 rounded-lg transition"
          >
            Register My First Factory
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {factories.map(factory => {
            const factoryProducts = products.filter(p => p.factoryId === factory.id);
            const isApproved = factory.status === 'Approved';

            return (
              <div 
                key={factory.id} 
                className={`bg-white border rounded-xl shadow-sm overflow-hidden transition-all duration-300 flex flex-col justify-between ${
                  activeFactoryDetailId === factory.id ? 'ring-2 ring-blue-500 border-blue-500' : 'border-slate-200 hover:shadow-md'
                }`}
              >
                {/* Header */}
                <div className="p-5 border-b border-slate-100 bg-slate-50/50">
                  <div className="flex justify-between items-start gap-4">
                    <div className="flex items-start space-x-3">
                      {factory.logoUrl ? (
                        <img 
                          src={factory.logoUrl} 
                          alt={`${factory.name} Logo`} 
                          className="w-12 h-12 rounded-lg object-cover border border-slate-200 bg-white shadow-sm shrink-0"
                          referrerPolicy="no-referrer"
                        />
                      ) : (
                        <div className="w-12 h-12 rounded-lg bg-blue-100 text-blue-700 flex items-center justify-center font-bold text-base border border-blue-200 shrink-0">
                          {factory.name.charAt(0)}
                        </div>
                      )}
                      <div className="space-y-1">
                        <div className="flex items-center space-x-2">
                          <h3 className="font-bold text-slate-900 text-sm sm:text-base leading-tight">
                            {factory.name}
                          </h3>
                          <span className="text-[10px] bg-slate-200 text-slate-800 px-2 py-0.5 rounded font-medium">
                            {factory.type}
                          </span>
                        </div>
                        <p className="text-[11px] text-slate-500 flex items-center">
                          <MapPin className="w-3 h-3 mr-1 text-slate-400" />
                          {factory.location}
                        </p>
                      </div>
                    </div>

                    {/* Status Badge */}
                    <div>
                      {factory.status === 'Approved' ? (
                        <span className="text-[10px] bg-emerald-50 text-emerald-700 border border-emerald-200 px-2.5 py-1 rounded-full font-semibold flex items-center space-x-1">
                          <CheckCircle2 className="w-3.5 h-3.5" />
                          <span>Approved</span>
                        </span>
                      ) : factory.status === 'Rejected' ? (
                        <span className="text-[10px] bg-rose-50 text-rose-700 border border-rose-200 px-2.5 py-1 rounded-full font-semibold flex items-center space-x-1">
                          <Clock className="w-3.5 h-3.5" />
                          <span>Rejected</span>
                        </span>
                      ) : factory.status === 'On-Hold' ? (
                        <span className="text-[10px] bg-amber-100 text-amber-800 border border-amber-300 px-2.5 py-1 rounded-full font-semibold flex items-center space-x-1">
                          <Clock className="w-3.5 h-3.5" />
                          <span>On-Hold</span>
                        </span>
                      ) : (
                        <span className="text-[10px] bg-amber-50 text-amber-700 border border-amber-200 px-2.5 py-1 rounded-full font-semibold flex items-center space-x-1" title="Awaiting admin approval">
                          <Clock className="w-3.5 h-3.5 animate-pulse" />
                          <span>Pending Approval</span>
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Details list */}
                <div className="p-5 space-y-4 flex-1">
                  <div className="grid grid-cols-2 gap-4 text-xs">
                    <div className="space-y-1 p-2 bg-slate-50 rounded">
                      <p className="text-slate-400 font-medium text-[10px] uppercase">Production Capacity</p>
                      <p className="font-semibold text-slate-700 flex items-center">
                        <Activity className="w-3.5 h-3.5 mr-1 text-blue-500" />
                        {factory.capacity}
                      </p>
                    </div>
                    <div className="space-y-1 p-2 bg-slate-50 rounded">
                      <p className="text-slate-400 font-medium text-[10px] uppercase">Trade License/BGMEA</p>
                      <p className="font-semibold text-slate-700 flex items-center font-mono">
                        <FileText className="w-3.5 h-3.5 mr-1 text-slate-500" />
                        {factory.verificationId}
                      </p>
                    </div>
                  </div>

                  {/* Showcase Products catalog */}
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="font-semibold text-slate-800 text-xs flex items-center">
                        <Layers className="w-3.5 h-3.5 mr-1 text-purple-600" />
                        Product Catalog ({factoryProducts.length})
                      </span>
                      {isApproved && (
                        <button
                          onClick={() => {
                            setSelectedFactoryId(factory.id);
                            setShowAddProductModal(true);
                          }}
                          className="text-blue-600 hover:text-blue-800 text-xs font-semibold flex items-center hover:underline cursor-pointer"
                        >
                          <FolderPlus className="w-3.5 h-3.5 mr-1" /> Add Product
                        </button>
                      )}
                    </div>

                    {factoryProducts.length === 0 ? (
                      <div className="border border-dashed border-slate-200 rounded-lg p-4 text-center text-slate-400 text-xs">
                        {isApproved 
                          ? "No items added. Add some garments to showcase capabilities!"
                          : "Verify factory to unlock product additions."}
                      </div>
                    ) : (
                      <div className="grid grid-cols-3 gap-2">
                        {factoryProducts.map(p => (
                          <div key={p.id} className="group relative rounded-lg overflow-hidden border border-slate-100 bg-slate-50 cursor-pointer hover:shadow">
                            <img 
                              src={p.image} 
                              alt={p.title} 
                              className="w-full h-16 sm:h-20 object-cover" 
                            />
                            <div className="absolute inset-0 bg-slate-900/40 opacity-0 group-hover:opacity-100 transition flex items-center justify-center p-1 text-center">
                              <span className="text-white text-[9px] font-semibold truncate w-full">{p.title}</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>

                {/* Footer details toggle */}
                <div className="p-3 bg-slate-50 border-t border-slate-100 flex justify-between items-center">
                  <div className="flex items-center space-x-3">
                    <button
                      onClick={() => setActiveFactoryDetailId(activeFactoryDetailId === factory.id ? null : factory.id)}
                      className="text-slate-500 hover:text-slate-800 text-xs font-semibold flex items-center cursor-pointer"
                    >
                      <span>{activeFactoryDetailId === factory.id ? 'Hide Details' : 'View Full Catalog'}</span>
                      <ChevronRight className={`w-3.5 h-3.5 ml-1 transition-transform ${activeFactoryDetailId === factory.id ? 'rotate-90' : ''}`} />
                    </button>

                    <button
                      onClick={() => handleStartEditFactory(factory)}
                      className="text-blue-600 hover:text-blue-800 text-[11px] font-semibold flex items-center hover:underline cursor-pointer bg-blue-50/80 px-2 py-0.5 rounded border border-blue-200"
                    >
                      Edit Factory
                    </button>
                  </div>

                  {!isApproved && (
                    <span className="text-[10px] text-amber-600 italic">Admin Approval pending</span>
                  )}
                </div>

                {/* Expanded Factory Catalog Details */}
                {activeFactoryDetailId === factory.id && (
                  <div className="p-5 border-t border-slate-100 bg-slate-50/50 space-y-6">
                    
                    {/* SECTION 1: Technical & Operational Profile */}
                    <div className="bg-white rounded-lg border border-slate-100 p-4 space-y-4">
                      <h4 className="font-sans font-bold text-xs text-slate-800 uppercase tracking-wider flex items-center gap-1.5">
                        <Gauge className="w-4 h-4 text-blue-600" />
                        Technical & Operational Profile
                      </h4>
                      <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 text-xs">
                        {factory.address && (
                          <div className="col-span-2 sm:col-span-3 space-y-1">
                            <p className="text-slate-400 font-medium text-[10px] uppercase">Registered Address</p>
                            <p className="font-medium text-slate-800 bg-slate-50 p-2 rounded border border-slate-100 leading-relaxed">
                              {factory.address}
                            </p>
                          </div>
                        )}
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">Facility Size</p>
                          <p className="font-semibold text-slate-800">{factory.size || 'Medium'}</p>
                        </div>
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">Average Lead Time</p>
                          <p className="font-semibold text-slate-800 flex items-center">
                            <Clock className="w-3.5 h-3.5 text-slate-400 mr-1 shrink-0" />
                            {factory.leadTime || '30 Days'}
                          </p>
                        </div>
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">Production Lines</p>
                          <p className="font-semibold text-slate-800 flex items-center">
                            <Layers className="w-3.5 h-3.5 text-slate-400 mr-1 shrink-0" />
                            {factory.productionLines || '8'} Lines
                          </p>
                        </div>
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">Annual Output</p>
                          <p className="font-semibold text-slate-800 flex items-center">
                            <FileSpreadsheet className="w-3.5 h-3.5 text-slate-400 mr-1 shrink-0" />
                            {factory.annualOutput || '2,500,000 Pcs'}
                          </p>
                        </div>
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">QC Staff Strength</p>
                          <p className="font-semibold text-slate-800 flex items-center">
                            <Users className="w-3.5 h-3.5 text-slate-400 mr-1 shrink-0" />
                            {factory.qcStaff || '25'} Specialists
                          </p>
                        </div>
                        <div className="space-y-0.5">
                          <p className="text-slate-400 font-medium text-[10px] uppercase">R&D Team Size</p>
                          <p className="font-semibold text-slate-800 flex items-center">
                            <Users className="w-3.5 h-3.5 text-slate-400 mr-1 shrink-0" />
                            {factory.rdStaff || '8'} Designers
                          </p>
                        </div>
                      </div>

                      {/* Trade License & Verification document banner */}
                      <div className="pt-3 border-t border-slate-100 flex flex-wrap items-center justify-between gap-2">
                        <div className="flex items-center space-x-2 text-xs">
                          <FileCheck className="w-4 h-4 text-emerald-600 animate-pulse" />
                          <span className="font-medium text-slate-700">Trade License: <span className="font-mono text-slate-900">{factory.verificationId}</span></span>
                          <span className="bg-emerald-50 text-emerald-700 text-[9px] px-1.5 py-0.5 rounded font-semibold border border-emerald-100">
                            Verified Auth ID
                          </span>
                        </div>
                        {factory.verificationDoc && (
                          <a 
                            href={factory.verificationDoc} 
                            target="_blank" 
                            rel="noopener noreferrer"
                            className="text-[11px] bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold px-2.5 py-1 rounded transition flex items-center gap-1 cursor-pointer"
                          >
                            <FileText className="w-3 h-3 text-slate-500" /> View Attached License PDF
                          </a>
                        )}
                      </div>
                    </div>

                    {/* SECTION 2: Product Showcase */}
                    <div className="bg-white rounded-lg border border-slate-100 p-4 space-y-4">
                      <h4 className="font-sans font-bold text-xs text-slate-800 uppercase tracking-wider flex items-center gap-1.5">
                        <Layers className="w-4 h-4 text-purple-600" />
                        Factory Showcase Showcase ({factoryProducts.length} Items)
                      </h4>
                      {factoryProducts.length === 0 ? (
                        <p className="text-xs text-slate-400 text-center py-4">No portfolio products currently live.</p>
                      ) : (
                        <div className="space-y-4 divide-y divide-slate-100">
                          {factoryProducts.map(p => (
                            <div key={p.id} className="pt-3 first:pt-0 flex gap-4">
                              <img src={p.image} alt={p.title} className="w-16 h-16 rounded object-cover border bg-slate-50 shrink-0" />
                              <div className="space-y-1">
                                <div className="flex items-center space-x-2">
                                  <span className="font-semibold text-xs text-slate-900">{p.title}</span>
                                  <span className="text-[9px] bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded font-medium">{p.category}</span>
                                </div>
                                <p className="text-slate-500 text-[11px] leading-relaxed">{p.description}</p>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* MODAL 1: ADD FACTORY */}
      {showAddFactoryModal && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 max-w-2xl w-full overflow-hidden flex flex-col max-h-[90vh]">
            <div className="px-6 py-4 bg-slate-50 border-b border-slate-100 flex justify-between items-center shrink-0">
              <div className="flex items-center space-x-2">
                <Building2 className="w-5 h-5 text-blue-600" />
                <h3 className="font-sans font-bold text-slate-900 text-sm sm:text-base">
                  {editingFactoryId ? 'Edit B2B Factory Profile' : 'Register B2B Factory Profile'}
                </h3>
              </div>
              <button 
                onClick={handleCloseFactoryModal}
                className="text-slate-400 hover:text-slate-600 text-lg cursor-pointer transition-colors"
              >
                &times;
              </button>
            </div>
            <form onSubmit={handleFactorySubmit} className="flex-1 overflow-y-auto p-6 space-y-6">
              
              {/* SECTION 1: GENERAL COMPANY INFORMATION */}
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-blue-600 uppercase tracking-wider flex items-center gap-1.5 border-b border-slate-100 pb-1.5">
                  <span className="w-1.5 h-3 bg-blue-600 rounded-sm"></span>
                  1. General Company Information
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Factory Name *</label>
                    <input 
                      type="text"
                      required
                      placeholder="e.g. Dhaka Garments & Textiles Ltd."
                      value={factoryName}
                      onChange={(e) => setFactoryName(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Factory Location (City/Region) *</label>
                    <input 
                      type="text"
                      required
                      placeholder="e.g. Gazipur, Narayanganj"
                      value={factoryLocation}
                      onChange={(e) => setFactoryLocation(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-slate-700">Location/Address (Full Detailed Physical Address) *</label>
                  <textarea 
                    rows={2}
                    required
                    placeholder="e.g. Plot 14-19, Savar EPZ Industrial Extension, Savar, Dhaka, Bangladesh"
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500 resize-none"
                  />
                </div>

                {/* Factory Logo Upload Field */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-slate-700 font-sans text-slate-750">Factory Logo (NEW FIELD)</label>
                  <div className="flex items-center space-x-4">
                    {logoUrl ? (
                      <div className="relative shrink-0">
                        <img 
                          src={logoUrl} 
                          alt="Factory Logo Preview" 
                          className="w-16 h-16 rounded-lg object-cover border border-slate-200 shadow-sm bg-white"
                          referrerPolicy="no-referrer"
                        />
                        <button
                          type="button"
                          onClick={() => {
                            setLogoUrl('');
                            setLogoFileName('');
                          }}
                          className="absolute -top-1.5 -right-1.5 bg-red-500 hover:bg-red-600 text-white rounded-full w-5 h-5 flex items-center justify-center shadow transition-colors cursor-pointer text-xs font-bold"
                        >
                          &times;
                        </button>
                      </div>
                    ) : (
                      <div className="w-16 h-16 rounded-lg bg-slate-100 border border-slate-200 text-slate-400 flex items-center justify-center font-bold text-[10px] shrink-0 text-center px-1">
                        No Logo
                      </div>
                    )}
                    <div 
                      onDragOver={handleLogoDragOver}
                      onDragLeave={handleLogoDragLeave}
                      onDrop={handleLogoDrop}
                      className={`flex-1 border-2 border-dashed rounded-lg p-3 text-center cursor-pointer transition-colors ${
                        isDraggingLogo 
                          ? 'border-blue-500 bg-blue-50' 
                          : logoFileName 
                            ? 'border-emerald-500 bg-emerald-50/50' 
                            : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
                      }`}
                    >
                      <input 
                        type="file"
                        id="logo-file-upload"
                        className="hidden"
                        onChange={handleLogoFileChange}
                        accept="image/*"
                      />
                      <label htmlFor="logo-file-upload" className="cursor-pointer block space-y-1">
                        {logoFileName ? (
                          <div>
                            <p className="text-xs font-semibold text-slate-800 truncate max-w-[200px] mx-auto">{logoFileName}</p>
                            <p className="text-[9px] text-slate-400">Logo attached successfully</p>
                          </div>
                        ) : (
                          <div>
                            <p className="text-xs font-semibold text-slate-700">Drag & drop logo here, or <span className="text-blue-600 underline">browse</span></p>
                            <p className="text-[9px] text-slate-400">Supports PNG, JPG, JPEG (Square format best)</p>
                          </div>
                        )}
                      </label>
                    </div>
                  </div>
                </div>
              </div>

              {/* SECTION 2: TECHNICAL & PRODUCTION SPECIFICATIONS */}
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-blue-600 uppercase tracking-wider flex items-center gap-1.5 border-b border-slate-100 pb-1.5">
                  <span className="w-1.5 h-3 bg-blue-600 rounded-sm"></span>
                  2. Technical & Production Specifications
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Factory Size *</label>
                    <select
                      value={size}
                      onChange={(e) => setSize(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    >
                      <option value="Small">Small (&lt; 25,000 sq ft)</option>
                      <option value="Medium">Medium (25,000 - 100,000 sq ft)</option>
                      <option value="Large">Large (&gt; 100,000 sq ft)</option>
                    </select>
                  </div>

                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Factory Type *</label>
                    <select
                      value={factoryType}
                      onChange={(e) => setFactoryType(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    >
                      <option value="Woven">Woven</option>
                      <option value="Knit">Knit</option>
                      <option value="Denim">Denim</option>
                      <option value="Sweater">Sweater</option>
                      <option value="Leather">Leather</option>
                      <option value="Activewear">Activewear</option>
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Production Capacity (Monthly Max) *</label>
                    <input 
                      type="text"
                      required
                      placeholder="e.g. 500,000 Pcs/Month"
                      value={productionCapacity}
                      onChange={(e) => setProductionCapacity(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Total Production Lines *</label>
                    <input 
                      type="number"
                      required
                      min={1}
                      placeholder="e.g. 12"
                      value={productionLines}
                      onChange={(e) => setProductionLines(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Annual Output *</label>
                    <input 
                      type="text"
                      required
                      placeholder="e.g. 4,500,000 Pcs/Year"
                      value={annualOutput}
                      onChange={(e) => setAnnualOutput(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Average Lead Time *</label>
                    <select
                      value={leadTime}
                      onChange={(e) => setLeadTime(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    >
                      <option value="30 Days">30 Days</option>
                      <option value="45 Days">45 Days</option>
                      <option value="60 Days">60 Days</option>
                      <option value="90 Days">90 Days</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* SECTION 3: STAFFING & QUALITY CONTROL */}
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-blue-600 uppercase tracking-wider flex items-center gap-1.5 border-b border-slate-100 pb-1.5">
                  <span className="w-1.5 h-3 bg-blue-600 rounded-sm"></span>
                  3. Staffing & Quality Control
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Total Quality Control (QC) Staff *</label>
                    <input 
                      type="number"
                      required
                      min={0}
                      placeholder="e.g. 25"
                      value={qcStaff}
                      onChange={(e) => setQcStaff(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-slate-700">Total R&D Staff *</label>
                    <input 
                      type="number"
                      required
                      min={0}
                      placeholder="e.g. 10"
                      value={rdStaff}
                      onChange={(e) => setRdStaff(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
              </div>

              {/* SECTION 4: VERIFICATION & COMPLIANCE */}
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-blue-600 uppercase tracking-wider flex items-center gap-1.5 border-b border-slate-100 pb-1.5">
                  <span className="w-1.5 h-3 bg-blue-600 rounded-sm"></span>
                  4. Verification & Compliance
                </h4>
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-slate-700">Trade License / BGMEA Membership ID *</label>
                  <input 
                    type="text"
                    required
                    placeholder="e.g. BGMEA-10492-C"
                    value={verificationId}
                    onChange={(e) => setVerificationId(e.target.value)}
                    className="w-full text-xs font-mono sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-blue-500"
                  />
                </div>

                {/* Usability Pattern: Drag-and-Drop or File Upload */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-slate-700">Upload Trade License / BGMEA Document *</label>
                  <div 
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    className={`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${
                      isDragging 
                        ? 'border-blue-500 bg-blue-50' 
                        : uploadedFileName 
                          ? 'border-emerald-500 bg-emerald-50/50' 
                          : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
                    }`}
                  >
                    <input 
                      type="file"
                      id="license-file-upload"
                      className="hidden"
                      onChange={handleFileChange}
                      accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                    />
                    <label htmlFor="license-file-upload" className="cursor-pointer block space-y-2">
                      {uploadedFileName ? (
                        <div className="flex flex-col items-center space-y-1">
                          <FileCheck className="w-8 h-8 text-emerald-600" />
                          <p className="text-xs font-semibold text-slate-800">{uploadedFileName}</p>
                          <p className="text-[10px] text-slate-400">File attached successfully</p>
                          <button
                            type="button"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              setUploadedFileName('');
                            }}
                            className="mt-1 text-[10px] text-red-500 hover:text-red-700 font-bold flex items-center gap-1 bg-white border border-red-200 px-2 py-0.5 rounded shadow-sm mx-auto"
                          >
                            <Trash2 className="w-3 h-3" /> Remove File
                          </button>
                        </div>
                      ) : (
                        <div className="flex flex-col items-center space-y-1">
                          <UploadCloud className="w-8 h-8 text-slate-400" />
                          <p className="text-xs font-semibold text-slate-700">Drag & drop your document here, or <span className="text-blue-600 underline">browse</span></p>
                          <p className="text-[10px] text-slate-400">Supports PDF, PNG, JPG or DOC (Max 10MB)</p>
                        </div>
                      )}
                    </label>
                  </div>
                </div>
              </div>

              {/* ACTION FOOTER */}
              <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold shrink-0">
                <button 
                  type="button"
                  onClick={handleCloseFactoryModal}
                  className="px-4 py-2 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-sm cursor-pointer transition-colors"
                >
                  {editingFactoryId ? 'Save Changes' : 'Submit factory'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: ADD SHOWCASE PRODUCT */}
      {showAddProductModal && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 max-w-md w-full overflow-hidden">
            <div className="px-6 py-4 bg-slate-50 border-b border-slate-100 flex justify-between items-center">
              <h3 className="font-sans font-bold text-slate-900 text-sm sm:text-base">Add Product Showcase</h3>
              <button 
                onClick={() => {
                  setShowAddProductModal(false);
                  setSelectedFactoryId(null);
                }}
                className="text-slate-400 hover:text-slate-600 text-lg cursor-pointer"
              >
                &times;
              </button>
            </div>
            <form onSubmit={handleProductSubmit} className="p-6 space-y-4">
              <div className="space-y-1">
                <label className="block text-xs font-semibold text-slate-700">Product Title *</label>
                <input 
                  type="text"
                  required
                  placeholder="e.g. Recycled Cotton Polo Shirt"
                  value={productTitle}
                  onChange={(e) => setProductTitle(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
              </div>

              <div className="space-y-1">
                <label className="block text-xs font-semibold text-slate-700">Category *</label>
                <input 
                  type="text"
                  required
                  placeholder="e.g. Polo Shirt, Jacket, Denim Jeans"
                  value={productCategory}
                  onChange={(e) => setProductCategory(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
              </div>

              <div className="space-y-1">
                <label className="block text-xs font-semibold text-slate-700">Product Description *</label>
                <textarea 
                  required
                  rows={3}
                  placeholder="Describe material compositions, stitches, weight/GSM, wash types, etc."
                  value={productDescription}
                  onChange={(e) => setProductDescription(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
              </div>

              {/* Product Image presets picker */}
              <div className="space-y-2">
                <label className="block text-xs font-semibold text-slate-700 flex items-center">
                  <ImageIcon className="w-3.5 h-3.5 mr-1 text-slate-400" />
                  Product Catalog Image Preset
                </label>
                <div className="grid grid-cols-5 gap-1.5">
                  {IMAGE_PRESETS.map((preset, idx) => (
                    <button
                      key={idx}
                      type="button"
                      onClick={() => setProductImage(preset.url)}
                      className={`relative rounded-md overflow-hidden h-10 border transition-all ${
                        productImage === preset.url ? 'ring-2 ring-blue-500 border-blue-500 scale-95' : 'border-slate-200 hover:opacity-80'
                      }`}
                      title={preset.name}
                    >
                      <img src={preset.url} alt={preset.name} className="w-full h-full object-cover" />
                    </button>
                  ))}
                </div>
                <div className="space-y-1 pt-1.5">
                  <span className="text-[10px] text-slate-400">Or input custom image URL:</span>
                  <input 
                    type="url"
                    placeholder="https://example.com/garment.jpg"
                    value={productImage}
                    onChange={(e) => setProductImage(e.target.value)}
                    className="w-full text-xs border border-slate-200 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                  />
                </div>
              </div>

              <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold">
                <button 
                  type="button"
                  onClick={() => {
                    setShowAddProductModal(false);
                    setSelectedFactoryId(null);
                  }}
                  className="px-4 py-2 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-sm cursor-pointer"
                >
                  Showcase Item
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
