import { Component, OnInit } from "@angular/core";
import { CommonModule } from "@angular/common";
import { MatButtonModule } from "@angular/material/button";
import { MatTooltipModule } from "@angular/material/tooltip";
import { MatIconModule } from "@angular/material/icon";
import {
  DataTableComponent,
  RequestFilter,
  TableConfig,
} from "../../../../shared/components/data-table/data-table.component";
import { TitleService } from "../../../../shared/services/theme/title.service";

interface ShopeeRoute {
  id: string;
  orderId: string;
  customerName: string;
  address: string;
  status: 'pending' | 'picked_up' | 'in_transit' | 'delivered' | 'returned';
  estimatedDelivery: Date;
  driverId?: string;
  vehicleId?: string;
  packageType: 'standard' | 'express' | 'same_day';
  weight: number;
  createdAt: Date;
  updatedAt: Date;
}

@Component({
  selector: "app-shopee",
  standalone: true,
  imports: [
    CommonModule,
    DataTableComponent,
    MatButtonModule,
    MatTooltipModule,
    MatIconModule,
  ],
  template: `
    <div class="shopee">
      <div class="header-section">
        <h2>Rotas Shopee</h2>
        <div class="actions">
          <button mat-raised-button color="primary" (click)="addNewRoute()">
            <mat-icon>add</mat-icon>
            Nova Rota
          </button>
          <button mat-raised-button color="accent" (click)="syncRoutes()">
            <mat-icon>sync</mat-icon>
            Sincronizar
          </button>
          <button mat-raised-button (click)="optimizeRoutes()">
            <mat-icon>route</mat-icon>
            Otimizar Rotas
          </button>
        </div>
      </div>

      <app-data-table
        [config]="tableConfig"
        [data]="routes"
        [tableId]="tableId"
        [loading]="isLoading"
        [totalDataItems]="totalItems"
        [currentPage]="currentPage"
        (sortChange)="onSort($event)"
        (pageChange)="onPageChange($event)"
        (filterChange)="onFilter($event)"
        (columnsChange)="onColumnsChange($event)"
        (actionClick)="onActionClick($event)"
        [showRequestFilters]="true"
        [requestFilters]="requestFilters"
        (filterRequested)="handleFilterRequest($event)"
      >
      </app-data-table>
    </div>
  `,
  styles: [
    `
      .shopee {
        padding: 1rem;
      }

      .header-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
      }

      .header-section h2 {
        margin: 0;
        color: var(--text-primary);
      }

      .actions {
        display: flex;
        gap: 0.5rem;
      }

      .status-chip {
        padding: 0.25rem 0.75rem;
        border-radius: 16px;
        font-size: 0.75rem;
        font-weight: 500;
      }

      .status-pending {
        background-color: #fff3cd;
        color: #856404;
      }

      .status-picked_up {
        background-color: #e2e3e5;
        color: #383d41;
      }

      .status-in_transit {
        background-color: #cce5ff;
        color: #004085;
      }

      .status-delivered {
        background-color: #d1edff;
        color: #0c5460;
      }

      .status-returned {
        background-color: #f8d7da;
        color: #721c24;
      }

      .package-express {
        color: #dc3545;
        font-weight: 600;
      }

      .package-same_day {
        color: #fd7e14;
        font-weight: 600;
      }

      .package-standard {
        color: #6c757d;
      }
    `,
  ],
})
export class ShopeeComponent implements OnInit {
  routes: ShopeeRoute[] = [];
  currentPage = 1;
  itemsPerPage = 10;
  totalItems = 0;
  totalPages = 0;
  isLoading = false;
  currentFilters: { [key: string]: string } = {};

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.setTitle("Rotas Shopee");
    this.loadRoutes();
  }

  requestFilters: RequestFilter[] = [
    {
      label: "ID do Pedido",
      field: "orderId",
      type: "text",
    },
    {
      label: "Cliente",
      field: "customerName",
      type: "text",
    },
    {
      label: "Status",
      field: "status",
      type: "text",
    },
    {
      label: "Tipo de Entrega",
      field: "packageType",
      type: "text",
    },
  ];

  handleFilterRequest(filters: { [key: string]: string }) {
    this.currentFilters = filters;
    this.loadRoutes();
  }

  loadRoutes() {
    this.isLoading = true;
    
    // Simulando dados mockados
    setTimeout(() => {
      this.routes = [
        {
          id: '1',
          orderId: 'SP001234',
          customerName: 'Ana Costa',
          address: 'Rua Botafogo, 321 - Botafogo, Rio de Janeiro',
          status: 'pending',
          estimatedDelivery: new Date('2024-12-16'),
          packageType: 'express',
          weight: 2.5,
          createdAt: new Date('2024-12-11'),
          updatedAt: new Date('2024-12-11'),
        },
        {
          id: '2',
          orderId: 'SP001235',
          customerName: 'Carlos Oliveira',
          address: 'Av. Barra da Tijuca, 654 - Barra, Rio de Janeiro',
          status: 'picked_up',
          estimatedDelivery: new Date('2024-12-15'),
          driverId: 'DRV003',
          vehicleId: 'VEH003',
          packageType: 'same_day',
          weight: 1.2,
          createdAt: new Date('2024-12-10'),
          updatedAt: new Date('2024-12-12'),
        },
        {
          id: '3',
          orderId: 'SP001236',
          customerName: 'Lucia Fernandes',
          address: 'Rua Tijuca, 987 - Tijuca, Rio de Janeiro',
          status: 'delivered',
          estimatedDelivery: new Date('2024-12-14'),
          driverId: 'DRV004',
          vehicleId: 'VEH004',
          packageType: 'standard',
          weight: 0.8,
          createdAt: new Date('2024-12-09'),
          updatedAt: new Date('2024-12-14'),
        },
        {
          id: '4',
          orderId: 'SP001237',
          customerName: 'Roberto Silva',
          address: 'Rua Flamengo, 159 - Flamengo, Rio de Janeiro',
          status: 'in_transit',
          estimatedDelivery: new Date('2024-12-15'),
          driverId: 'DRV005',
          vehicleId: 'VEH005',
          packageType: 'express',
          weight: 3.1,
          createdAt: new Date('2024-12-11'),
          updatedAt: new Date('2024-12-13'),
        },
      ];
      
      this.totalItems = this.routes.length;
      this.totalPages = Math.ceil(this.totalItems / this.itemsPerPage);
      this.isLoading = false;
    }, 1000);
  }

  tableConfig: TableConfig = {
    columns: [
      {
        field: "orderId",
        header: "ID do Pedido",
        sortable: true,
        filterable: true,
      },
      {
        field: "customerName",
        header: "Cliente",
        sortable: true,
        filterable: true,
      },
      {
        field: "address",
        header: "Endereço",
        sortable: true,
        filterable: true,
      },
      {
        field: "status",
        header: "Status",
        sortable: true,
        filterable: true,
        label: (data: string) => {
          const statusMap: { [key: string]: string } = {
            pending: 'Pendente',
            picked_up: 'Coletado',
            in_transit: 'Em Trânsito',
            delivered: 'Entregue',
            returned: 'Devolvido'
          };
          return statusMap[data] || data;
        },
      },
      {
        field: "packageType",
        header: "Tipo de Entrega",
        sortable: true,
        filterable: true,
        label: (data: string) => {
          const typeMap: { [key: string]: string } = {
            standard: 'Padrão',
            express: 'Expressa',
            same_day: 'Mesmo Dia'
          };
          return typeMap[data] || data;
        },
      },
      {
        field: "weight",
        header: "Peso (kg)",
        sortable: true,
        filterable: true,
        label: (data: number) => {
          return `${data} kg`;
        },
      },
      {
        field: "estimatedDelivery",
        header: "Entrega Prevista",
        sortable: true,
        filterable: true,
        date: true,
      },
      {
        field: "driverId",
        header: "Motorista",
        sortable: true,
        filterable: true,
      },
      {
        field: "vehicleId",
        header: "Veículo",
        sortable: true,
        filterable: true,
      },
      {
        field: "createdAt",
        header: "Criado em",
        sortable: true,
        filterable: true,
        date: true,
      },
    ],
    pageSize: this.itemsPerPage,
    pageSizeOptions: [5, 10, 25, 50],
    showFirstLastButtons: true,
    actions: [
      {
        icon: "fas fa-edit",
        label: "Editar",
        action: "edit",
      },
      {
        icon: "fas fa-hand-paper",
        label: "Marcar como Coletado",
        action: "pickup",
        show: (row: ShopeeRoute) => row.status === 'pending',
      },
      {
        icon: "fas fa-truck",
        label: "Atribuir Motorista",
        action: "assign",
        show: (row: ShopeeRoute) => row.status === 'pending' || row.status === 'picked_up',
      },
      {
        icon: "fas fa-check",
        label: "Marcar como Entregue",
        action: "deliver",
        show: (row: ShopeeRoute) => row.status === 'in_transit',
      },
      {
        icon: "fas fa-undo",
        label: "Marcar como Devolvido",
        action: "return",
        show: (row: ShopeeRoute) => row.status === 'in_transit',
      },
      {
        icon: "fas fa-eye",
        label: "Visualizar",
        action: "view",
      },
    ],
  };

  tableId = "shopee-routes";

  onSort(event: { field: string; direction: "asc" | "desc" }) {
    const { field, direction } = event;
    this.routes = [...this.routes].sort((a: any, b: any) => {
      const isAsc = direction === "asc";
      return compare(a[field], b[field], isAsc);
    });
  }

  onPageChange(event: { page: number; pageSize: number }) {
    const maxPage = Math.ceil(this.totalItems / event.pageSize);
    const validPage = Math.min(event.page, maxPage);

    if (
      this.currentPage !== validPage ||
      this.itemsPerPage !== event.pageSize
    ) {
      this.currentPage = validPage;
      this.itemsPerPage = event.pageSize;
      this.loadRoutes();
    }
  }

  onFilter(filters: { [key: string]: string }) {
    console.log("Filtros aplicados:", filters);
  }

  onColumnsChange(columns: any[]) {
    this.tableConfig = {
      ...this.tableConfig,
      columns,
    };
  }

  onActionClick(event: { action: string; data: any }) {
    switch (event.action) {
      case "edit":
        this.editRoute(event.data);
        break;
      case "pickup":
        this.markAsPickedUp(event.data);
        break;
      case "assign":
        this.assignDriver(event.data);
        break;
      case "deliver":
        this.markAsDelivered(event.data);
        break;
      case "return":
        this.markAsReturned(event.data);
        break;
      case "view":
        this.viewRoute(event.data);
        break;
    }
  }

  addNewRoute() {
    console.log("Adicionar nova rota Shopee");
  }

  syncRoutes() {
    console.log("Sincronizar rotas com Shopee");
    this.loadRoutes();
  }

  optimizeRoutes() {
    console.log("Otimizar rotas Shopee");
  }

  editRoute(route: ShopeeRoute) {
    console.log("Editar rota:", route);
  }

  markAsPickedUp(route: ShopeeRoute) {
    console.log("Marcar como coletado:", route);
    route.status = 'picked_up';
    route.updatedAt = new Date();
  }

  assignDriver(route: ShopeeRoute) {
    console.log("Atribuir motorista:", route);
  }

  markAsDelivered(route: ShopeeRoute) {
    console.log("Marcar como entregue:", route);
    route.status = 'delivered';
    route.updatedAt = new Date();
  }

  markAsReturned(route: ShopeeRoute) {
    console.log("Marcar como devolvido:", route);
    route.status = 'returned';
    route.updatedAt = new Date();
  }

  viewRoute(route: ShopeeRoute) {
    console.log("Visualizar rota:", route);
  }
}

function compare(a: number | string | Date, b: number | string | Date, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
} 