<script setup>
import AppPhoneLayout from "@/Layouts/AppPhoneLayout.vue";
import { Badge } from "@/Components/ui/badge";
import { Button } from "@/Components/ui/button";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/Components/ui/card";
import { Input } from "@/Components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Separator } from "@/Components/ui/separator";
import { Skeleton } from "@/Components/ui/skeleton";
import { router } from "@inertiajs/vue3";
import { computed, ref, watch } from "vue";
import { useDebounceFn } from "@vueuse/core";
import {
  CalendarDays,
  FileText,
  FilterIcon,
  MapPin,
  Phone,
  Wallet,
} from "lucide-vue-next";
import { fmtDateDMY } from "@/Utilities/functions";

const props = defineProps({
  jobs: { type: Object, required: true },
  clients: { type: Array, default: () => [] },
  view_mode: { type: String, default: "assigned" },
  filters: { type: Object, default: () => ({ search: "", client: "" }) },
});

const search = ref(props.filters.search || "");
const clientFilter = ref(props.filters.client || "");
const isLoading = ref(false);

const listNonActivity = computed(() =>
  (props.jobs.data || []).filter((item) => !item.added_activity)
);

const listActivity = computed(() =>
  (props.jobs.data || []).filter((item) => !!item.added_activity)
);

const debouncedSearch = useDebounceFn((value) => {
  performSearch();
}, 500);

watch(search, (newValue) => {
  debouncedSearch(newValue);
});

watch(clientFilter, () => {
  performSearch();
});

function performSearch() {
  isLoading.value = true;

  router.get(
    route(props.view_mode === "completed-today" ? "phone.completed" : "phone.index"),
    {
      search: search.value || undefined,
      client: clientFilter.value || undefined,
    },
    {
      preserveState: true,
      preserveScroll: true,
      only: ["jobs", "filters"],
      onFinish: () => {
        isLoading.value = false;
      },
    }
  );
}

function clearSearch() {
  search.value = "";
  clientFilter.value = "";
}

