package dto

import (
	"fmt"
	"time"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)

// === DTO Structs ===

type ClosingRelationDTO struct {
	Id   uint   `json:"id"`
	Name string `json:"name"`
}

type ClosingListDTO struct {
	Id          uint                     `json:"id"`
	Name        string                   `json:"name"`
	CreatedUser *userDTO.UserRelationDTO `json:"created_user"`
	CreatedAt   time.Time                `json:"created_at"`
	UpdatedAt   time.Time                `json:"updated_at"`
}

type ClosingDetailDTO struct {
	ClosingListDTO
}

type ClosingListItemDTO struct {
	Id              uint   `json:"id"`
	ProjectName     string `json:"project_name"`
	LocationID      uint   `json:"location_id"`
	LocationName    string `json:"location_name"`
	ProjectCategory string `json:"project_category"`
	Period          int    `json:"period"`
	ClosingDate     string `json:"closing_date"`
	ShedLabel       string `json:"shed_label"`
	ShedCount       int    `json:"shed_count"`
	// SalesPaidAmount      int64  `json:"sales_paid_amount"`
	// SalesRemainingAmount int64  `json:"sales_remaining_amount"`
	// SalesPaymentStatus   string `json:"sales_payment_status"`
	ProjectStatus string `json:"project_status"`
}

type ClosingSummaryDTO struct {
	FlockID uint `json:"flock_id"`
	Period  int  `json:"period"`
	// JenisProduk           string `json:"jenis_produk"`
	// LabelPopulasi         string `json:"label_populasi"`
	Population          int    `json:"population"`
	PopulationFormatted string `json:"population_formatted"`
	ProjectType         string `json:"project_type"`
	ActiveHouseCount    int    `json:"active_house_count"`
	ActiveHouseLabel    string `json:"active_house_label"`
	SalesPaymentStatus  string `json:"sales_payment_status"`
	// StatusPembayaranMitra string `json:"status_pembayaran_mitra"`
	StatusProject string `json:"project_status"`
	StatusClosing string `json:"closing_status"`
}

type ClosingSummaryKandangDTO struct {
	FlockID             uint   `json:"flock_id"`
	Period              int    `json:"period"`
	LocationName        string `json:"location_name"`
	Population          int    `json:"population"`
	PopulationFormatted string `json:"population_formatted"`
	ProjectType         string `json:"project_type"`
	ClosingDate         string `json:"closing_date"`
	KandangName         string `json:"kandang_name"`
	ChickInDate         string `json:"chick_in_date"`
	PicName             string `json:"pic_name"`
	ApprovalDate        string `json:"approval_date"`
	ProjectStatus       string `json:"project_status"`
}

type ClosingPurchaseDTO struct {
	InitialPopulation int     `json:"initial_population"`
	ClaimCulling      int     `json:"claim_culling"`
	FinalPopulation   int     `json:"final_population"`
	FeedIn            float64 `json:"feed_in"`
	FeedUsed          float64 `json:"feed_used"`
	// FeedUsedPerHead   float64 `json:"feed_used_per_head"`
}

type ClosingSalesDTO struct {
	SalesPopulation     int     `json:"sales_population"`
	SalesWeight         float64 `json:"sales_weight"`
	AverageWeight       float64 `json:"avg_weight"`
	AverageSellingPrice float64 `json:"avg_selling_price"`
}

type ClosingEggSalesDTO struct {
	EggPieces           int     `json:"egg_pieces"`
	EggMassKg           float64 `json:"egg_mass"`
	AverageEggWeightKg  float64 `json:"avg_egg_weight"`
	AverageSellingPrice float64 `json:"avg_selling_price"`
}

type ClosingPerformanceDTO struct {
	Depletion     float64 `json:"depletion"`
	Age           float64 `json:"age_day"`
	MortalityStd  float64 `json:"mor_std"`
	MortalityAct  float64 `json:"mor_act"`
	DeffMortality float64 `json:"mor_diff"`
	FcrStd        float64 `json:"fcr_std"`
	FcrAct        float64 `json:"fcr_act"`
	DeffFcr       float64 `json:"fcr_diff"`
	AwgAct        float64 `json:"awg_act"`
	AwgStd        float64 `json:"awg_std"`
	FeedIntake    float64 `json:"feed_intake"`
	FeedIntakeStd float64 `json:"feed_intake_std"`
	HenDayAct     float64 `json:"hen_day_act,omitempty"`
	HendayStd     float64 `json:"hen_day_std"`
	EggMass       float64 `json:"egg_mass,omitempty"`
	EggMassStd    float64 `json:"egg_mass_std"`
	EggWeight     float64 `json:"egg_weight,omitempty"`
	EggWeightStd  float64 `json:"egg_weight_std"`
	HenHouseAct   float64 `json:"hen_housed_act,omitempty"`
	HenHouseStd   float64 `json:"hen_housed_std"`
}

