import React, { useState } from 'react';
import { Plus, Trash2, Printer, Download, Save } from 'lucide-react';

export default function ITServiceInvoice() {
  const [companyInfo, setCompanyInfo] = useState({
    name: 'TechFix Solutions',
    address: '123 Business Street',
    city: 'Your City, State 12345',
    phone: '+1 (555) 123-4567',
    email: 'info@techfix.com',
    gst: 'GST123456789'
  });

  const [clientInfo, setClientInfo] = useState({
    name: '',
    address: '',
    city: '',
    phone: '',
    email: ''
  });

  const [invoiceDetails, setInvoiceDetails] = useState({
    number: 'INV-001',
    date: new Date().toISOString().split('T')[0],
    dueDate: new Date(Date.now() + 30*24*60*60*1000).toISOString().split('T')[0]
  });

  const [services, setServices] = useState([
    { id: 1, description: '', quantity: 1, rate: 0, amount: 0 }
  ]);

  const [taxRate, setTaxRate] = useState(18); // GST/Tax percentage

  // Predefined services (without rates - manually entered per client)
  const predefinedServices = [
    'Windows Installation',
    'MS Office Installation',
    'Tally Installation',
    'Antivirus Installation',
    'Computer Servicing',
    'Hardware Repair',
    'Software Troubleshooting',
    'Data Recovery',
    'Network Setup',
    'Laptop Screen Replacement',
    'Printer Setup & Configuration',
    'Virus & Malware Removal',
    'System Upgrade',
    'Data Backup & Transfer'
  ];

  const addService = () => {
    const newId = Math.max(...services.map(s => s.id), 0) + 1;
    setServices([...services, { id: newId, description: '', quantity: 1, rate: 0, amount: 0 }]);
  };

  const removeService = (id) => {
    if (services.length > 1) {
      setServices(services.filter(s => s.id !== id));
    }
  };

  const updateService = (id, field, value) => {
    setServices(services.map(s => {
      if (s.id === id) {
        const updated = { ...s, [field]: value };
        if (field === 'quantity' || field === 'rate') {
          updated.amount = updated.quantity * updated.rate;
        }
        return updated;
      }
      return s;
    }));
  };

  const selectPredefinedService = (id, serviceName) => {
    if (serviceName) {
      updateService(id, 'description', serviceName);
    }
  };

  const subtotal = services.reduce((sum, s) => sum + s.amount, 0);
  const taxAmount = (subtotal * taxRate) / 100;
  const total = subtotal + taxAmount;

  const handlePrint = () => {
    window.print();
  };

  const handleDownload = () => {
    window.print();
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-slate-100 p-4 md:p-8">
      <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet" />
      
      <style>{`
        * {
          font-family: 'Outfit', sans-serif;
        }
        
        .mono {
          font-family: 'Space Mono', monospace;
        }
        
        @keyframes slideIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        
        .animate-slide-in {
          animation: slideIn 0.4s ease-out forwards;
        }
        
        .glass-card {
          background: rgba(255, 255, 255, 0.9);
          backdrop-filter: blur(10px);
          border: 1px solid rgba(255, 255, 255, 0.5);
        }
        
        @media print {
          body { 
            background: white !important;
            margin: 0;
            padding: 20px;
          }
          .no-print { 
            display: none !important; 
          }
          .print-full-width {
            max-width: 100% !important;
            box-shadow: none !important;
            border: none !important;
          }
          .glass-card {
            background: white !important;
            border: 1px solid #ddd !important;
          }
        }
        
        input:focus, textarea:focus, select:focus {
          outline: none;
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .gradient-text {
          background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      `}</style>

      <div className="max-w-5xl mx-auto">
        {/* Header Actions */}
        <div className="no-print mb-6 flex justify-between items-center animate-slide-in">
          <div>
            <h1 className="text-3xl font-bold gradient-text">Invoice Generator</h1>
            <p className="text-slate-600 mt-1">Create professional invoices for IT services</p>
          </div>
          <div className="flex gap-3">
            <button
              onClick={handlePrint}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all duration-200 hover:shadow-lg"
            >
              <Printer className="w-4 h-4" />
              Print
            </button>
            <button
              onClick={handleDownload}
              className="flex items-center gap-2 px-4 py-2 bg-slate-700 text-white rounded-lg hover:bg-slate-800 transition-all duration-200 hover:shadow-lg"
            >
              <Download className="w-4 h-4" />
              Download PDF
            </button>
          </div>
        </div>

        {/* Invoice Container */}
        <div className="glass-card print-full-width rounded-2xl shadow-2xl p-8 md:p-12 animate-slide-in" style={{ animationDelay: '0.1s' }}>
          
          {/* Invoice Header */}
          <div className="border-b-2 border-blue-600 pb-8 mb-8">
            <div className="grid md:grid-cols-2 gap-8">
              {/* Company Info */}
              <div>
                <h2 className="text-sm font-semibold text-blue-600 uppercase tracking-wider mb-4">From</h2>
                <input
                  type="text"
                  value={companyInfo.name}
                  onChange={(e) => setCompanyInfo({...companyInfo, name: e.target.value})}
                  className="text-2xl font-bold text-slate-900 mb-3 w-full border-b-2 border-transparent hover:border-blue-200 transition-colors bg-transparent"
                  placeholder="Company Name"
                />
                <div className="space-y-2 text-slate-600">
                  <input
                    type="text"
                    value={companyInfo.address}
                    onChange={(e) => setCompanyInfo({...companyInfo, address: e.target.value})}
                    className="w-full border-b border-transparent hover:border-blue-200 transition-colors bg-transparent py-1"
                    placeholder="Address"
                  />
                  <input
                    type="text"
                    value={companyInfo.city}
                    onChange={(e) => setCompanyInfo({...companyInfo, city: e.target.value})}
                    className="w-full border-b border-transparent hover:border-blue-200 transition-colors bg-transparent py-1"
                    placeholder="City, State ZIP"
                  />
                  <input
                    type="text"
                    value={companyInfo.phone}
                    onChange={(e) => setCompanyInfo({...companyInfo, phone: e.target.value})}
                    className="w-full border-b border-transparent hover:border-blue-200 transition-colors bg-transparent py-1"
                    placeholder="Phone"
                  />
                  <input
                    type="email"
                    value={companyInfo.email}
                    onChange={(e) => setCompanyInfo({...companyInfo, email: e.target.value})}
                    className="w-full border-b border-transparent hover:border-blue-200 transition-colors bg-transparent py-1"
                    placeholder="Email"
                  />
                  <input
                    type="text"
                    value={companyInfo.gst}
                    onChange={(e) => setCompanyInfo({...companyInfo, gst: e.target.value})}
                    className="w-full border-b border-transparent hover:border-blue-200 transition-colors bg-transparent py-1"
                    placeholder="GST/Tax Number"
                  />
                </div>
              </div>

              {/* Invoice Details */}
              <div className="text-right">
                <h1 className="text-5xl font-bold gradient-text mb-6">INVOICE</h1>
                <div className="space-y-3">
                  <div className="flex justify-end items-center gap-3">
                    <span className="text-slate-600 font-medium">Invoice #:</span>
                    <input
                      type="text"
                      value={invoiceDetails.number}
                      onChange={(e) => setInvoiceDetails({...invoiceDetails, number: e.target.value})}
                      className="mono font-bold text-slate-900 border-b-2 border-transparent hover:border-blue-200 transition-colors bg-transparent text-right"
                      placeholder="INV-001"
                    />
                  </div>
                  <div className="flex justify-end items-center gap-3">
                    <span className="text-slate-600 font-medium">Date:</span>
                    <input
                      type="date"
                      value={invoiceDetails.date}
                      onChange={(e) => setInvoiceDetails({...invoiceDetails, date: e.target.value})}
                      className="text-slate-900 border-b-2 border-transparent hover:border-blue-200 transition-colors bg-transparent"
                    />
                  </div>
                  <div className="flex justify-end items-center gap-3">
                    <span className="text-slate-600 font-medium">Due Date:</span>
                    <input
                      type="date"
                      value={invoiceDetails.dueDate}
                      onChange={(e) => setInvoiceDetails({...invoiceDetails, dueDate: e.target.value})}
                      className="text-slate-900 border-b-2 border-transparent hover:border-blue-200 transition-colors bg-transparent"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Bill To */}
          <div className="mb-8">
            <h2 className="text-sm font-semibold text-blue-600 uppercase tracking-wider mb-4">Bill To</h2>
            <div className="grid md:grid-cols-2 gap-4">
              <input
                type="text"
                value={clientInfo.name}
                onChange={(e) => setClientInfo({...clientInfo, name: e.target.value})}
                className="text-xl font-semibold text-slate-900 border-b-2 border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-2"
                placeholder="Client Name *"
              />
              <input
                type="email"
                value={clientInfo.email}
                onChange={(e) => setClientInfo({...clientInfo, email: e.target.value})}
                className="border-b-2 border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-2 text-slate-700"
                placeholder="Client Email"
              />
              <input
                type="text"
                value={clientInfo.address}
                onChange={(e) => setClientInfo({...clientInfo, address: e.target.value})}
                className="border-b-2 border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-2 text-slate-700"
                placeholder="Address"
              />
              <input
                type="text"
                value={clientInfo.phone}
                onChange={(e) => setClientInfo({...clientInfo, phone: e.target.value})}
                className="border-b-2 border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-2 text-slate-700"
                placeholder="Phone"
              />
            </div>
          </div>

          {/* Services Table */}
          <div className="mb-8">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b-2 border-blue-600">
                    <th className="text-left py-3 px-2 text-sm font-semibold text-blue-600 uppercase tracking-wider">Service Description</th>
                    <th className="text-center py-3 px-2 text-sm font-semibold text-blue-600 uppercase tracking-wider w-24">Qty</th>
                    <th className="text-right py-3 px-2 text-sm font-semibold text-blue-600 uppercase tracking-wider w-32">Rate</th>
                    <th className="text-right py-3 px-2 text-sm font-semibold text-blue-600 uppercase tracking-wider w-32">Amount</th>
                    <th className="no-print w-12"></th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  {services.map((service, index) => (
                    <tr key={service.id} className="group hover:bg-blue-50/50 transition-colors">
                      <td className="py-3 px-2">
                        <select
                          value={service.description}
                          onChange={(e) => {
                            if (e.target.value === 'custom') {
                              updateService(service.id, 'description', '');
                            } else if (e.target.value) {
                              selectPredefinedService(service.id, e.target.value);
                            } else {
                              updateService(service.id, 'description', '');
                            }
                          }}
                          className="w-full border-b border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-1 text-slate-900"
                        >
                          <option value="">Select a service...</option>
                          {predefinedServices.map(ps => (
                            <option key={ps} value={ps}>{ps}</option>
                          ))}
                          <option value="custom">Custom Service...</option>
                        </select>
                        {service.description && !predefinedServices.includes(service.description) && (
                          <input
                            type="text"
                            value={service.description}
                            onChange={(e) => updateService(service.id, 'description', e.target.value)}
                            className="w-full mt-2 border-b border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-1 text-slate-900"
                            placeholder="Enter custom service description"
                          />
                        )}
                      </td>
                      <td className="py-3 px-2">
                        <input
                          type="number"
                          min="1"
                          value={service.quantity}
                          onChange={(e) => updateService(service.id, 'quantity', parseFloat(e.target.value) || 1)}
                          className="w-full text-center border-b border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-1"
                        />
                      </td>
                      <td className="py-3 px-2">
                        <input
                          type="number"
                          min="0"
                          step="1"
                          value={service.rate}
                          onChange={(e) => updateService(service.id, 'rate', parseFloat(e.target.value) || 0)}
                          className="w-full text-right mono border-b border-slate-200 hover:border-blue-400 transition-colors bg-transparent py-1"
                          placeholder="Enter rate"
                        />
                      </td>
                      <td className="py-3 px-2 text-right mono font-semibold text-slate-900">
                        UGX {service.amount.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0})}
                      </td>
                      <td className="no-print py-3 px-2">
                        <button
                          onClick={() => removeService(service.id)}
                          className="text-red-500 hover:text-red-700 opacity-0 group-hover:opacity-100 transition-opacity"
                          disabled={services.length === 1}
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <button
              onClick={addService}
              className="no-print mt-4 flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium transition-colors"
            >
              <Plus className="w-4 h-4" />
              Add Service
            </button>
          </div>

          {/* Totals */}
          <div className="flex justify-end mb-8">
            <div className="w-full md:w-96 space-y-3">
              <div className="flex justify-between items-center py-2 border-b border-slate-200">
                <span className="text-slate-600 font-medium">Subtotal:</span>
                <span className="mono text-lg font-semibold text-slate-900">UGX {subtotal.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0})}</span>
              </div>
              <div className="flex justify-between items-center py-2 border-b border-slate-200">
                <div className="flex items-center gap-3">
                  <span className="text-slate-600 font-medium">Tax/GST:</span>
                  <input
                    type="number"
                    min="0"
                    max="100"
                    step="0.01"
                    value={taxRate}
                    onChange={(e) => setTaxRate(parseFloat(e.target.value) || 0)}
                    className="w-16 text-center border-b border-slate-200 hover:border-blue-400 transition-colors bg-transparent"
                  />
                  <span className="text-slate-600">%</span>
                </div>
                <span className="mono text-lg font-semibold text-slate-900">UGX {taxAmount.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0})}</span>
              </div>
              <div className="flex justify-between items-center py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg px-4">
                <span className="font-bold text-lg">Total Amount:</span>
                <span className="mono text-2xl font-bold">UGX {total.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0})}</span>
              </div>
            </div>
          </div>

          {/* Payment Terms */}
          <div className="border-t-2 border-slate-200 pt-6">
            <h3 className="font-semibold text-slate-900 mb-2">Payment Terms & Notes</h3>
            <textarea
              className="w-full border border-slate-200 rounded-lg p-3 text-slate-700 hover:border-blue-400 focus:border-blue-500 transition-colors resize-none"
              rows="3"
              placeholder="Payment is due within 30 days. Please make checks payable to [Company Name]. Late payments may incur additional charges."
              defaultValue="Payment is due within 30 days. Please make checks payable to TechFix Solutions."
            />
          </div>

          {/* Footer */}
          <div className="mt-8 text-center text-sm text-slate-500">
            <p>Thank you for your business!</p>
            <p className="mt-1">For questions about this invoice, please contact {companyInfo.email}</p>
          </div>
        </div>
      </div>
    </div>
  );
}