function formatDateDMY(d) {
  if (!d) return "-";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return String(d);
  const parts = new Intl.DateTimeFormat("en-GB", {
    timeZone: "Europe/Ljubljana",
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).formatToParts(dt);
  const map = Object.fromEntries(parts.map((p) => [p.type, p.value]));
  return `${map.day}.${map.month}.${map.year}`;
}

function formatAmount(val) {
  if (val === null || val === undefined) return "0,00";
  const num = typeof val === "number" ? val : parseFloat(val);
  if (Number.isNaN(num)) return String(val);
  return num.toLocaleString("sl-SI", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

function getCaseUuid(job) {
  return (
    job?.contract?.client_case?.uuid || job?.client_case?.uuid || job?.case_uuid || null
  );
}

function changePage(url) {
  if (!url) return;
  isLoading.value = true;
  router.get(
    url,
    {},
    {
      preserveState: true,
      preserveScroll: false,
      only: ["jobs"],
      onFinish: () => {
        isLoading.value = false;
      },
    }
  );
}
</script>

<template>
  <AppPhoneLayout title="Phone">
    <template #header>
      <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
        {{
          props.view_mode === "completed-today" ? "Zaključeno danes" : "Terenska opravila"
        }}
      </h2>
    </template>

    <div class="py-6 sm:py-8">
      <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-4">
        <!-- Filters Section -->
        <Card>
          <CardHeader class="flex flex-row gap-1 items-center">
            <FilterIcon size="20" />
            <CardTitle class="text-xl">Filter</CardTitle>
          </CardHeader>
          <CardContent>
            <div class="flex flex-col sm:flex-row gap-4">
              <div class="flex-1">
                <Input
                  v-model="search"
                  type="text"
                  placeholder="Išči po referenci ali imenu..."
                  class="w-full"
                />
              </div>

              <Select v-model="clientFilter">
                <SelectTrigger class="w-full sm:w-64">
                  <SelectValue placeholder="Vsi naročniki" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem
                    v-for="client in props.clients"
                    :key="client.uuid"
                    :value="client.uuid"
                  >
                    {{ client.name }}
                  </SelectItem>
                </SelectContent>
              </Select>

              <Button
                v-if="search || clientFilter"
                variant="outline"
                @click="clearSearch"
              >
                Počisti
              </Button>
            </div>
          </CardContent>
        </Card>

        <!-- Loading Skeleton -->
        <div v-if="isLoading" class="space-y-6">
          <div class="space-y-3">
            <Skeleton class="h-8 w-48" />
            <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
              <Skeleton v-for="i in 6" :key="i" class="h-72" />
            </div>
          </div>
        </div>

        <!-- Content -->
        <div v-else-if="props.jobs.data && props.jobs.data.length" class="space-y-8">
          <!-- Non-Activity Jobs -->
          <section v-if="listNonActivity.length" class="space-y-4">
            <div class="flex items-center gap-3">
              <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                Nove / Ne obdelano
              </h2>
              <Badge variant="secondary" class="text-sm">
                {{ listNonActivity.length }}
              </Badge>
            </div>

            <div class="grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3">
              <Card
                v-for="job in listNonActivity"
                :key="job.id"
                class="flex flex-col hover:shadow-xl transition-all duration-200 border-l-2 border-l-blue-500"
              >
                <CardHeader>
                  <div class="flex items-start justify-between gap-2">
                    <div class="flex-1 min-w-0">
                      <h3
                        class="text-xl font-bold text-gray-900 dark:text-gray-100 truncate mb-1"
                      >
                        {{ job.contract?.client_case?.person?.full_name || "—" }}
                      </h3>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        <span class="font-semibold text-indigo-600 dark:text-indigo-400"
                          >Naročnik:</span
                        >
                        <span class="ml-1 font-medium text-gray-900 dark:text-gray-200">
                          {{
                            job.contract?.client_case?.client?.person?.full_name || "—"
                          }}
                        </span>
                      </p>
                    </div>
                    <Badge
                      v-if="job.priority"
                      variant="destructive"
                      class="shrink-0 animate-pulse"
                    >
                      Prioriteta
                    </Badge>
                  </div>
                </CardHeader>

                <CardContent class="flex-1 space-y-3 pt-4">
                  <div class="space-y-3 text-sm">
                    <div class="flex items-start gap-3">
                      <CalendarDays class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Dodeljeno
                        </p>
                        <p class="font-semibold text-gray-900 dark:text-gray-100">
                          {{ formatDateDMY(job.assigned_at) }}
                        </p>
                      </div>
                    </div>

                    <Separator />

                    <div class="flex items-start gap-3">
                      <FileText class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Pogodba
                        </p>
                        <p
                          class="font-mono text-xs text-gray-900 dark:text-gray-100 bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded inline-block"
                        >
                          {{ job.contract?.reference || job.contract?.uuid }}
                        </p>
                      </div>
                    </div>

                    <div class="flex items-start gap-3">
                      <MapPin class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Naslov
                        </p>
                        <p class="text-gray-900 dark:text-gray-100">
                          {{ job.contract?.client_case?.person?.address?.address || "—" }}
                        </p>
                      </div>
                    </div>

                    <div class="flex items-start gap-3">
                      <Phone class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Telefon
                        </p>
                        <p class="font-medium text-gray-900 dark:text-gray-100">
                          {{ job.contract?.client_case?.person?.phones?.[0]?.nu || "—" }}
                        </p>
                      </div>
                    </div>

                    <div
                      v-if="job.contract?.account?.balance_amount != null"
                      class="flex items-start gap-3 p-3 bg-red-50 dark:bg-red-950/20 rounded border border-red-200 dark:border-red-900 mt-4"
                    >
                      <Wallet
                        class="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5"
                      />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-red-600 dark:text-red-400 uppercase tracking-wide mb-0.5"
                        >
                          Odprto
                        </p>
                        <p class="font-bold text-red-700 dark:text-red-400 text-lg">
                          {{ formatAmount(job.contract.account.balance_amount) }} €
                        </p>
                      </div>
                    </div>
                  </div>
                </CardContent>

                <CardFooter class="pt-4 mt-auto">
                  <Button
                    v-if="getCaseUuid(job)"
                    as="a"
                    :href="
                      route('phone.case', {
                        client_case: getCaseUuid(job),
                        completed: props.view_mode === 'completed-today' ? 1 : undefined,
                      })
                    "
                    class="w-full font-semibold"
                    size="lg"
                  >
                    Odpri primer
                  </Button>
                  <Button v-else disabled class="w-full" variant="secondary" size="lg">
                    Manjka primer
                  </Button>
                </CardFooter>
              </Card>
            </div>
          </section>

          <!-- Activity Jobs -->
          <section v-if="listActivity.length" class="space-y-4">
            <div class="flex items-center gap-3">
              <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                Obdelane pogodbe
              </h2>
              <Badge variant="secondary" class="text-sm">
                {{ listActivity.length }}
              </Badge>
            </div>

            <div class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
              <Card
                v-for="job in listActivity"
                :key="job.id"
                class="flex flex-col hover:shadow-xl transition-all duration-200 border-l-2 border-l-green-500"
              >
                <CardHeader>
                  <div class="flex items-start justify-between gap-2">
                    <div class="flex-1 min-w-0">
                      <h3
                        class="text-xl font-bold text-gray-900 dark:text-gray-100 truncate mb-1"
                      >
                        {{ job.contract?.client_case?.person?.full_name || "—" }}
                      </h3>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        <span class="font-semibold text-indigo-600 dark:text-indigo-400"
                          >Naročnik:</span
                        >
                        <span class="ml-1 font-medium text-gray-900 dark:text-gray-200">
                          {{
                            job.contract?.client_case?.client?.person?.full_name || "—"
                          }}
                        </span>
                      </p>
                    </div>
                    <Badge
                      v-if="job.priority"
                      variant="destructive"
                      class="shrink-0 animate-pulse"
                    >
                      Prioriteta
                    </Badge>
                  </div>
                </CardHeader>

                <CardContent class="flex-1 space-y-3 pt-4">
                  <div class="space-y-3 text-sm">
                    <div class="flex items-start gap-3">
                      <CalendarDays class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Dodeljeno
                        </p>
                        <p class="font-semibold text-gray-900 dark:text-gray-100">
                          {{ fmtDateDMY(job.assigned_at) }}
                        </p>
                      </div>
                    </div>

                    <div
                      class="flex items-start gap-3 p-2 bg-green-50 dark:bg-green-900/20 rounded"
                    >
                      <CalendarDays
                        class="w-5 h-5 text-green-600 dark:text-green-400 shrink-0 mt-0.5"
                      />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-green-600 dark:text-green-400 uppercase tracking-wide mb-0.5"
                        >
                          Zadnja aktivnost
                        </p>
                        <p class="font-semibold text-green-700 dark:text-green-400">
                          {{ fmtDateDMY(job.last_activity) || "—" }}
                        </p>
                      </div>
                    </div>

                    <Separator />

                    <div class="flex items-start gap-3">
                      <FileText class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Kontrakt
                        </p>
                        <p
                          class="font-mono text-xs text-gray-900 dark:text-gray-100 bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded inline-block"
                        >
                          {{ job.contract?.reference || job.contract?.uuid }}
                        </p>
                      </div>
                    </div>

                    <div class="flex items-start gap-3">
                      <MapPin class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Naslov
                        </p>
                        <p class="text-gray-900 dark:text-gray-100">
                          {{ job.contract?.client_case?.person?.address?.address || "—" }}
                        </p>
                      </div>
                    </div>

                    <div class="flex items-start gap-3">
                      <Phone class="w-5 h-5 text-gray-400 shrink-0 mt-0.5" />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5"
                        >
                          Telefon
                        </p>
                        <p class="font-medium text-gray-900 dark:text-gray-100">
                          {{ job.contract?.client_case?.person?.phones?.[0]?.nu || "—" }}
                        </p>
                      </div>
                    </div>

                    <div
                      v-if="job.contract?.account?.balance_amount != null"
                      class="flex items-start gap-3 p-3 bg-red-50 dark:bg-red-950/20 rounded border border-red-200 dark:border-red-900 mt-4"
                    >
                      <Wallet
                        class="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5"
                      />
                      <div class="flex-1 min-w-0">
                        <p
                          class="text-xs text-red-600 dark:text-red-400 uppercase tracking-wide mb-0.5"
                        >
                          Odprto
                        </p>
                        <p class="font-bold text-red-700 dark:text-red-400 text-lg">
                          {{ formatAmount(job.contract.account.balance_amount) }} €
                        </p>
                      </div>
                    </div>
                  </div>
                </CardContent>

                <CardFooter class="pt-4 mt-auto">
                  <Button
                    v-if="getCaseUuid(job)"
                    as="a"
                    :href="
                      route('phone.case', {
                        client_case: getCaseUuid(job),
                        completed: props.view_mode === 'completed-today' ? 1 : undefined,
                      })
                    "
                    class="w-full font-semibold"
                    variant="secondary"
                    size="lg"
                  >
                    Odpri primer
                  </Button>
                  <Button v-else disabled class="w-full" variant="secondary" size="lg">
                    Manjka primer
                  </Button>
                </CardFooter>
              </Card>
            </div>
          </section>

          <!-- Pagination -->
          <Card v-if="props.jobs.links && props.jobs.links.length > 3">
            <CardContent class="pt-6">
              <div class="flex flex-wrap items-center justify-center gap-2">
                <Button
                  v-for="(link, index) in props.jobs.links"
                  :key="index"
                  :variant="link.active ? 'default' : 'outline'"
                  :disabled="!link.url"
                  @click="changePage(link.url)"
                  size="sm"
                  v-html="link.label"
                />
              </div>
            </CardContent>
          </Card>
        </div>

        <!-- Empty State -->
        <Card v-else>
          <CardContent class="py-12">
            <div class="text-center space-y-3">
              <div
                class="mx-auto w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center"
              >
                <svg
                  class="w-8 h-8 text-gray-400 dark:text-gray-600"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
                  />
                </svg>
              </div>
              <p class="text-lg font-medium text-gray-900 dark:text-gray-100">
                {{ search || clientFilter ? "Ni zadetkov" : "Ni opravil" }}
              </p>
              <p class="text-sm text-gray-600 dark:text-gray-400">
                {{
                  search || clientFilter
                    ? "Poskusite spremeniti iskalne kriterije"
                    : "Trenutno nimate dodeljenih terenskih opravil"
                }}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  </AppPhoneLayout>
</template>