type ClosingSalesGroupDTO struct {
	Chicken ClosingSalesDTO     `json:"chicken"`
	Egg     *ClosingEggSalesDTO `json:"egg,omitempty"`
}

type ClosingProductionReportDTO struct {
	Purchase    ClosingPurchaseDTO    `json:"purchase"`
	Sales       ClosingSalesGroupDTO  `json:"sales"`
	Performance ClosingPerformanceDTO `json:"performance"`
}

func ToClosingSummaryDTO(project entity.ProjectFlock, statusProject, statusClosing string) ClosingSummaryDTO {
	history := project.KandangHistory

	period := maxPeriod(history)
	kandangCount := len(history)
	population := sumPopulation(history)
	populationInt := int(population)

	return ClosingSummaryDTO{
		FlockID: project.Id,
		Period:  period,
		// JenisProduk:               project.Category,
		// LabelPopulasi:         "",
		Population:          populationInt,
		PopulationFormatted: fmt.Sprintf("%d Ekor", populationInt),
		ProjectType:         project.Category,
		ActiveHouseCount:    kandangCount,
		ActiveHouseLabel:    fmt.Sprintf("%d Kandang", kandangCount),
		SalesPaymentStatus:  "Tempo",
		// StatusPembayaranMitra: "",
		StatusProject: statusProject,
		StatusClosing: statusClosing,
	}
}

func ToClosingListItemDTO(project entity.ProjectFlock, projectStatus string) ClosingListItemDTO {
	shedCount := len(project.KandangHistory)

	return ClosingListItemDTO{
		Id:              project.Id,
		ProjectName:     project.FlockName,
		LocationID:      project.LocationId,
		LocationName:    project.Location.Name,
		ProjectCategory: project.Category,
		Period:          maxPeriod(project.KandangHistory),
		ClosingDate:     "17-Nov-2025",
		ShedLabel:       fmt.Sprintf("%d Kandang", shedCount),
		ShedCount:       shedCount,
		// SalesPaidAmount:      21993726,
		// SalesRemainingAmount: 11075919,
		// SalesPaymentStatus:   "Lunas",
		ProjectStatus: projectStatus,
	}
}

func maxPeriod(history []entity.ProjectFlockKandang) int {
	max := 0
	for _, h := range history {
		if h.Period > max {
			max = h.Period
		}
	}
	return max
}

func sumPopulation(history []entity.ProjectFlockKandang) float64 {
	var total float64
	for _, h := range history {
		for _, chickin := range h.Chickins {
			total += chickin.UsageQty
		}
	}
	return total
}

// === Mapper Functions ===

func ToClosingRelationDTO(e entity.ProjectFlock) ClosingRelationDTO {
	return ClosingRelationDTO{
		Id: e.Id,
	}
}

func ToClosingListDTO(e entity.ProjectFlock) ClosingListDTO {
	var createdUser *userDTO.UserRelationDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.CreatedUser)
		createdUser = &mapped
	}

	return ClosingListDTO{
		Id:          e.Id,
		CreatedAt:   e.CreatedAt,
		UpdatedAt:   e.UpdatedAt,
		CreatedUser: createdUser,
	}
}

func ToClosingListDTOs(e []entity.ProjectFlock) []ClosingListDTO {
	result := make([]ClosingListDTO, len(e))
	for i, r := range e {
		result[i] = ToClosingListDTO(r)
	}
	return result
}

func ToClosingDetailDTO(e entity.ProjectFlock) ClosingDetailDTO {
	return ClosingDetailDTO{
		ClosingListDTO: ToClosingListDTO(e),
	}
}

func CalculateAgeFromChickinDataProduksi(projectFlockKandang *entity.ProjectFlockKandang, deliveryDate *time.Time) int {
	if projectFlockKandang == nil || deliveryDate == nil || len(projectFlockKandang.Chickins) == 0 {
		return 0
	}

	earliestChickinDate := projectFlockKandang.Chickins[0].ChickInDate
	for _, chickin := range projectFlockKandang.Chickins {
		if chickin.ChickInDate.Before(earliestChickinDate) {
			earliestChickinDate = chickin.ChickInDate
		}
	}

	ageInDays := int(deliveryDate.Sub(earliestChickinDate).Hours() / 24)
	ageInWeeks := ageInDays / 7
	return ageInWeeks
}
