'use client'

import { useState, useRef, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { 
  Zap, 
  ArrowLeft,
  Plus,
  Trash2,
  Download,
  FileText
} from 'lucide-react'

import { toast } from '@/components/ui/use-toast'

// Invoice item type
interface InvoiceItem {
  id: string
  description: string
  qty: number
  price: number
}

// Teal color for PDF (avoiding lab color function error)
const TEAL_COLOR = '#0d9488'
const TEAL_DARK = '#0f766e'
const TEAL_LIGHT = '#ccfbf1'
const GRAY_50 = '#f9fafb'
const GRAY_100 = '#f3f4f6'
const GRAY_200 = '#e5e7eb'
const GRAY_300 = '#d1d5db'
const GRAY_400 = '#9ca3af'
const GRAY_500 = '#6b7280'
const GRAY_600 = '#4b5563'
const GRAY_700 = '#374151'
const GRAY_800 = '#1f2937'
const GRAY_900 = '#111827'
const WHITE = '#ffffff'

export default function FakturPage() {
  const printRef = useRef<HTMLDivElement>(null)
  const [logo, setLogo] = useState<string | null>(null)
  const [logoFile, setLogoFile] = useState<File | null>(null)
  const [companyName, setCompanyName] = useState('PT. Contoh Perusahaan')
    const [clientName, setClientName] = useState('')
    const [invoiceNumber, setInvoiceNumber] = useState('FAK-001')
    const [invoiceDate, setInvoiceDate] = useState(new Date().toISOString().split('T')[0])
    const [taxEnabled, setTaxEnabled] = useState(false)
    const [taxRate, setTaxRate] = useState('11')
    const [items, setItems] = useState<InvoiceItem[]>([
        { id: '1', description: '', qty: 1, price: 0 }
    ])
    const [toastMessage, setToastMessage] = useState('')

    // Generate unique ID
    const generateId = () => Math.random().toString(36).substr(2, 9)

    // Handle logo upload
    const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (file) {
            setLogoFile(file)
            const reader = new FileReader()
            reader.onloadend = () => {
                setLogo(reader.result as string)
            }
            reader.readAsDataURL(file)
        }
    }

    // Add new item
    const addItem = () => {
        setItems([...items, { id: generateId(), description: '', qty: 1, price: 0 }])
    }

    // Remove item
    const removeItem = (id: string) => {
        if (items.length > 1) {
            setItems(items.filter(item => item.id !== id))
        } else {
            setToastMessage('Minimal 1 item harus ada')
        }
    }

    // Update item
    const updateItem = (id: string, field: keyof InvoiceItem, value: string | number) => {
        setItems(items.map(item => 
            item.id === id ? { ...item, [field]: value } : item
        ))
    }

    // Calculate subtotal
    const calculateSubtotal = () => {
        return items.reduce((sum, item) => sum + (item.qty * item.price), 0)
    }

    // Calculate tax
    const calculateTax = () => {
        if (!taxEnabled) return 0
        return calculateSubtotal() * (parseInt(taxRate) / 100)
    }

    // Calculate total
    const calculateTotal = () => {
        return calculateSubtotal() + calculateTax()
    }

    // Format currency
    const formatCurrency = (amount: number) => {
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0,
        }).format(amount)
    }

    // Format date
    const formatDate = (dateString: string) => {
        const date = new Date(dateString)
        return date.toLocaleDateString('id-ID', {
            day: 'numeric',
            month: 'long',
            year: 'numeric'
        })
    }

    // Generate PDF
    const generatePDF = async () => {
        if (typeof window !== 'undefined' && printRef.current) {
            try {
                const html2pdf = (await import('html2pdf.js')).default
                const element = printRef.current
                
                const opt = {
                    margin: 0,
                    filename: `faktur-${invoiceNumber}.pdf`,
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: { 
                        scale: 2, 
                        useCORS: true,
                        backgroundColor: WHITE,
                    },
                    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
                }

                await html2pdf().set(opt).from(element).save()
                setToastMessage('PDF berhasil diunduh!')
            } catch (error) {
                console.error('Error generating PDF:', error)
                setToastMessage('Gagal membuat PDF')
            }
        }
    }

    // Show toast
    const showToast = (message: string) => {
        if (toastMessage) {
            setToastMessage('')
        }
        setTimeout(() => setToastMessage(message), 10)
    }

    return (
        <div className="min-h-screen flex flex-col bg-gray-50">
            {/* Header */}
            <header className="sticky top-0 z-50 bg-white shadow-sm border-b border-gray-200">
                <nav style={{ maxWidth: '1280px', margin: '0 auto', padding: '0 1rem' }}>
                    <div className="flex justify-between items-center h-16">
                        <div className="flex items-center gap-4">
                            <Link href="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
                                <Zap className="h-8 w-8 text-teal-600" />
                                <span className="text-xl font-bold text-gray-900">Admin Kilat</span>
                            </Link>
                            <span className="text-gray-300">|</span>
                            <h1 className="text-lg font-semibold text-gray-700">Pembuatan Faktur</h1>
                        </div>
                        <div className="flex items-center gap-2">
                            <Link href="/">
                                <Button variant="outline" size="sm">
                                    <ArrowLeft className="h-4 w-4 mr-1" />
                                    Kembali
                                </Button>
                            </Link>
                            <Button onClick={generatePDF} className="bg-teal-600 hover:bg-teal-700">
                                <Download className="h-4 w-4 mr-2" />
                                Download PDF
                            </Button>
                        </div>
                    </div>
                </nav>
            </header>

            {/* Main Content */}
            <main className="flex-grow py-6">
                <div style={{ maxWidth: '1400px', margin: '0 auto', padding: '0 1rem' }}>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {/* Left: Form Input */}
                        <div className="space-y-4">
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-lg">Informasi Faktur</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    {/* Logo Upload */}
                                    <div className="space-y-2">
                                        <Label htmlFor="logo">Logo Perusahaan</Label>
                                        <Input
                                            id="logo"
                                            type="file"
                                            accept="image/*"
                                            onChange={handleLogoUpload}
                                        />
                                        {logo && (
                                            <div className="mt-2 relative w-24 h-24 border rounded-lg overflow-hidden">
                                                <img src={logo} alt="Logo" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                                            </div>
                                        )}
                                    </div>

                                    {/* Company Name */}
                                    <div className="space-y-2">
                                        <Label htmlFor="companyName">Nama Perusahaan</Label>
                                        <Input
                                            id="companyName"
                                            value={companyName}
                                            onChange={(e) => setCompanyName(e.target.value)}
                                            placeholder="Nama Perusahaan Anda"
                                        />
                                    </div>

                                    {/* Client Name */}
                                    <div className="space-y-2">
                                        <Label htmlFor="clientName">Nama Klien</Label>
                                        <Input
                                            id="clientName"
                                            value={clientName}
                                            onChange={(e) => setClientName(e.target.value)}
                                            placeholder="Nama Klien"
                                        />
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        {/* Invoice Number */}
                                        <div className="space-y-2">
                                            <Label htmlFor="invoiceNumber">Nomor Faktur</Label>
                                            <Input
                                                id="invoiceNumber"
                                                value={invoiceNumber}
                                                onChange={(e) => setInvoiceNumber(e.target.value)}
                                                placeholder="FAK-001"
                                            />
                                        </div>

                                        {/* Date */}
                                        <div className="space-y-2">
                                            <Label htmlFor="invoiceDate">Tanggal</Label>
                                            <Input
                                                id="invoiceDate"
                                                type="date"
                                                value={invoiceDate}
                                                onChange={(e) => setInvoiceDate(e.target.value)}
                                            />
                                        </div>
                                    </div>

                                    {/* Tax Options */}
                                    <div style={{ padding: '1rem', backgroundColor: GRAY_50, borderRadius: '0.5rem' }}>
                                        <div className="flex items-center space-x-2">
                                            <Checkbox
                                                id="taxEnabled"
                                                checked={taxEnabled}
                                                onCheckedChange={(checked) => setTaxEnabled(checked as boolean)}
                                            />
                                            <Label htmlFor="taxEnabled" style={{ cursor: 'pointer' }}>
                                                Gunakan Pajak (PPN)
                                            </Label>
                                        </div>
                                        
                                        {taxEnabled && (
                                            <div className="space-y-2 mt-3">
                                                <Label>Tarif Pajak</Label>
                                                <Select value={taxRate} onValueChange={setTaxRate}>
                                                    <SelectTrigger>
                                                        <SelectValue />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        <SelectItem value="11">11%</SelectItem>
                                                        <SelectItem value="12">12%</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                            </div>
                                        )}
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Items */}
                            <Card>
                                <CardHeader style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <CardTitle className="text-lg">Daftar Barang/Jasa</CardTitle>
                                    <Button size="sm" variant="outline" onClick={addItem}>
                                        <Plus className="h-4 w-4 mr-1" />
                                        Tambah Item
                                    </Button>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                    {items.map((item, index) => (
                                        <div key={item.id} style={{ padding: '0.75rem', backgroundColor: GRAY_50, borderRadius: '0.5rem' }} className="space-y-3">
                                            <div className="flex items-center justify-between">
                                                <span style={{ fontSize: '0.875rem', fontWeight: 500, color: GRAY_500 }}>Item {index + 1}</span>
                                                {items.length > 1 && (
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        style={{ color: '#ef4444' }}
                                                        onClick={() => removeItem(item.id)}
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                )}
                                            </div>
                                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0.5rem' }}>
                                                <div style={{ gridColumn: 'span 3' }}>
                                                    <Input
                                                        placeholder="Deskripsi Barang/Jasa"
                                                        value={item.description}
                                                        onChange={(e) => updateItem(item.id, 'description', e.target.value)}
                                                    />
                                                </div>
                                                <div>
                                                    <Label style={{ fontSize: '0.75rem', color: GRAY_500 }}>Qty</Label>
                                                    <Input
                                                        type="number"
                                                        min="1"
                                                        value={item.qty}
                                                        onChange={(e) => updateItem(item.id, 'qty', parseInt(e.target.value) || 0)}
                                                    />
                                                </div>
                                                <div>
                                                    <Label style={{ fontSize: '0.75rem', color: GRAY_500 }}>Harga</Label>
                                                    <Input
                                                        type="number"
                                                        min="0"
                                                        value={item.price || ''}
                                                        onChange={(e) => updateItem(item.id, 'price', parseInt(e.target.value) || 0)}
                                                        placeholder="0"
                                                    />
                                                </div>
                                                <div>
                                                    <Label style={{ fontSize: '0.75rem', color: GRAY_500 }}>Total</Label>
                                                    <div style={{ height: '2.25rem', padding: '0 0.75rem', backgroundColor: GRAY_100, borderRadius: '0.375rem', fontSize: '0.875rem', color: GRAY_600, display: 'flex', alignItems: 'center' }}>
                                                        {formatCurrency(item.qty * item.price)}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </CardContent>
                            </Card>
                        </div>

                        {/* Right: Preview */}
                        <div style={{ position: 'sticky', top: '6rem', alignSelf: 'start' }}>
                            <Card style={{ borderWidth: '2px', borderColor: GRAY_200 }}>
                                <CardHeader style={{ backgroundColor: GRAY_100 }}>
                                    <CardTitle className="text-lg flex items-center gap-2">
                                        <FileText className="h-5 w-5" />
                                        Preview Faktur
                                    </CardTitle>
                                </CardHeader>
                                <CardContent style={{ padding: 0 }}>
                                    {/* Invoice Preview - Using inline styles with hex colors */}
                                    <div 
                                        ref={printRef}
                                        style={{ 
                                            backgroundColor: WHITE, 
                                            padding: '2rem', 
                                            minHeight: '297mm',
                                            fontSize: '0.875rem',
                                            width: '210mm', 
                                            maxWidth: '100%', 
                                            margin: '0 auto',
                                            fontFamily: 'Arial, sans-serif'
                                        }}
                                    >
                                        {/* Header */}
                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '2rem', paddingBottom: '1rem', borderBottom: '2px solid ' + TEAL_COLOR }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                                                {logo ? (
                                                    <img src={logo} alt="Logo" style={{ height: '4rem', width: 'auto', objectFit: 'contain' }} />
                                                ) : (
                                                    <div style={{ width: '4rem', height: '4rem', backgroundColor: TEAL_LIGHT, borderRadius: '0.5rem', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                                        <Zap style={{ height: '2rem', width: '2rem', color: TEAL_COLOR }} />
                                                    </div>
                                                )}
                                                <div>
                                                    <h1 style={{ fontSize: '1.25rem', fontWeight: 'bold', color: GRAY_900 }}>{companyName || 'Nama Perusahaan'}</h1>
                                                </div>
                                            </div>
                                            <div style={{ textAlign: 'right' }}>
                                                <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: TEAL_COLOR }}>FAKTUR</h2>
                                                <p style={{ color: GRAY_500, marginTop: '0.25rem' }}>#{invoiceNumber}</p>
                                            </div>
                                        </div>

                                        {/* Invoice Details */}
                                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '2rem', marginBottom: '2rem' }}>
                                            <div>
                                                <p style={{ fontSize: '0.75rem', color: GRAY_500, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.25rem' }}>Kepada:</p>
                                                <p style={{ fontWeight: '600', color: GRAY_900 }}>{clientName || 'Nama Klien'}</p>
                                            </div>
                                            <div style={{ textAlign: 'right' }}>
                                                <p style={{ fontSize: '0.75rem', color: GRAY_500, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.25rem' }}>Tanggal:</p>
                                                <p style={{ fontWeight: '600', color: GRAY_900 }}>{formatDate(invoiceDate)}</p>
                                            </div>
                                        </div>

                                        {/* Items Table */}
                                        <table style={{ width: '100%', marginBottom: '2rem', borderCollapse: 'collapse' }}>
                                            <thead>
                                                <tr style={{ backgroundColor: TEAL_COLOR, color: WHITE }}>
                                                    <th style={{ textAlign: 'left', padding: '0.75rem', borderRadius: '0.5rem 0 0' }}>Deskripsi</th>
                                                    <th style={{ textAlign: 'center', padding: '0.75rem', width: '5rem' }}>Qty</th>
                                                    <th style={{ textAlign: 'right', padding: '0.75rem', width: '8rem' }}>Harga</th>
                                                    <th style={{ textAlign: 'right', padding: '0.75rem', width: '8rem', borderRadius: '0 0.5rem 0 0' }}>Total</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {items.map((item, index) => (
                                                    <tr key={item.id} style={{ backgroundColor: index % 2 === 0 ? GRAY_50 : WHITE }}>
                                                        <td style={{ padding: '0.75rem' }}>{item.description || '-'}</td>
                                                        <td style={{ padding: '0.75rem', textAlign: 'center' }}>{item.qty}</td>
                                                        <td style={{ padding: '0.75rem', textAlign: 'right' }}>{formatCurrency(item.price)}</td>
                                                        <td style={{ padding: '0.75rem', textAlign: 'right', fontWeight: '500' }}>{formatCurrency(item.qty * item.price)}</td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>

                                        {/* Totals */}
                                        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                            <div style={{ width: '16rem' }}>
                                                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0' }}>
                                                    <span style={{ color: GRAY_600 }}>Subtotal:</span>
                                                    <span style={{ fontWeight: '500' }}>{formatCurrency(calculateSubtotal())}</span>
                                                </div>
                                                {taxEnabled && (
                                                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0' }}>
                                                        <span style={{ color: GRAY_600 }}>PPN ({taxRate}%):</span>
                                                        <span style={{ fontWeight: '500' }}>{formatCurrency(calculateTax())}</span>
                                                    </div>
                                                )}
                                                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.75rem 0', borderTop: '2px solid ' + TEAL_COLOR }}>
                                                    <span style={{ fontSize: '1.125rem', fontWeight: 'bold', color: GRAY_900 }}>Total:</span>
                                                    <span style={{ fontSize: '1.125rem', fontWeight: 'bold', color: TEAL_COLOR }}>{formatCurrency(calculateTotal())}</span>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Footer */}
                                        <div style={{ marginTop: '4rem', paddingTop: '2rem', borderTop: '1px solid ' + GRAY_200, textAlign: 'center' }}>
                                            <p style={{ color: GRAY_500, fontSize: '0.75rem' }}>
                                                Terima kasih atas kepercayaan Anda kepada {companyName}
                                            </p>
                                            <p style={{ color: GRAY_400, fontSize: '0.75rem', marginTop: '0.5rem' }}>
                                                Dokumen ini dibuat menggunakan AdminKilat.com
                                            </p>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        </div>
                    </div>
                </div>
            </main>

            {/* Toast notification */}
            {toastMessage && (
                <div style={{
                    position: 'fixed',
                    bottom: '1rem',
                    right: '1rem',
                    padding: '0.75rem 1rem',
                    backgroundColor: toastMessage.includes('berhasil') ? TEAL_COLOR : '#ef4444',
                    color: WHITE,
                    borderRadius: '0.5rem',
                    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                    zIndex: 50
                }}>
                    {toastMessage}
                </div>
            )}
        </div>
    )
}
