<template>
  <v-row no-gutters class="border-thin pa-6 rounded-lg">
    <v-col cols="12">
      <!-- Header -->
      <v-row no-gutters class="mb-4" align="center">
        <v-col cols="12" md="6">
          <v-btn
            variant="text"
            prepend-icon="mdi-chevron-left"
            class="text-none"
            @click="goBack"
          >
            Patrol Report Log
          </v-btn>
        </v-col>
        <v-col cols="12" md="6" class="d-flex justify-end">
          <v-btn
            color="primary"
         
            variant="flat"
            size="large"
            class="text-none px-8"
            prepend-icon="mdi-plus"
          >
            Create Routes & Schedule
          </v-btn>
        </v-col>
      </v-row>

      <!-- Tabs -->
      <v-tabs v-model="activeTab" class="mb-6 " bg-color="transparent" grow>
        <v-tab value="patrol" class="text-none border-thin" >Patrol Report</v-tab>
        <v-tab value="daily" class="text-none border-thin">Daily Report</v-tab>
        <v-tab value="monthly" class="text-none border-thin">Monthly Report</v-tab>
      </v-tabs>

      <v-window v-model="activeTab" class="pt-4">
        <!-- Patrol Report Tab -->
        <v-window-item value="patrol">
          <!-- Filters -->
          <v-row no-gutters class="mb-6">
            <v-col cols="12" md="3" class="pr-md-2 mb-2 mb-md-0">
              <v-select
                v-model="selectedRoute"
                :items="routes"
                label="Select Route"
                variant="outlined"
                density="comfortable"
                rounded="lg"
                hide-details
                bg-color="white"
              />
            </v-col>
            <v-col cols="12" md="2" class="px-md-2 mb-2 mb-md-0">
              <v-select
                v-model="selectedTimeRange"
                :items="timeRanges"
                label="Time Range"
                variant="outlined"
                density="comfortable"
                rounded="lg"
                hide-details
                bg-color="white"
              />
            </v-col>
            <v-col cols="12" md="2" class="px-md-2 mb-2 mb-md-0">
              <v-text-field
                v-model="selectedDate"
                type="date"
                variant="outlined"
                density="comfortable"
                rounded="lg"
                hide-details
                bg-color="white"
              />
            </v-col>
            <v-col cols="12" md="3" class="px-md-2 mb-2 mb-md-0">
              <v-btn
                color="primary"
                block
                size="large"
                rounded="lg"
                class="text-none"
                @click="loadReport"
              >
                Select Routes & Schedule
              </v-btn>
            </v-col>
            <v-col cols="12" md="2" class="pl-md-2">
              <v-btn
                variant="outlined"
                block
                size="large"
                rounded="lg"
                class="text-none"
                prepend-icon="mdi-export"
                @click="exportReport"
              >
                Export
              </v-btn>
            </v-col>
          </v-row>

          <v-divider :thickness="1" class="border-opacity-100"></v-divider>


          <!-- Location Card -->
          <v-card
            v-if="locationData"
            class=" text-center pa-8 mt-2"
            variant="flat"
            rounded="lg"
          >
            <v-icon size="64" class="mb-4">mdi-office-building</v-icon>
            <h2 class="text-h5 mb-2">{{ locationData.name }}</h2>
            <p class="text-body-2 text-medium-emphasis">
              {{ locationData.address }}
            </p>
          </v-card>
          <v-divider :thickness="1" class="border-opacity-100 mb-6"></v-divider>
          <!-- Route Summary -->
          <v-card v-if="routeSummary" class="mb-6" variant="flat" rounded="lg">
            <v-card-title class="d-flex justify-space-between align-center">
              <span>Patrol Route Summary: {{ routeSummary.routeName }}</span>
              <span class="text-body-2 text-medium-emphasis">
                Tolerance: {{ routeSummary.tolerance }} mins
              </span>
            </v-card-title>
            <v-card-text class="pa-0">
              <v-table class=" border-thin">
                <thead>
                  <tr>
                    <th>Time</th>
                    <th>Start</th>
                    <th>End</th>
                    <th>Total travel time</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td class="font-weight-medium">Schedule</td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.schedule.start }}
                    </td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.schedule.end }}
                    </td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.schedule.totalTime }}
                    </td>
                  </tr>
                  <tr>
                    <td class="font-weight-medium">Actual</td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.actual.start }}
                    </td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.actual.end }}
                    </td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ routeSummary.actual.totalTime }}
                    </td>
                  </tr>
                </tbody>
              </v-table>
            </v-card-text>
          </v-card>

          <!-- Patrol Activity -->
          <v-card
            v-if="patrolActivity.length"
            variant="flat"
            rounded="lg"
          >
            <v-card-title>Patrol Activity</v-card-title>
            <v-card-text class="pa-0">
              <v-table class="border-thin">
                <thead>
                  <tr>
                    <th>Checkpoints</th>
                    <th>Start - End Time</th>
                    <th>
                      Travel time<br />
                      <span class="text-caption text-medium-emphasis">Actual/Expected</span>
                    </th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  <tr 
                    v-for="activity in patrolActivity" 
                    :key="activity.id"
                    :class="{ 'cursor-pointer': activity.status === 'Skipped' }"
                    @click="activity.status === 'Skipped' && openRemarksDialog(activity)"
                  >
                    <td>{{ activity.checkpoint }}</td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ activity.startTime }}
                      <v-icon size="small" class="mx-2">mdi-arrow-right</v-icon>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ activity.endTime }}
                    </td>
                    <td>
                      <v-icon size="small" class="mr-1">mdi-clock-outline</v-icon>
                      {{ activity.actualTime }} / {{ activity.expectedTime }}
                    </td>
                    <td>
                      <v-chip
                        :color="getStatusColor(activity.status)"
                        size="small"
                        variant="flat"
                      >
                        {{ activity.status }}
                        <v-icon
                          v-if="activity.status === 'Skipped'"
                          size="small"
                          class="ml-1"
                        >
                          mdi-flag
                        </v-icon>
                      </v-chip>
                    </td>
                  </tr>
                </tbody>
              </v-table>
            </v-card-text>
          </v-card>

          <!-- Empty State -->
          <v-card
            v-if="!routeSummary && !loading"
            class="text-center pa-12"
            variant="outlined"
            rounded="lg"
          >
            <v-icon size="64" color="grey-lighten-1" class="mb-4">
              mdi-clipboard-text-outline
            </v-icon>
            <h3 class="text-h6 mb-2">No Patrol Report Selected</h3>
            <p class="text-body-2 text-medium-emphasis">
              Please select a route, time range, and date to view the patrol
              report
            </p>
          </v-card>
        </v-window-item>

        <!-- Daily Report Tab -->
        <v-window-item value="daily">
          <v-card class="text-center pa-12" variant="outlined" rounded="lg">
            <v-icon size="64" color="grey-lighten-1" class="mb-4">
              mdi-calendar-today
            </v-icon>
            <h3 class="text-h6 mb-2">Daily Report</h3>
            <p class="text-body-2 text-medium-emphasis">Coming soon...</p>
          </v-card>
        </v-window-item>

        <!-- Monthly Report Tab -->
        <v-window-item value="monthly">
          <v-card class="text-center pa-12" variant="outlined" rounded="lg">
            <v-icon size="64" color="grey-lighten-1" class="mb-4">
              mdi-calendar-month
            </v-icon>
            <h3 class="text-h6 mb-2">Monthly Report</h3>
            <p class="text-body-2 text-medium-emphasis">Coming soon...</p>
          </v-card>
        </v-window-item>
      </v-window>
    </v-col>

    <!-- Skip Checkpoint Remarks Dialog -->
    <v-dialog v-model="dialogRemarks" max-width="600" persistent>
      <v-card rounded="xl">
        <v-card-title class="d-flex align-center pa-6">
          <span class="text-h6">Skip Checkpoint Remarks</span>
          <v-spacer />
          <v-btn
            icon="mdi-close"
            variant="text"
            size="small"
            @click="dialogRemarks = false"
          />
        </v-card-title>

        <v-card-text class="px-6 pb-6">
          <v-textarea
            :model-value="selectedActivityRemarks"
            variant="outlined"
            rounded="lg"
            readonly
            rows="4"
            hide-details
          />
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- Select Routes & Schedule Dialog -->
    <v-dialog v-model="dialogSelectRoute" max-width="680" persistent>
      <v-card rounded="xl">
        <v-card-title class="pa-6">
          <v-btn
            icon="mdi-chevron-left"
            variant="text"
            size="small"
            @click="dialogSelectRoute = false"
          />
          <span class="text-h6 ml-2">Select Routes & Schedule</span>
        </v-card-title>

        <v-card-text class="px-6 pb-6">
          <!-- Route Selector -->
          <v-select
            v-model="dialogRoute"
            :items="routes"
            variant="outlined"
            rounded="lg"
            density="comfortable"
            hide-details
            class="mb-4"
          />

          <!-- Date and Time Row -->
          <v-row no-gutters>
            <v-col cols="12" md="6" class="pr-md-2">
              <v-text-field
                v-model="dialogDate"
                type="date"
                variant="outlined"
                rounded="lg"
                density="comfortable"
                hide-details
                prepend-inner-icon="mdi-calendar"
              />
            </v-col>
            <v-col cols="12" md="6" class="pl-md-2 mt-2 mt-md-0">
              <v-select
                v-model="dialogTime"
                :items="timeRanges"
                variant="outlined"
                rounded="lg"
                density="comfortable"
                hide-details
                prepend-inner-icon="mdi-clock-outline"
              />
            </v-col>
          </v-row>
        </v-card-text>

        <!-- Action Buttons -->
        <v-card-actions class="px-6 pb-6">
          <v-row no-gutters>
            <v-col cols="6" class="pr-2">
              <v-btn
                block
                size="x-large"
                variant="outlined"
                rounded="lg"
                class="text-none"
                @click="dialogSelectRoute = false"
              >
                Cancel
              </v-btn>
            </v-col>
            <v-col cols="6" class="pl-2">
              <v-btn
                block
                size="x-large"
                color="primary"
                rounded="lg"
                class="text-none"
                @click="submitSelection"
              >
                Submit
              </v-btn>
            </v-col>
          </v-row>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

