import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(CryptoApp());
}

class CryptoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _fileContent = '';
  String _result = '';
  String _error = '';
  final TextEditingController _keyController = TextEditingController();

  Future<void> _pickFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['txt', 'md'],
      );

      if (result != null) {
        File file = File(result.files.single.path!);
        String content = await file.readAsString();
        setState(() {
          _fileContent = content;
          _error = '';
        });
      } else {
        setState(() {
          _error = 'Dosya seçilmedi.';
        });
      }
    } catch (e) {
      setState(() {
        _error = 'Dosya yükleme hatası: $e';
      });
    }
  }

  String encrypt(String message, String key) {
    List<String> words = message.split(' ');
    int keyLength = key.length;
    List<String> encryptedWords = [];

    for (int i = 0; i < words.length; i++) {
      String word = words[i];
      String encryptedWord = '';

      for (int j = 0; j < word.length; j++) {
        int shift = int.tryParse(key[j % keyLength]) ?? 0;
        int charCode = word.codeUnitAt(j);

        if (word[j].isAlphabetic()) {
          int base = word[j].isUpperCase() ? 'A'.codeUnitAt(0) : 'a'.codeUnitAt(0);
          charCode = (charCode - base + shift) % 26 + base;
        } else if (word[j].isDigit()) {
          charCode = (charCode - '0'.codeUnitAt(0) + shift) % 10 + '0'.codeUnitAt(0);
        }

        encryptedWord += String.fromCharCode(charCode);
      }

      encryptedWords.add(encryptedWord);
    }

    return encryptedWords.join(' ');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Crypto App'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _keyController,
              decoration: InputDecoration(
                labelText: 'Anahtar',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton.icon(
              onPressed: _pickFile,
              icon: Icon(Icons.attach_file),
              label: Text('Dosya Seç'),
              style: ElevatedButton.styleFrom(
                minimumSize: Size(double.infinity, 50),
              ),
            ),
            SizedBox(height: 20),
            if (_error.isNotEmpty)
              Text(
                'Hata: $_error',
                style: TextStyle(color: Colors.red),
              ),
            if (_fileContent.isNotEmpty)
              Text(
                'Dosya İçeriği:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            if (_fileContent.isNotEmpty)
              Container(
                padding: EdgeInsets.all(8.0),
                color: Colors.grey[200],
                child: Text(_fileContent),
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _result = encrypt(_fileContent, _keyController.text);
                  Clipboard.setData(ClipboardData(text: _result));
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Şifrelenmiş metin panoya kopyalandı')),
                  );
                });
              },
              child: Text('Şifrele ve Kopyala'),
              style: ElevatedButton.styleFrom(
                minimumSize: Size(double.infinity, 50),
                primary: Colors.blueAccent,
              ),
            ),
            SizedBox(height: 20),
            if (_result.isNotEmpty)
              GestureDetector(
                onTap: () {
                  Clipboard.setData(ClipboardData(text: _result));
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Panoya kopyalandı')),
                  );
                },
                child: Container(
                  padding: EdgeInsets.all(8.0),
                  color: Colors.blue[50],
                  child: Text('Şifrelenmiş Metin: $_result'),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

extension StringExtension on String {
  bool isAlphabetic() {
    return RegExp(r'^[a-zA-Z]$').hasMatch(this);
  }

  bool isUpperCase() {
    return this == this.toUpperCase();
  }

  bool isDigit() {
    return RegExp(r'^[0-9]$').hasMatch(this);
  }
}