'use client'

import { useState, useRef } from 'react'
import Link from 'next/link'
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 { 
  Zap, 
  ArrowLeft,
  Plus,
  Trash2,
  Download,
  FileText,
  Building2,
  User,
  Wallet,
  TrendingDown
} from 'lucide-react'

// Color constants (hex format for html2canvas compatibility)
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'

// Types
interface IncomeItem {
  id: string
  name: string
  amount: number
}

interface DeductionItem {
  id: string
  name: string
  amount: number
}

interface SlipData {
  logo: string | null
  companyName: string
  period: string
  employeeName: string
  employeeId: string
}

const generateId = () => Math.random().toString(36).substr(2, 9)

// Default income items
const defaultIncomes: IncomeItem[] = [
  { id: generateId(), name: 'Gaji Pokok', amount: 0 },
  { id: generateId(), name: 'Tunjangan Makan', amount: 0 },
  { id: generateId(), name: 'Tunjangan Transport', amount: 0 },
]

// Default deduction items
const defaultDeductions: DeductionItem[] = [
  { id: generateId(), name: 'BPJS Kesehatan', amount: 0 },
  { id: generateId(), name: 'BPJS Ketenagakerjaan', amount: 0 },
  { id: generateId(), name: 'PPh 21', amount: 0 },
]