<script setup lang="ts">
interface PatrolActivity {
  id: string;
  checkpoint: string;
  startTime: string;
  endTime: string;
  actualTime: string;
  expectedTime: string;
  status: "Completed" | "Skipped";
  remarks?: string;
}

interface RouteSummary {
  routeName: string;
  tolerance: number;
  schedule: {
    start: string;
    end: string;
    totalTime: string;
  };
  actual: {
    start: string;
    end: string;
    totalTime: string;
  };
}

interface LocationData {
  name: string;
  address: string;
}

const props = defineProps<{
  site: string;
  orgId: string;
}>();

const router = useRouter();

// State
const activeTab = ref("patrol");
const selectedRoute = ref("WH01 Patrol Route");
const selectedTimeRange = ref("15:00 - 17:00");
const selectedDate = ref("2025-11-27");
const loading = ref(false);

// Dialog state
const dialogSelectRoute = ref(false);
const dialogRoute = ref("WH01 Patrol Route");
const dialogDate = ref("2025-11-27");
const dialogTime = ref("15:00 - 17:00");

// Remarks dialog state
const dialogRemarks = ref(false);
const selectedActivityRemarks = ref("");

// Mock data - replace with actual API calls
const routes = ref([
  "WH01 Patrol Route",
  "WH02 Patrol Route",
  "WH03 Patrol Route",
]);

