from django.contrib import admin
from django.shortcuts import render, redirect
from django.urls import path
from django import forms
from django.contrib import messages
from .models import Candidate, Video, CandidateVideoProgress
from .forms import UploadCSVForm
import pandas as pd
import csv
# from .forms import CandidateUploadForm

# Inline model for CandidateVideoProgress (optional, still needed for detailed candidate view)
class CandidateVideoProgressInline(admin.TabularInline):
    model = CandidateVideoProgress
    extra = 0
    readonly_fields = ['video', 'watched', 'watched_at']
    can_delete = False

class CandidateAdmin(admin.ModelAdmin):
    list_display = ['danone_id', 'full_name', 'candidate_type', 'video_progress']
    search_fields = ['danone_id', 'full_name', 'candidate_type']
    inlines = [CandidateVideoProgressInline]  # Still useful for detailed view, but not in list

    # Custom method to display the video progress on the same page
    def video_progress(self, obj):
        # Get all video progress entries for this candidate
        progress_entries = CandidateVideoProgress.objects.filter(candidate=obj)
        total_videos = progress_entries.count()
        watched_videos = progress_entries.filter(watched=True).count()

        # Format output (e.g., "3/7 videos watched")
        return f"{watched_videos}/{total_videos} videos watched"

    # Set a short description for the column
    video_progress.short_description = 'Video Progress'

    # Add a custom view for uploading CSV
    def upload_csv(self, request):
        if request.method == "POST":
            form = UploadCSVForm(request.POST, request.FILES)
            if form.is_valid():
                csv_file = request.FILES['file']

                # Ensure file is CSV
                if not csv_file.name.endswith('.csv'):
                    self.message_user(request, 'File is not CSV format', level='error')
                    return redirect('admin:upload_csv')

                # Read and process CSV data
                file_data = csv_file.read().decode("utf-8")
                csv_reader = csv.reader(file_data.splitlines())

                # Skip the header
                next(csv_reader, None)

                # Process each row
                for row in csv_reader:
                    if len(row) >= 3:
                        Candidate.objects.update_or_create(
                            danone_id=row[0].strip(),
                            full_name=row[1].strip(),
                            candidate_type=row[2].strip(),
                        )
                self.message_user(request, 'CSV uploaded successfully')
                return redirect('admin:backend_candidate_changelist')
        else:
            form = UploadCSVForm()
        return render(request, 'admin/csv_form.html', {'form': form})

    # Custom admin URL
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('upload-csv/', self.admin_site.admin_view(self.upload_csv), name='upload_csv'),
        ]
        return custom_urls + urls

admin.site.register(Candidate, CandidateAdmin)


# VideoAdmin for managing video uploads independently
@admin.register(Video)
class VideoAdmin(admin.ModelAdmin):
    # Exclude the fields from the form since they are auto-filled
    exclude = ['slug']

    list_display = ['title', 'video_type', 'duration']  # Display in list
    search_fields = ['title']  # Search by video title

    # Point to the custom change form template
    change_form_template = 'admin/backend/video/change_form.html'
