package com.draw.painting.line.ui;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.Nullable;

public class DeerDrawView extends View {
    
    private Paint paint;
    private Path bodyPath;
    private Path legsPath;
    private Path headPath;
    private Path antlersPath;
    private Path detailsPath; // 眼睛和鼻子
    
    private float bodyProgress = 0f;
    private float legsProgress = 0f;
    private float headProgress = 0f;
    private float antlersProgress = 0f;
    private float detailsProgress = 0f;
    
    private boolean isAnimating = false;
    
    public DeerDrawView(Context context) {
        super(context);
        init();
    }
    
    public DeerDrawView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public DeerDrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    
    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(0xFF2F3A3A); // 深灰色
        float density = getContext().getResources().getDisplayMetrics().density;
        paint.setStrokeWidth(2f * density); // 2px
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeJoin(Paint.Join.ROUND);
        
        createDeerPaths();
    }
    
    private void createDeerPaths() {
        // Layer 1: 身体主轮廓（第一个画，定形态、定情绪）
        // M60 140 C90 120, 140 120, 165 135 C175 140, 175 155, 160 160 C130 170, 90 165, 70 155
        bodyPath = new Path();
        bodyPath.moveTo(60, 140);
        bodyPath.cubicTo(90, 120, 140, 120, 165, 135);
        bodyPath.cubicTo(175, 140, 175, 155, 160, 160);
        bodyPath.cubicTo(130, 170, 90, 165, 70, 155);
        bodyPath.close();
        
        // Layer 2: 腿部（第二阶段，前腿 → 后腿）
        // front leg: M90 155 L85 185, M100 155 L95 185
        // back leg: M140 155 L135 185, M150 155 L145 185
        legsPath = new Path();
        // 前腿
        legsPath.moveTo(90, 155);
        legsPath.lineTo(85, 185);
        legsPath.moveTo(100, 155);
        legsPath.lineTo(95, 185);
        // 后腿
        legsPath.moveTo(140, 155);
        legsPath.lineTo(135, 185);
        legsPath.moveTo(150, 155);
        legsPath.lineTo(145, 185);
        
        // Layer 3: 头部 + 脖子（第三阶段，头微微向前）
        // M165 135 C175 120, 190 110, 205 112 C215 115, 215 130, 200 135 C190 138, 180 140, 170 145
        headPath = new Path();
        headPath.moveTo(165, 135);
        headPath.cubicTo(175, 120, 190, 110, 205, 112);
        headPath.cubicTo(215, 115, 215, 130, 200, 135);
        headPath.cubicTo(190, 138, 180, 140, 170, 145);
        
        // Layer 4: 鹿角（第四阶段，简化2-3分叉）
        // M195 108 C190 90, 180 80, 170 75
        // M195 108 C200 90, 210 85, 220 80
        antlersPath = new Path();
        // 左角
        antlersPath.moveTo(195, 108);
        antlersPath.cubicTo(190, 90, 180, 80, 170, 75);
        // 右角
        antlersPath.moveTo(195, 108);
        antlersPath.cubicTo(200, 90, 210, 85, 220, 80);
        
        // Layer 5: 面部细节（最后出现，情绪点）
        // eye: M198 125 C199 124, 201 124, 202 125
        // nose: M205 130 C206 132, 208 132, 209 130
        detailsPath = new Path();
        // 眼睛（小弧线）
        detailsPath.moveTo(198, 125);
        detailsPath.cubicTo(199, 124, 201, 124, 202, 125);
        // 鼻子（小弧线）
        detailsPath.moveTo(205, 130);
        detailsPath.cubicTo(206, 132, 208, 132, 209, 130);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 路径已经在createDeerPaths中创建，在绘制时会居中缩放
    }
    
    public void startAnimation() {
        if (isAnimating) return;
        isAnimating = true;
        
        // body: 0s, 0.6s duration
        animatePath(bodyPath, 0, 600, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                bodyProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        
        // legs: 0.3s delay, 0.6s duration
        animatePath(legsPath, 300, 600, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                legsProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        
        // head: 0.7s delay, 0.6s duration
        animatePath(headPath, 700, 600, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                headProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        
        // antlers: 1.1s delay, 0.6s duration
        animatePath(antlersPath, 1100, 600, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                antlersProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        
        // face: 1.5s delay, 0.6s duration (稍慢，治愈感)
        animatePath(detailsPath, 1500, 600, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                detailsProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
    }
    
    private void animatePath(Path path, long delay, long duration, ValueAnimator.AnimatorUpdateListener listener) {
        ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
        animator.setDuration(duration);
        animator.setStartDelay(delay);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(listener);
        animator.start();
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        if (getWidth() == 0 || getHeight() == 0) return;
        
        // 居中绘制，根据View大小缩放
        canvas.save();
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        
        // 原始路径基于约220x110的尺寸（从60到约220宽，从75到约185高），进行缩放
        float scaleX = getWidth() / 220f;
        float scaleY = getHeight() / 110f;
        float scale = Math.min(scaleX, scaleY) * 0.9f; // 留出边距
        
        canvas.translate(centerX, centerY);
        canvas.scale(scale, scale);
        canvas.translate(-140, -130); // 原始路径中心偏移（约140, 130）
        
        // 绘制身体
        drawPathWithProgress(canvas, bodyPath, bodyProgress);
        
        // 绘制腿部
        drawPathWithProgress(canvas, legsPath, legsProgress);
        
        // 绘制头部
        drawPathWithProgress(canvas, headPath, headProgress);
        
        // 绘制鹿角
        drawPathWithProgress(canvas, antlersPath, antlersProgress);
        
        // 绘制细节（眼睛和鼻子，带透明度效果）
        if (detailsProgress > 0) {
            float alpha = detailsProgress < 0.5f ? detailsProgress * 2f : 1f;
            paint.setAlpha((int) (255 * alpha));
            drawPathWithProgress(canvas, detailsPath, detailsProgress);
            paint.setAlpha(255);
        }
        
        canvas.restore();
    }
    
    private void drawPathWithProgress(Canvas canvas, Path path, float progress) {
        if (progress <= 0) return;
        
        PathMeasure pathMeasure = new PathMeasure(path, false);
        float length = pathMeasure.getLength();
        float distance = length * progress;
        
        Path drawPath = new Path();
        pathMeasure.getSegment(0, distance, drawPath, true);
        canvas.drawPath(drawPath, paint);
    }
}

