import 'dart:io';
import 'dart:math' as math;
import 'dart:ui';

import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:perfect_freehand/perfect_freehand.dart' as pf;
import 'package:syncfusion_flutter_pdf/pdf.dart';

import '../editor/engine/stroke_geometry.dart' show freehandOutlinePoints;
import '../models/ink_stroke.dart';
import '../models/pen_tool.dart';

/// Service for PDF operations: file picking, info extraction, and annotation export.
class PdfService {
  /// Pick a PDF file path using the cross-platform file_picker.
  Future<String?> pickPdfFile() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf'],
    );
    final files = result?.files;
    if (files == null || files.isEmpty) return null;
    return files.first.path;
  }

  /// Get the page count of the PDF at [filePath].
  Future<int> getPageCount(String filePath) async {
    final bytes = await File(filePath).readAsBytes();
    final document = PdfDocument(inputBytes: bytes);
    try {
      return document.pages.count;
    } finally {
      document.dispose();
    }
  }

  /// Get basic info about a PDF file: fileName and fileSize.
  Future<Map<String, dynamic>> getPdfInfo(String filePath) async {
    final file = File(filePath);
    final fileSize = await file.length();
    return {'fileName': p.basename(filePath), 'fileSize': fileSize};
  }

  /// Export an annotated PDF by drawing ink strokes onto each page.
  ///
  /// [annotations] maps page index (0-based) to lists of [InkStroke].
  /// Stroke coordinates are normalized to [0, 1] relative to the annotation
  /// overlay size used during capture, and are scaled to actual PDF page
  /// dimensions during export.
  ///
  /// Returns the path to the exported annotated PDF.
  Future<String> exportAnnotatedPdf(
    String filePath,
    Map<int, List<InkStroke>> annotations,
  ) async {
    final bytes = await File(filePath).readAsBytes();
    final document = PdfDocument(inputBytes: bytes);
    try {
      for (final entry in annotations.entries) {
        final pageIndex = entry.key;
        final strokes = entry.value;
        if (strokes.isEmpty) continue;
        if (pageIndex >= document.pages.count) continue;

        final page = document.pages[pageIndex];
        _renderStrokes(page, strokes);
      }

      final outputDir = await getTemporaryDirectory();
      final baseName = p.basenameWithoutExtension(filePath);
      final outputPath = p.join(outputDir.path, '${baseName}_annotated.pdf');
      final savedBytes = await document.save();
      await File(outputPath).writeAsBytes(savedBytes, flush: true);

      return outputPath;
    } finally {
      document.dispose();
    }
  }

  /// Delete a page at [pageIndex]. Returns true on success.
  Future<bool> deletePage(String filePath, int pageIndex) async {
    try {
      final bytes = await File(filePath).readAsBytes();
      final document = PdfDocument(inputBytes: bytes);
      try {
        if (pageIndex < 0 || pageIndex >= document.pages.count) {
          return false;
        }
        document.pages.removeAt(pageIndex);
        final outputBytes = await document.save();
        await File(filePath).writeAsBytes(outputBytes, flush: true);
        return true;
      } finally {
        document.dispose();
      }
    } catch (_) {
      return false;
    }
  }

  /// Insert a blank A4 page (595 x 842 pt) after [afterIndex].
  /// Returns true on success.
  Future<bool> insertBlankPage(String filePath, int afterIndex) async {
    try {
      final bytes = await File(filePath).readAsBytes();
      final document = PdfDocument(inputBytes: bytes);
      final insertAt = (afterIndex + 1).clamp(0, document.pages.count);
      document.pages.insert(insertAt);
      final outputBytes = await document.save();
      document.dispose();
      await File(filePath).writeAsBytes(outputBytes, flush: true);
      return true;
    } catch (_) {
      return false;
    }
  }

  /// Rotate page at [pageIndex] 90 degrees clockwise.
  /// Returns true on success.
  Future<bool> rotatePage(String filePath, int pageIndex) async {
    try {
      final bytes = await File(filePath).readAsBytes();
      final document = PdfDocument(inputBytes: bytes);
      try {
        if (pageIndex < 0 || pageIndex >= document.pages.count) {
          return false;
        }
        final page = document.pages[pageIndex];
        final current = page.rotation;
        // Cycle through: 0 -> 90 -> 180 -> 270 -> 0
        switch (current) {
          case PdfPageRotateAngle.rotateAngle0:
            page.rotation = PdfPageRotateAngle.rotateAngle90;
          case PdfPageRotateAngle.rotateAngle90:
            page.rotation = PdfPageRotateAngle.rotateAngle180;
          case PdfPageRotateAngle.rotateAngle180:
            page.rotation = PdfPageRotateAngle.rotateAngle270;
          case PdfPageRotateAngle.rotateAngle270:
            page.rotation = PdfPageRotateAngle.rotateAngle0;
        }
        final outputBytes = await document.save();
        await File(filePath).writeAsBytes(outputBytes, flush: true);
        return true;
      } finally {
        document.dispose();
      }
    } catch (_) {
      return false;
    }
  }

  /// Draw an image from [imagePath] onto the page at [pageIndex],
  /// fitted to the page dimensions while preserving aspect ratio.
  /// Returns the [pdfPath] on success, null on failure.
  Future<String?> insertImageOnPage(
    String pdfPath,
    int pageIndex,
    String imagePath,
  ) async {
    try {
      final pdfBytes = await File(pdfPath).readAsBytes();
      final document = PdfDocument(inputBytes: pdfBytes);
      try {
        if (pageIndex < 0 || pageIndex >= document.pages.count) {
          return null;
        }
        final page = document.pages[pageIndex];
        final imageBytes = await File(imagePath).readAsBytes();
        final pdfImage = PdfBitmap(imageBytes);
        final pageSize = page.getClientSize();

        // Fit the image to the page while preserving its aspect ratio
        // (letterboxed and centered), rather than stretching it to fill.
        final imageWidth = pdfImage.width.toDouble();
        final imageHeight = pdfImage.height.toDouble();
        final scale = (imageWidth <= 0 || imageHeight <= 0)
            ? 1.0
            : math.min(
                pageSize.width / imageWidth,
                pageSize.height / imageHeight,
              );
        final drawWidth = imageWidth * scale;
        final drawHeight = imageHeight * scale;
        final left = (pageSize.width - drawWidth) / 2;
        final top = (pageSize.height - drawHeight) / 2;

        page.graphics.drawImage(
          pdfImage,
          Rect.fromLTWH(left, top, drawWidth, drawHeight),
        );
        final outputBytes = await document.save();
        await File(pdfPath).writeAsBytes(outputBytes, flush: true);
        return pdfPath;
      } finally {
        document.dispose();
      }
    } catch (_) {
      return null;
    }
  }

  /// Renders [strokes] onto a PDF [page] using normalized [0, 1] coordinates
  /// scaled to the actual page dimensions.
  ///
  /// Freehand tools (pen, marker, highlighter) are rendered as filled outline
  /// polygons produced by perfect_freehand's [getStroke], matching the
  /// on-screen filled-nib appearance. Shape tools and text keep their existing
  /// pen-stroke semantics.
  void _renderStrokes(PdfPage page, List<InkStroke> strokes) {
    final graphics = page.graphics;
    final pageSize = page.getClientSize();

    for (final stroke in strokes) {
      if (stroke.points.isEmpty) continue;

      final color = stroke.color;
      final r = (color >> 16) & 0xFF;
      final g = (color >> 8) & 0xFF;
      final b = color & 0xFF;
      final a = (color >> 24) & 0xFF;
      final pdfColor = PdfColor(r, g, b, a);

      final isFreehand = stroke.tool == PenTool.pen ||
          stroke.tool == PenTool.marker ||
          stroke.tool == PenTool.highlighter;

      if (isFreehand) {
        final brush = PdfSolidBrush(pdfColor);

        if (stroke.points.length == 1) {
          // Single point — filled dot matching stroke width.
          final pt = stroke.points.first;
          final radius = stroke.strokeWidth / 2;
          graphics.drawEllipse(
            Rect.fromCenter(
              center: Offset(pt.x * pageSize.width, pt.y * pageSize.height),
              width: radius * 2,
              height: radius * 2,
            ),
            brush: brush,
          );
        } else {
          final pdfPath = _buildFreehandPdfPath(stroke, pageSize);
          if (pdfPath != null) {
            graphics.drawPath(pdfPath, brush: brush);
          }
        }
      } else {
        // Shape tools and text: keep existing pen-segment semantics.
        final pen = PdfPen(pdfColor);
        pen.width = stroke.strokeWidth.clamp(1.0, 8.0);

        if (stroke.points.length == 1) {
          final pt = stroke.points.first;
          graphics.drawEllipse(
            Rect.fromCenter(
              center: Offset(pt.x * pageSize.width, pt.y * pageSize.height),
              width: stroke.strokeWidth,
              height: stroke.strokeWidth,
            ),
            pen: pen,
          );
        } else {
          for (int i = 0; i < stroke.points.length - 1; i++) {
            final p1 = stroke.points[i];
            final p2 = stroke.points[i + 1];
            graphics.drawLine(
              pen,
              Offset(p1.x * pageSize.width, p1.y * pageSize.height),
              Offset(p2.x * pageSize.width, p2.y * pageSize.height),
            );
          }
        }
      }
    }
  }

  /// Builds a [PdfPath] filled outline polygon for a freehand [stroke] using
  /// perfect_freehand's [getStroke], matching the on-screen recipe from
  /// [lib/editor/engine/stroke_geometry.dart].
  ///
  /// Points are scaled from normalized [0,1] coords into PDF-point space
  /// defined by [pageSize] before being passed to [getStroke], so the
  /// resulting outline is already in PDF coordinates.
  ///
  /// Returns null when [getStroke] produces an empty outline.
  PdfPath? _buildFreehandPdfPath(InkStroke stroke, Size pageSize) {
    final isHighlighter = stroke.tool == PenTool.highlighter;
    final pixelWidth = stroke.strokeWidth * pageSize.width;

    // Detect real stylus pressure: the InkPoint default is 0.5, so any point
    // that differs from the default indicates actual device pressure data.
    final hasRealPressure = stroke.points.any((pt) => pt.pressure != 0.5);

    final pfPoints = stroke.points
        .map(
          (pt) => pf.PointVector(
            pt.x * pageSize.width,
            pt.y * pageSize.height,
            pt.pressure,
          ),
        )
        .toList();

    // ONE shared recipe with the on-screen painter (R7): export can no longer
    // drift from screen. Previously this hardcoded thinning:0.7/streamline:0.5,
    // which diverged from the screen's 0.85/0.32 → hairline export mismatch.
    final outline = freehandOutlinePoints(
      pfPoints: pfPoints,
      size: pixelWidth,
      isHighlighter: isHighlighter,
      hasRealPressure: hasRealPressure,
      isComplete: true,
    );

    if (outline.isEmpty) return null;

    final path = PdfPath();
    // outline is already List<Offset> in perfect_freehand 2.x.
    path.addPolygon(outline.toList());
    return path;
  }
}
