from fastapi import APIRouter, Depends, Query, HTTPException, UploadFile, File, Form
from sqlmodel import Session, select
import os
import shutil
from uuid import uuid4, UUID
from typing import List, Optional
from app.core.database import get_session
from app.models.taxi import Taxi
from app.api.deps import get_current_admin

router = APIRouter(prefix="/api/taxis", tags=["taxis"])

UPLOAD_DIR = "uploads"


@router.get("", response_model=List[Taxi])
async def get_taxis(
    corregimiento: Optional[str] = Query(None),
    shift: Optional[str] = Query(None),
    english_speaking: Optional[bool] = Query(None),
    is_active: Optional[bool] = Query(None),
    session: Session = Depends(get_session)
):
    """Get all taxis with optional filters."""
    try:
        statement = select(Taxi)
        
        if is_active is not None:
            statement = statement.where(Taxi.is_active == is_active)
        
        if corregimiento:
            statement = statement.where(Taxi.corregimiento.contains(corregimiento))
        
        if shift:
            statement = statement.where(Taxi.shift == shift)
        
        if english_speaking is not None:
            statement = statement.where(Taxi.english_speaking == english_speaking)
            
        taxis = session.exec(statement).all()
        return taxis
    except Exception as e:
        print(f"Error fetching taxis: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("")
async def create_taxi(
    owner_name: str = Form(...),
    phone_number: str = Form(...),
    license_plate: str = Form(...),
    corregimiento: str = Form(...),
    shift: str = Form(...),
    cooperative: Optional[str] = Form(None),
    rating: float = Form(5.0),
    english_speaking: bool = Form(False),
    is_active: bool = Form(True),
    image: Optional[UploadFile] = File(None),
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Create a new taxi entry (Admin only)."""
    image_url = None
    if image:
        ext = os.path.splitext(image.filename)[1]
        filename = f"{uuid4()}{ext}"
        path = os.path.join(UPLOAD_DIR, "profiles", filename)
        with open(path, "wb") as buffer:
            shutil.copyfileobj(image.file, buffer)
        image_url = f"/uploads/profiles/{filename}"
    
    taxi = Taxi(
        owner_name=owner_name,
        phone_number=phone_number,
        license_plate=license_plate,
        cooperative=cooperative,
        corregimiento=corregimiento,
        shift=shift,
        rating=rating,
        english_speaking=english_speaking,
        image_url=image_url,
        is_active=is_active
    )
    session.add(taxi)
    session.commit()
    session.refresh(taxi)
    return taxi


@router.put("/{taxi_id}", response_model=Taxi)
async def update_taxi(
    taxi_id: UUID,
    owner_name: str = Form(...),
    phone_number: str = Form(...),
    license_plate: str = Form(...),
    corregimiento: str = Form(...),
    shift: str = Form(...),
    cooperative: Optional[str] = Form(None),
    rating: float = Form(5.0),
    english_speaking: bool = Form(False),
    is_active: bool = Form(True),
    image: Optional[UploadFile] = File(None),
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Update a taxi entry (Admin only)."""
    db_taxi = session.get(Taxi, taxi_id)
    if not db_taxi:
        raise HTTPException(status_code=404, detail="Taxi not found")
    
    # Update fields
    db_taxi.owner_name = owner_name
    db_taxi.phone_number = phone_number
    db_taxi.license_plate = license_plate
    db_taxi.corregimiento = corregimiento
    db_taxi.shift = shift
    db_taxi.cooperative = cooperative
    db_taxi.rating = rating
    db_taxi.english_speaking = english_speaking
    db_taxi.is_active = is_active
    
    # Handle image upload
    if image:
        ext = os.path.splitext(image.filename)[1]
        filename = f"{uuid4()}{ext}"
        path = os.path.join(UPLOAD_DIR, "profiles", filename)
        with open(path, "wb") as buffer:
            shutil.copyfileobj(image.file, buffer)
        db_taxi.image_url = f"/uploads/profiles/{filename}"
    
    session.add(db_taxi)
    session.commit()
    session.refresh(db_taxi)
    return db_taxi


@router.delete("/{taxi_id}")
async def delete_taxi(
    taxi_id: UUID,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Delete a taxi entry (Admin only)."""
    db_taxi = session.get(Taxi, taxi_id)
    if not db_taxi:
        raise HTTPException(status_code=404, detail="Taxi not found")
    session.delete(db_taxi)
    session.commit()
    return {"ok": True}