export default function SlipGajiPage() {
  const printRef = useRef<HTMLDivElement>(null)
  const [toastMessage, setToastMessage] = useState('')
  
  // Header state
  const [slipData, setSlipData] = useState<SlipData>({
    logo: null,
    companyName: '',
    period: '',
    employeeName: '',
    employeeId: '',
  })

  // Income items
  const [incomes, setIncomes] = useState<IncomeItem[]>(defaultIncomes)

  // Deduction items
  const [deductions, setDeductions] = useState<DeductionItem[]>(defaultDeductions)

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

  // Update slip data
  const updateSlipData = (field: keyof SlipData, value: string) => {
    setSlipData({ ...slipData, [field]: value })
  }

  // Income functions
  const addIncome = () => {
    setIncomes([...incomes, { id: generateId(), name: '', amount: 0 }])
  }

  const removeIncome = (id: string) => {
    if (incomes.length > 1) {
      setIncomes(incomes.filter(item => item.id !== id))
    } else {
      setToastMessage('Minimal 1 item pendapatan harus ada')
      setTimeout(() => setToastMessage(''), 3000)
    }
  }

  const updateIncome = (id: string, field: keyof IncomeItem, value: string | number) => {
    setIncomes(incomes.map(item => 
      item.id === id ? { ...item, [field]: value } : item
    ))
  }

  // Deduction functions
  const addDeduction = () => {
    setDeductions([...deductions, { id: generateId(), name: '', amount: 0 }])
  }

  const removeDeduction = (id: string) => {
    if (deductions.length > 1) {
      setDeductions(deductions.filter(item => item.id !== id))
    } else {
      setToastMessage('Minimal 1 item potongan harus ada')
      setTimeout(() => setToastMessage(''), 3000)
    }
  }

  const updateDeduction = (id: string, field: keyof DeductionItem, value: string | number) => {
    setDeductions(deductions.map(item => 
      item.id === id ? { ...item, [field]: value } : item
    ))
  }

  // Calculate totals
  const calculateTotalIncome = () => {
    return incomes.reduce((sum, item) => sum + (item.amount || 0), 0)
  }

  const calculateTotalDeduction = () => {
    return deductions.reduce((sum, item) => sum + (item.amount || 0), 0)
  }

  const calculateNetSalary = () => {
    return calculateTotalIncome() - calculateTotalDeduction()
  }

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

  // Format period
  const formatPeriod = (periodString: string) => {
    if (!periodString) return '-'
    const [year, month] = periodString.split('-')
    const date = new Date(parseInt(year), parseInt(month) - 1)
    return date.toLocaleDateString('id-ID', { 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: `slip-gaji-${slipData.employeeName.replace(/\s+/g, '-') || 'karyawan'}-${slipData.period || 'document'}.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('Slip Gaji berhasil diunduh!')
        setTimeout(() => setToastMessage(''), 3000)
      } catch (error) {
        console.error('Error generating PDF:', error)
        setToastMessage('Gagal membuat PDF')
        setTimeout(() => setToastMessage(''), 3000)
      }
    }
  }

  return (
    <div className="min-h-screen flex flex-col" style={{ backgroundColor: GRAY_50 }}>
      {/* Header */}
      <header style={{ position: 'sticky', top: 0, zIndex: 50, backgroundColor: WHITE, boxShadow: '0 1px 2px rgba(0,0,0,0.05)', borderBottom: `1px solid ${GRAY_200}` }}>
        <nav style={{ maxWidth: '1400px', margin: '0 auto', padding: '0 1rem' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '4rem' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
              <Link href="/" style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', textDecoration: 'none' }}>
                <Zap style={{ height: '2rem', width: '2rem', color: TEAL_COLOR }} />
                <span style={{ fontSize: '1.25rem', fontWeight: 'bold', color: GRAY_900 }}>Admin Kilat</span>
              </Link>
              <span style={{ color: GRAY_300 }}>|</span>
              <h1 style={{ fontSize: '1.125rem', fontWeight: 600, color: GRAY_700 }}>Pembuatan Slip Gaji</h1>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <Link href="/">
                <Button variant="outline" size="sm">
                  <ArrowLeft style={{ height: '1rem', width: '1rem', marginRight: '0.25rem' }} />
                  Kembali
                </Button>
              </Link>
              <Button onClick={generatePDF} style={{ backgroundColor: TEAL_COLOR, color: WHITE }} className="hover:bg-teal-700">
                <Download style={{ height: '1rem', width: '1rem', marginRight: '0.5rem' }} />
                Download PDF
              </Button>
            </div>
          </div>
        </nav>
      </header>

      {/* Main Content */}
      <main style={{ flexGrow: 1, padding: '1.5rem 0' }}>
        <div style={{ maxWidth: '1400px', margin: '0 auto', padding: '0 1rem' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(1, 1fr)', gap: '1.5rem' }} className="lg:grid-cols-2">
            {/* Left: Form Input */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              {/* Header Info */}
              <Card>
                <CardHeader>
                  <CardTitle style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1.125rem' }}>
                    <Building2 style={{ height: '1.25rem', width: '1.25rem', color: TEAL_COLOR }} />
                    Informasi Header
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(1, 1fr)', gap: '1rem' }} className="md:grid-cols-2">
                    {/* Logo Upload */}
                    <div style={{ gridColumn: 'span 1' }} className="md:col-span-2">
                      <Label htmlFor="logo">Logo Perusahaan</Label>
                      <Input
                        id="logo"
                        type="file"
                        accept="image/*"
                        onChange={handleLogoUpload}
                        style={{ marginTop: '0.25rem' }}
                      />
                      {slipData.logo && (
                        <div style={{ marginTop: '0.5rem', width: '6rem', height: '6rem', borderRadius: '0.5rem', overflow: 'hidden', border: `1px solid ${GRAY_200}` }}>
                          <img src={slipData.logo} alt="Logo" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                        </div>
                      )}
                    </div>

                    {/* Company Name */}
                    <div style={{ gridColumn: 'span 1' }} className="md:col-span-2">
                      <Label htmlFor="companyName">Nama Perusahaan</Label>
                      <Input
                        id="companyName"
                        value={slipData.companyName}
                        onChange={(e) => updateSlipData('companyName', e.target.value)}
                        placeholder="PT. Contoh Perusahaan"
                        style={{ marginTop: '0.25rem' }}
                      />
                    </div>

                    {/* Period */}
                    <div style={{ gridColumn: 'span 1' }} className="md:col-span-2">
                      <Label htmlFor="period">Periode Gaji</Label>
                      <Input
                        id="period"
                        type="month"
                        value={slipData.period}
                        onChange={(e) => updateSlipData('period', e.target.value)}
                        style={{ marginTop: '0.25rem' }}
                      />
                    </div>

                    {/* Employee Name */}
                    <div>
                      <Label htmlFor="employeeName">Nama Karyawan</Label>
                      <Input
                        id="employeeName"
                        value={slipData.employeeName}
                        onChange={(e) => updateSlipData('employeeName', e.target.value)}
                        placeholder="John Doe"
                        style={{ marginTop: '0.25rem' }}
                      />
                    </div>

                    {/* Employee ID */}
                    <div>
                      <Label htmlFor="employeeId">ID Karyawan</Label>
                      <Input
                        id="employeeId"
                        value={slipData.employeeId}
                        onChange={(e) => updateSlipData('employeeId', e.target.value)}
                        placeholder="EMP-001"
                        style={{ marginTop: '0.25rem' }}
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Income Section */}
              <Card>
                <CardHeader style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                  <CardTitle style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1.125rem' }}>
                    <Wallet style={{ height: '1.25rem', width: '1.25rem', color: '#22c55e' }} />
                    Pendapatan
                  </CardTitle>
                  <Button size="sm" variant="outline" onClick={addIncome}>
                    <Plus style={{ height: '1rem', width: '1rem', marginRight: '0.25rem' }} />
                    Tambah
                  </Button>
                </CardHeader>
                <CardContent>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                    {incomes.map((item, index) => (
                      <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                        <span style={{ fontSize: '0.75rem', color: GRAY_500, width: '1.5rem' }}>{index + 1}.</span>
                        <Input
                          value={item.name}
                          onChange={(e) => updateIncome(item.id, 'name', e.target.value)}
                          placeholder="Nama Item"
                          style={{ flex: 1 }}
                        />
                        <Input
                          type="number"
                          value={item.amount || ''}
                          onChange={(e) => updateIncome(item.id, 'amount', parseInt(e.target.value) || 0)}
                          placeholder="0"
                          style={{ width: '10rem' }}
                        />
                        {incomes.length > 1 && (
                          <Button
                            size="sm"
                            variant="ghost"
                            style={{ color: '#ef4444' }}
                            onClick={() => removeIncome(item.id)}
                          >
                            <Trash2 style={{ height: '1rem', width: '1rem' }} />
                          </Button>
                        )}
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: '0.75rem', borderTop: `1px solid ${GRAY_200}` }}>
                      <div style={{ fontSize: '0.875rem', fontWeight: 600, color: '#22c55e' }}>
                        Total Pendapatan: {formatCurrency(calculateTotalIncome())}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Deduction Section */}
              <Card>
                <CardHeader style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                  <CardTitle style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1.125rem' }}>
                    <TrendingDown style={{ height: '1.25rem', width: '1.25rem', color: '#ef4444' }} />
                    Potongan
                  </CardTitle>
                  <Button size="sm" variant="outline" onClick={addDeduction}>
                    <Plus style={{ height: '1rem', width: '1rem', marginRight: '0.25rem' }} />
                    Tambah
                  </Button>
                </CardHeader>
                <CardContent>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                    {deductions.map((item, index) => (
                      <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                        <span style={{ fontSize: '0.75rem', color: GRAY_500, width: '1.5rem' }}>{index + 1}.</span>
                        <Input
                          value={item.name}
                          onChange={(e) => updateDeduction(item.id, 'name', e.target.value)}
                          placeholder="Nama Item"
                          style={{ flex: 1 }}
                        />
                        <Input
                          type="number"
                          value={item.amount || ''}
                          onChange={(e) => updateDeduction(item.id, 'amount', parseInt(e.target.value) || 0)}
                          placeholder="0"
                          style={{ width: '10rem' }}
                        />
                        {deductions.length > 1 && (
                          <Button
                            size="sm"
                            variant="ghost"
                            style={{ color: '#ef4444' }}
                            onClick={() => removeDeduction(item.id)}
                          >
                            <Trash2 style={{ height: '1rem', width: '1rem' }} />
                          </Button>
                        )}
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: '0.75rem', borderTop: `1px solid ${GRAY_200}` }}>
                      <div style={{ fontSize: '0.875rem', fontWeight: 600, color: '#ef4444' }}>
                        Total Potongan: {formatCurrency(calculateTotalDeduction())}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Right: Preview */}
            <div style={{ position: 'sticky', top: '5rem', alignSelf: 'start' }}>
              <Card style={{ borderWidth: '2px', borderColor: GRAY_200 }}>
                <CardHeader style={{ backgroundColor: GRAY_100 }}>
                  <CardTitle style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1.125rem' }}>
                    <FileText style={{ height: '1.25rem', width: '1.25rem' }} />
                    Preview Slip Gaji
                  </CardTitle>
                </CardHeader>
                <CardContent style={{ padding: 0 }}>
                  {/* Slip 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', alignItems: 'center', gap: '1rem', marginBottom: '1.5rem', paddingBottom: '1rem', borderBottom: `2px solid ${TEAL_COLOR}` }}>
                      {slipData.logo ? (
                        <img src={slipData.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' }}>
                          <Building2 style={{ height: '2rem', width: '2rem', color: TEAL_COLOR }} />
                        </div>
                      )}
                      <div>
                        <h1 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: GRAY_900 }}>{slipData.companyName || 'Nama Perusahaan'}</h1>
                        <p style={{ color: GRAY_500, marginTop: '0.25rem' }}>SLIP GAJI</p>
                      </div>
                    </div>

                    {/* Period Badge */}
                    <div style={{ textAlign: 'right', marginBottom: '1.5rem' }}>
                      <span style={{ 
                        backgroundColor: TEAL_LIGHT, 
                        color: TEAL_DARK, 
                        padding: '0.5rem 1rem', 
                        borderRadius: '0.5rem',
                        fontWeight: 600
                      }}>
                        Periode: {formatPeriod(slipData.period)}
                      </span>
                    </div>

                    {/* Employee Info */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '1rem', marginBottom: '2rem', padding: '1rem', backgroundColor: GRAY_50, borderRadius: '0.5rem' }}>
                      <div>
                        <p style={{ fontSize: '0.75rem', color: GRAY_500, marginBottom: '0.25rem' }}>Nama Karyawan</p>
                        <p style={{ fontWeight: 600, color: GRAY_900 }}>{slipData.employeeName || '-'}</p>
                      </div>
                      <div>
                        <p style={{ fontSize: '0.75rem', color: GRAY_500, marginBottom: '0.25rem' }}>ID Karyawan</p>
                        <p style={{ fontWeight: 600, color: GRAY_900 }}>{slipData.employeeId || '-'}</p>
                      </div>
                    </div>

                    {/* Income & Deduction Tables */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '1.5rem', marginBottom: '1.5rem' }}>
                      {/* Income Table */}
                      <div>
                        <h3 style={{ fontSize: '0.875rem', fontWeight: 'bold', color: '#22c55e', marginBottom: '0.75rem', textTransform: 'uppercase' }}>
                          Pendapatan
                        </h3>
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                          <thead>
                            <tr style={{ backgroundColor: '#f0fdf4' }}>
                              <th style={{ textAlign: 'left', padding: '0.5rem', border: `1px solid ${GRAY_200}`, fontSize: '0.75rem' }}>Item</th>
                              <th style={{ textAlign: 'right', padding: '0.5rem', border: `1px solid ${GRAY_200}`, fontSize: '0.75rem' }}>Nominal</th>
                            </tr>
                          </thead>
                          <tbody>
                            {incomes.filter(i => i.name || i.amount).map((item) => (
                              <tr key={item.id}>
                                <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}` }}>{item.name || '-'}</td>
                                <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}`, textAlign: 'right' }}>{formatCurrency(item.amount)}</td>
                              </tr>
                            ))}
                            <tr style={{ backgroundColor: '#f0fdf4', fontWeight: 'bold' }}>
                              <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}` }}>Total</td>
                              <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}`, textAlign: 'right', color: '#22c55e' }}>{formatCurrency(calculateTotalIncome())}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>

                      {/* Deduction Table */}
                      <div>
                        <h3 style={{ fontSize: '0.875rem', fontWeight: 'bold', color: '#ef4444', marginBottom: '0.75rem', textTransform: 'uppercase' }}>
                          Potongan
                        </h3>
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                          <thead>
                            <tr style={{ backgroundColor: '#fef2f2' }}>
                              <th style={{ textAlign: 'left', padding: '0.5rem', border: `1px solid ${GRAY_200}`, fontSize: '0.75rem' }}>Item</th>
                              <th style={{ textAlign: 'right', padding: '0.5rem', border: `1px solid ${GRAY_200}`, fontSize: '0.75rem' }}>Nominal</th>
                            </tr>
                          </thead>
                          <tbody>
                            {deductions.filter(i => i.name || i.amount).map((item) => (
                              <tr key={item.id}>
                                <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}` }}>{item.name || '-'}</td>
                                <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}`, textAlign: 'right' }}>{formatCurrency(item.amount)}</td>
                              </tr>
                            ))}
                            <tr style={{ backgroundColor: '#fef2f2', fontWeight: 'bold' }}>
                              <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}` }}>Total</td>
                              <td style={{ padding: '0.5rem', border: `1px solid ${GRAY_200}`, textAlign: 'right', color: '#ef4444' }}>{formatCurrency(calculateTotalDeduction())}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>

                    {/* Net Salary */}
                    <div style={{ 
                      backgroundColor: TEAL_COLOR, 
                      color: WHITE, 
                      padding: '1rem 1.5rem', 
                      borderRadius: '0.5rem', 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      marginBottom: '2rem'
                    }}>
                      <span style={{ fontSize: '1.125rem', fontWeight: 'bold' }}>GAJI BERSIH</span>
                      <span style={{ fontSize: '1.5rem', fontWeight: 'bold' }}>{formatCurrency(calculateNetSalary())}</span>
                    </div>

                    {/* Footer */}
                    <div style={{ marginTop: '2rem', paddingTop: '1rem', borderTop: `1px solid ${GRAY_200}`, textAlign: 'center' }}>
                      <p style={{ color: GRAY_400, fontSize: '0.7rem' }}>
                        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>
  )
}
