package com.example.myapplication

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.github.gcacace.signaturepad.views.SignaturePad
import com.itextpdf.io.image.ImageDataFactory
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.*
import com.itextpdf.layout.property.HorizontalAlignment
import com.itextpdf.layout.property.UnitValue
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private lateinit var edtTarih: EditText
    private lateinit var edtMusteriAd: EditText
    private lateinit var edtMusteriMail: EditText
    private lateinit var edtTeknisyenAd: EditText
    private lateinit var edtCihazModel: EditText
    private lateinit var edtIslem: EditText
    private lateinit var padTeknisyen: SignaturePad
    private lateinit var padMusteri: SignaturePad

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Tanımlamalar
        edtTarih = findViewById(R.id.edtTarih)
        edtMusteriAd = findViewById(R.id.edtMusteriAd)
        edtMusteriMail = findViewById(R.id.edtMusteriMail)
        edtTeknisyenAd = findViewById(R.id.edtTeknisyenAd)
        edtCihazModel = findViewById(R.id.edtCihazModel)
        edtIslem = findViewById(R.id.edtIslem)
        padTeknisyen = findViewById(R.id.padTeknisyen)
        padMusteri = findViewById(R.id.padMusteri)

        // Bugünün tarihini otomatik yaz
        val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
        edtTarih.setText(sdf.format(Date()))

        findViewById<Button>(R.id.btnKaydet).setOnClickListener {
            if (edtMusteriAd.text.isEmpty() || padTeknisyen.isEmpty || padMusteri.isEmpty) {
                Toast.makeText(this, "Eksik alanları doldurun!", Toast.LENGTH_SHORT).show()
            } else {
                generatePdfAndSendEmail()
            }
        }
    }

    private fun generatePdfAndSendEmail() {
        try {
            val fileName = "Servis_Formu_${edtMusteriAd.text.toString().replace(" ", "_")}.pdf"
            val pdfFile = File(getExternalFilesDir(null), fileName)

            val writer = PdfWriter(FileOutputStream(pdfFile))
            val pdf = PdfDocument(writer)
            val document = Document(pdf)

            // 1. Font Ayarı (Türkçe Karakter İçin) - arial.ttf assets klasöründe olmalı
            val fontBytes = assets.open("arial.ttf").readBytes()
            val fontProgram = com.itextpdf.io.font.FontProgramFactory.createFont(fontBytes)
            val turkishFont = com.itextpdf.kernel.font.PdfFontFactory.createFont(
                fontProgram, com.itextpdf.io.font.PdfEncodings.IDENTITY_H,
                com.itextpdf.kernel.font.PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED
            )
            document.setFont(turkishFont)

            // 2. Logo
            try {
                val d = resources.getDrawable(R.drawable.logo1, null)
                val bitmap = (d as BitmapDrawable).bitmap
                val stream = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                val logo = Image(ImageDataFactory.create(stream.toByteArray()))
                    .scaleToFit(120f, 60f)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER)
                document.add(logo)
            } catch (e: Exception) {}

            document.add(Paragraph("TEKNİK SERVİS FORMU")
                .setBold().setFontSize(18f)
                .setTextAlignment(com.itextpdf.layout.property.TextAlignment.CENTER))

            // 3. Tablo
            val table = Table(UnitValue.createPercentArray(floatArrayOf(100f))).useAllAvailableWidth()
            table.addCell(Cell().add(Paragraph("TARİH: ${edtTarih.text}")))
            table.addCell(Cell().add(Paragraph("MÜŞTERİ: ${edtMusteriAd.text}").setBold()))
            table.addCell(Cell().add(Paragraph("MÜŞTERİ MAİL: ${edtMusteriMail.text}")))
            table.addCell(Cell().add(Paragraph("TEKNİSYEN: ${edtTeknisyenAd.text}")))
            table.addCell(Cell().add(Paragraph("CİHAZ: ${edtCihazModel.text}")))
            table.addCell(Cell().add(Paragraph("YAPILAN İŞLEMLER:\n${edtIslem.text}").setPaddingBottom(10f)))
            document.add(table)

            // 4. İmzalar
            val signTable = Table(2).useAllAvailableWidth().setMarginTop(20f)
            val tSign = Image(ImageDataFactory.create(bitmapToByteArray(padTeknisyen.signatureBitmap))).scaleToFit(120f, 80f)
            val mSign = Image(ImageDataFactory.create(bitmapToByteArray(padMusteri.signatureBitmap))).scaleToFit(120f, 80f)

            signTable.addCell(Cell().add(Paragraph("Teknisyen İmzası")).add(tSign).setTextAlignment(com.itextpdf.layout.property.TextAlignment.CENTER))
            signTable.addCell(Cell().add(Paragraph("Müşteri İmzası")).add(mSign).setTextAlignment(com.itextpdf.layout.property.TextAlignment.CENTER))
            document.add(signTable)
            val zeroWasteSeparator = LineSeparator(com.itextpdf.kernel.pdf.canvas.draw.SolidLine(0.5f))
                .setMarginTop(20f)
                .setMarginBottom(10f)
            document.add(zeroWasteSeparator)

            val zeroWasteMessage = Paragraph()
                .add("🌱 Bu form dijital olarak oluşturulmuştur. ")
                .add("Kağıt kullanımını engelleyerek doğayı koruduğunuz için teşekkür ederiz. ")
                .add("Sıfır Atık projesini destekliyoruz.")
                .setItalic()
                .setFontSize(10f)
                .setFontColor(com.itextpdf.kernel.colors.DeviceRgb(34, 139, 34)) // Yeşil renk (Forest Green)
                .setTextAlignment(com.itextpdf.layout.property.TextAlignment.CENTER)

            document.add(zeroWasteMessage)  

            document.close()

            // 5. Mail Gönderimini Başlat
            initiateEmail(pdfFile)

        } catch (e: Exception) {
            Toast.makeText(this, "Hata: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    private fun initiateEmail(file: File) {
        val uri = FileProvider.getUriForFile(this, "$packageName.fileprovider", file)
        val customerEmail = edtMusteriMail.text.toString()

        val emailIntent = Intent(Intent.ACTION_SEND).apply {
            type = "application/pdf"
            // Alıcı olarak hem müşteriyi hem de yedek için kendinizi ekleyebilirsiniz
            putExtra(Intent.EXTRA_EMAIL, arrayOf(customerEmail))
            putExtra(Intent.EXTRA_SUBJECT, "Servis Formu - ${edtCihazModel.text}")

            val body = "Sayın ${edtMusteriAd.text},\n\nServis işleminiz tamamlanmıştır. Detaylı servis formu ektedir.\n\nİyi çalışmalar."
            putExtra(Intent.EXTRA_TEXT, body)
            putExtra(Intent.EXTRA_STREAM, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }

        try {
            startActivity(Intent.createChooser(emailIntent, "Mail Gönderiliyor..."))
        } catch (e: Exception) {
            Toast.makeText(this, "Mail uygulaması bulunamadı!", Toast.LENGTH_SHORT).show()
        }
    }

    private fun bitmapToByteArray(bitmap: Bitmap): ByteArray {
        val stream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
        return stream.toByteArray()
    }
}