const timeRanges = ref([
  "15:00 - 17:00",
  "08:00 - 10:00",
  "13:00 - 15:00",
  "18:00 - 20:00",
]);

const locationData = ref<LocationData>({
  name: "Winsland Homes",
  address: "221A Upper Thomson Road THOMSON RIDGE ESTATE",
});

const routeSummary = ref<RouteSummary>({
  routeName: "WH01 Patrol Route",
  tolerance: 30,
  schedule: {
    start: "14:00",
    end: "15:00",
    totalTime: "25 mins",
  },
  actual: {
    start: "14:01",
    end: "14:16",
    totalTime: "15 mins",
  },
});

const patrolActivity = ref<PatrolActivity[]>([
  {
    id: "1",
    checkpoint: "Point 1 WH01",
    startTime: "14:01",
    endTime: "14:04",
    actualTime: "3:00 mins",
    expectedTime: "5:00 mins",
    status: "Skipped",
    remarks: "Raining",
  },
  {
    id: "2",
    checkpoint: "Point 2 WH02",
    startTime: "14:04",
    endTime: "14:07",
    actualTime: "3:00 mins",
    expectedTime: "5:00 mins",
    status: "Completed",
  },
  {
    id: "3",
    checkpoint: "Point 3 WH03",
    startTime: "14:07",
    endTime: "15:10",
    actualTime: "3:00 mins",
    expectedTime: "5:00 mins",
    status: "Completed",
  },
  {
    id: "4",
    checkpoint: "Point 4 WH04",
    startTime: "14:10",
    endTime: "14:13",
    actualTime: "3:00 mins",
    expectedTime: "5:00 mins",
    status: "Completed",
  },
  {
    id: "5",
    checkpoint: "Point 5 WH05",
    startTime: "14:13",
    endTime: "14:16",
    actualTime: "3:00 mins",
    expectedTime: "5:00 mins",
    status: "Completed",
  },
]);

// Methods
const goBack = () => {
  router.back();
};

const loadReport = () => {
  // Open the dialog
  dialogRoute.value = selectedRoute.value;
  dialogDate.value = selectedDate.value;
  dialogTime.value = selectedTimeRange.value;
  dialogSelectRoute.value = true;
};

const submitSelection = () => {
  // Update the main filters with dialog values
  selectedRoute.value = dialogRoute.value;
  selectedDate.value = dialogDate.value;
  selectedTimeRange.value = dialogTime.value;
  
  // Close the dialog
  dialogSelectRoute.value = false;
  
  // TODO: Implement report loading based on filters
  console.log("Loading report...", {
    route: selectedRoute.value,
    timeRange: selectedTimeRange.value,
    date: selectedDate.value,
  });
};

const exportReport = () => {
  // TODO: Implement export functionality
  console.log("Exporting report...");
};

const getStatusColor = (status: string) => {
  return status === "Completed" ? "success" : "error";
};

const openRemarksDialog = (activity: PatrolActivity) => {
  selectedActivityRemarks.value = activity.remarks || "No remarks provided";
  dialogRemarks.value = true;
};

// TODO: Add API integration
// TODO: Add data fetching based on filters
// TODO: Implement Daily and Monthly reports
</script>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}

.cursor-pointer:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.v-table {
  border-radius: 0;
}
</style>
