from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.utils import timezone
import datetime

class Department(models.Model):
    name_en = models.CharField(_("Name (English)"), max_length=100)
    name_ar = models.CharField(_("Name (Arabic)"), max_length=100)
    description = models.TextField(_("Description"), blank=True)

    def __str__(self):
        return f"{self.name_en} / {self.name_ar}"

class JobPosition(models.Model):
    title_en = models.CharField(_("Job Title (English)"), max_length=100)
    title_ar = models.CharField(_("Job Title (Arabic)"), max_length=100)
    department = models.ForeignKey(Department, on_delete=models.CASCADE, related_name='positions', verbose_name=_("Department"))
    
    def __str__(self):
        return f"{self.title_en} / {self.title_ar}"

class Employee(models.Model):
    STATUS_CHOICES = [
        ('active', _('Active')),
        ('on_leave', _('On Leave')),
        ('terminated', _('Terminated')),
        ('resigned', _('Resigned')),
    ]
    GENDER_CHOICES = [
        ('M', _('Male')),
        ('F', _('Female')),
    ]

    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='employee_profile', verbose_name=_("User Account"))
    first_name = models.CharField(_("First Name"), max_length=100)
    last_name = models.CharField(_("Last Name"), max_length=100)
    email = models.EmailField(_("Email"), unique=True)
    phone = models.CharField(_("Phone Number"), max_length=20)
    gender = models.CharField(_("Gender"), max_length=1, choices=GENDER_CHOICES, default='M')
    
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, related_name='employees', verbose_name=_("Department"))
    job_position = models.ForeignKey(JobPosition, on_delete=models.SET_NULL, null=True, blank=True, related_name='employees', verbose_name=_("Job Position"))
    
    hire_date = models.DateField(_("Hire Date"), default=timezone.now)
    salary = models.DecimalField(_("Basic Salary"), max_digits=10, decimal_places=2, default=0)
    status = models.CharField(_("Status"), max_length=20, choices=STATUS_CHOICES, default='active')
    
    address = models.TextField(_("Address"), blank=True)
    date_of_birth = models.DateField(_("Date of Birth"), null=True, blank=True)
    
    # New field for linking with biometric device
    biometric_id = models.IntegerField(_("Biometric Device ID"), null=True, blank=True, help_text=_("The User ID used on the attendance device"))
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

class BiometricDevice(models.Model):
    DEVICE_TYPES = [
        ('zkteco', _('ZKTeco')),
        ('other', _('Other')),
    ]
    STATUS_CHOICES = [
        ('active', _('Active')),
        ('inactive', _('Inactive')),
    ]

    name = models.CharField(_("Device Name"), max_length=100)
    ip_address = models.GenericIPAddressField(_("IP Address"))
    port = models.PositiveIntegerField(_("Port"), default=4370)
    device_type = models.CharField(_("Device Type"), max_length=20, choices=DEVICE_TYPES, default='zkteco')
    status = models.CharField(_("Status"), max_length=20, choices=STATUS_CHOICES, default='active')
    last_sync = models.DateTimeField(_("Last Sync"), null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} ({self.ip_address})"
    
    def sync_data(self):
        """
        Connects to the device and fetches attendance records.
        Returns a summary dictionary: {'new': count, 'total': count, 'error': str}
        """
        if self.device_type != 'zkteco':
            return {'error': 'Only ZKTeco devices are supported for auto-sync currently.'}
            
        from zk import ZK
        
        conn = None
        try:
            conn = ZK(self.ip_address, port=self.port, timeout=10)
            conn.connect()
            # self.status = 'active' # Update status on successful connect
            
            attendance_list = conn.get_attendance()
            
            new_records = 0
            
            for att in attendance_list:
                user_id = att.user_id # String or Int depending on device
                timestamp = att.timestamp
                
                try:
                    # Find employee with this biometric ID
                    # We cast user_id to int to be safe if model is int
                    emp_id = int(user_id)
                    employee = Employee.objects.filter(biometric_id=emp_id).first()
                    
                    if employee:
                        date = timestamp.date()
                        time = timestamp.time()
                        
                        # Get or create attendance record for this day
                        attendance, created = Attendance.objects.get_or_create(
                            employee=employee,
                            date=date,
                            defaults={'device': self}
                        )
                        
                        updated = False
                        # Logic: First punch is check_in, Last punch is check_out
                        if attendance.check_in is None:
                            attendance.check_in = time
                            updated = True
                        elif time < attendance.check_in:
                            # If we found an earlier time, update check_in
                            attendance.check_in = time
                            updated = True
                        
                        if attendance.check_out is None and time > attendance.check_in:
                            attendance.check_out = time
                            updated = True
                        elif attendance.check_out and time > attendance.check_out:
                            attendance.check_out = time
                            updated = True
                            
                        if created:
                            new_records += 1
                        elif updated:
                             attendance.save()
                             
                except ValueError:
                    continue # Skip if user_id is not parseable
                except Exception as e:
                    print(f"Error processing record: {e}")
                    continue

            self.last_sync = timezone.now()
            self.status = 'active'
            self.save()
            
            return {'new': new_records, 'total': len(attendance_list), 'error': None}
            
        except Exception as e:
            self.status = 'inactive'
            self.save()
            return {'error': str(e)}
        finally:
            if conn:
                conn.disconnect()

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='attendances', verbose_name=_("Employee"))
    date = models.DateField(_("Date"), default=timezone.now)
    check_in = models.TimeField(_("Check In"), null=True, blank=True)
    check_out = models.TimeField(_("Check Out"), null=True, blank=True)
    notes = models.TextField(_("Notes"), blank=True)
    device = models.ForeignKey(BiometricDevice, on_delete=models.SET_NULL, null=True, blank=True, related_name='attendances', verbose_name=_("Source Device"))

    class Meta:
        ordering = ['-date']
        unique_together = ['employee', 'date'] # Prevent duplicate rows per day per employee

    def __str__(self):
        return f"{self.employee} - {self.date}"

class LeaveRequest(models.Model):
    LEAVE_TYPES = [
        ('annual', _('Annual Leave')),
        ('sick', _('Sick Leave')),
        ('unpaid', _('Unpaid Leave')),
        ('maternity', _('Maternity Leave')),
        ('other', _('Other')),
    ]
    STATUS_CHOICES = [
        ('pending', _('Pending')),
        ('approved', _('Approved')),
        ('rejected', _('Rejected')),
    ]

    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='leave_requests', verbose_name=_("Employee"))
    leave_type = models.CharField(_("Leave Type"), max_length=20, choices=LEAVE_TYPES, default='annual')
    start_date = models.DateField(_("Start Date"))
    end_date = models.DateField(_("End Date"))
    reason = models.TextField(_("Reason"), blank=True)
    status = models.CharField(_("Status"), max_length=20, choices=STATUS_CHOICES, default='pending')
    approved_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='approved_leaves', verbose_name=_("Approved By"))
    
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.employee} ({self.start_date} to {self.end_date})"

    @property
    def duration_days(self):
        return (self.end_date - self.start_date).days + 1
