<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-3">
      <v-row no-gutters align="center" justify="space-between">
        <div class="d-flex flex-wrap align-center">
          <v-btn
            v-if="showAddButton && canAddServiceProvider"
            class="text-none mr-2"
            rounded="pill"
            variant="tonal"
            size="large"
            @click="(createDialog = true), setServiceProvider({ mode: 'add' })"
          >
            Add
          </v-btn>
          <v-btn
            v-if="canInviteServiceProvider"
            class="text-none mr-2"
            rounded="pill"
            variant="tonal"
            size="large"
            @click="
              (createInviteDialog = true),
                setServiceProvider({ mode: 'invite' })
            "
          >
            Invite
          </v-btn>
          <v-btn
            v-if="showBillingButton"
            class="text-none mr-2"
            rounded="pill"
            variant="tonal"
            size="large"
            @click="
              useRouter().push({
                name: 'org-site-service-provider-mgmt-billing',
              })
            "
          >
            Billing
          </v-btn>
        </div>

        <v-text-field
          v-model="searchText"
          placeholder="Search"
          variant="outlined"
          density="comfortable"
          clearable
          hide-details
          prepend-inner-icon="mdi-magnify"
          class="ml-2"
          style="max-width: 280px"
        />
      </v-row>
    </v-col>

    <v-col cols="12">
      <v-card
        width="100%"
        variant="outlined"
        border="thin"
        rounded="lg"
        :loading="loading"
      >
        <div class="sp-table-header">
          <v-toolbar
            density="compact"
            color="grey-lighten-4"
            flat
            class="sp-toolbar-top px-2"
          >
            <v-btn
              icon
              variant="text"
              density="comfortable"
              @click="loadList()"
            >
              <v-icon>mdi-refresh</v-icon>
            </v-btn>

            <v-spacer />

            <template v-if="canViewServiceProviders">
              <span class="mr-2 text-caption text-medium-emphasis">{{
                pageRange
              }}</span>
              <local-pagination
                v-model="page"
                :length="pages"
                @update:value="loadList()"
              />
            </template>
          </v-toolbar>

          <v-tabs
            v-model="listTab"
            color="primary"
            density="comfortable"
            class="sp-tabs"
            align-tabs="start"
          >
            <v-tab value="active" class="text-none">Service Providers</v-tab>
            <v-tab value="pending" class="text-none">Pending</v-tab>
            <v-tab value="inactive" class="text-none">In-Active</v-tab>
          </v-tabs>
        </div>

        <v-data-table
          v-if="canViewServiceProviders"
          :headers="headers"
          :items="items"
          item-value="_id"
          :items-per-page="pageSize"
          fixed-header
          hide-default-footer
          class="sp-table"
          style="max-height: calc(100vh - 280px)"
        >
          <template #item.companyName="{ item }">
            <span class="text-body-2 d-block text-truncate sp-col-company">{{
              item.companyName
            }}</span>
          </template>
          <template #item.email="{ item }">
            <span class="text-body-2 d-block text-truncate sp-col-email">{{
              item.email
            }}</span>
          </template>
          <template #item.type="{ item }">
            <span class="text-body-2 d-block text-truncate sp-col-type">{{
              item.type
            }}</span>
          </template>
          <template #item.members="{ item }">
            <span class="text-body-2">{{ item.members }}</span>
          </template>
          <template #item.status="{ item }">
            <v-chip
              :color="statusChipColor(item.status)"
              size="small"
              variant="tonal"
              class="text-none"
            >
              {{ item.status }}
            </v-chip>
          </template>
          <template #item.actions="{ item }">
            <v-menu v-if="item.source === 'provider'" location="bottom end">
              <template #activator="{ props: menuProps }">
                <v-btn
                  v-bind="menuProps"
                  icon
                  variant="text"
                  density="comfortable"
                  aria-label="Row actions"
                >
                  <v-icon>mdi-dots-vertical</v-icon>
                </v-btn>
              </template>
              <v-list density="compact" min-width="140">
                <v-list-item
                  v-if="canViewMembers(item)"
                  title="View Members"
                  @click="openView(item)"
                />
                <v-list-item
                  :title="rowActionLabel(item)"
                  :base-color="
                    item.source === 'provider' && listTab === 'inactive'
                      ? undefined
                      : 'error'
                  "
                  @click="onDeleteRow(item)"
                />
              </v-list>
            </v-menu>
          </template>
        </v-data-table>
        <v-card-text v-else class="text-body-2 text-medium-emphasis">
          You do not have permission to view service providers.
        </v-card-text>

      </v-card>
    </v-col>
  </v-row>

  <v-dialog v-model="viewDialog" max-width="514">
    <v-card rounded="lg" class="sp-members-card">
      <v-card-title class="sp-members-title">
        Members ({{ memberDialogCount }})
      </v-card-title>

      <v-divider />

      <v-table class="sp-members-table">
        <thead>
          <tr>
            <th>Name</th>
            <th class="text-right">Role</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loadingMembers">
            <td colspan="2" class="text-center text-medium-emphasis">
              Loading...
            </td>
          </tr>
          <tr v-else-if="!serviceProviderMembers.length">
            <td colspan="2" class="text-center text-medium-emphasis">
              No members found.
            </td>
          </tr>
          <template v-else>
            <tr v-for="member in serviceProviderMembers" :key="member._id">
              <td>{{ member.name }}</td>
              <td class="text-right">{{ member.role }}</td>
            </tr>
          </template>
        </tbody>
      </v-table>

      <v-divider />

      <v-card-actions class="pa-0">
        <v-btn
          block
          variant="text"
          height="56"
          class="text-none font-weight-bold"
          @click="viewDialog = false"
        >
          Close
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <v-dialog v-model="statusDialog" max-width="728" persistent>
    <v-card rounded="lg" class="sp-status-card">
      <v-card-title class="sp-status-title">
        {{ statusDialogTitle }}
      </v-card-title>

      <v-card-text class="sp-status-body">
        <div class="sp-status-question">
          {{ statusDialogQuestion }}
        </div>
        <div class="sp-status-copy">
          {{ statusDialogCopy }}
        </div>
      </v-card-text>

      <v-divider />

      <v-card-actions class="pa-0">
        <v-row no-gutters class="fill-height">
          <v-col cols="6">
            <v-btn
              block
              variant="flat"
              height="82"
              class="text-none sp-status-cancel"
              :disabled="statusUpdating"
              @click="closeStatusDialog"
            >
              Cancel
            </v-btn>
          </v-col>
          <v-col cols="6">
            <v-btn
              block
              variant="flat"
              height="82"
              class="text-none sp-status-confirm"
              :loading="statusUpdating"
              @click="confirmStatusChange"
            >
              {{ statusConfirmLabel }}
            </v-btn>
          </v-col>
        </v-row>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <v-dialog v-model="createDialog" width="500" persistent>
    <v-card width="100%">
      <v-toolbar>
        <v-row no-gutters class="fill-height px-6" align="center">
          <span class="font-weight-bold text-h5"> Add Service Provider </span>
        </v-row>
      </v-toolbar>
      <v-card-text style="max-height: 100vh; overflow-y: auto">
        <v-form
          v-model="validServiceProvider"
          :disabled="disableServiceProvider"
        >
          <v-row no-gutters class="px-4">
            <v-col cols="12" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Name" required />
                <v-col cols="12">
                  <v-text-field
                    v-model="serviceProvider.name"
                    density="comfortable"
                    :rules="[requiredRule]"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Type" required />
                <v-col cols="12">
                  <v-select
                    v-model="serviceProvider.type"
                    item-title="title"
                    item-value="value"
                    :items="natureOfBusiness"
                    density="comfortable"
                    :rules="[requiredRule]"
                  ></v-select>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Email" required />
                <v-col cols="12">
                  <v-text-field
                    v-model="serviceProvider.email"
                    density="comfortable"
                    :rules="[emailRule, requiredRule]"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Description" />
                <v-col cols="12">
                  <v-textarea
                    v-model="serviceProvider.description"
                    density="comfortable"
                    no-resize
                    rows="2"
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12">
              <v-checkbox
                v-model="createMoreServiceProvider"
                density="comfortable"
                hide-details
              >
                <template #label>
                  <span class="text-subtitle-2 font-weight-bold">
                    Create more
                  </span>
                </template>
              </v-checkbox>
            </v-col>

            <v-col cols="12" class="my-2">
              <v-row no-gutters>
                <v-col cols="12" class="text-center">
                  <span
                    class="text-none text-subtitle-2 font-weight-medium text-error"
                  >
                    {{ messageServiceProvider }}
                  </span>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>
      <v-toolbar>
        <v-row class="px-6">
          <v-col cols="6">
            <v-btn
              block
              variant="text"
              class="text-none"
              size="large"
              @click="setServiceProvider({ mode: 'add', dialog: false })"
            >
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6">
            <v-btn
              block
              variant="flat"
              color="black"
              class="text-none"
              size="large"
              :disabled="!validServiceProvider"
              :loading="disableServiceProvider"
              @click="submitServiceProviderAdd"
            >
              Submit
            </v-btn>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>

  <v-dialog v-model="createInviteDialog" width="680" persistent>
    <v-card width="100%" rounded="lg" class="sp-invite-card">
      <v-toolbar flat color="grey-lighten-4" height="76">
        <v-row no-gutters class="fill-height px-6" align="center">
          <span class="font-weight-bold text-h5">
            Invite Service Provider
          </span>
        </v-row>
      </v-toolbar>
      <v-card-text class="sp-invite-body">
        <v-form
          v-model="validServiceProvider"
          :disabled="disableServiceProvider"
        >
          <v-row no-gutters>
            <v-col cols="12">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Email" required />
                <v-col cols="12">
                  <v-text-field
                    v-model="serviceProviderInvite.email"
                    variant="outlined"
                    density="comfortable"
                    :rules="[requiredRule, emailRule]"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12">
              <v-divider class="mb-6" />
            </v-col>

            <v-col cols="12">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="App" required />
                <v-col cols="12">
                  <v-select
                    v-model="serviceProviderInvite.app"
                    :items="serviceProviderInviteApps"
                    item-title="title"
                    item-value="value"
                    variant="outlined"
                    density="comfortable"
                    :rules="[requiredRule]"
                    @update:model-value="loadInviteRoles"
                  ></v-select>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Site" required />
                <v-col cols="12">
                  <v-select
                    v-model="serviceProviderInvite.siteId"
                    :items="serviceProviderInviteSites"
                    item-title="title"
                    item-value="value"
                    variant="outlined"
                    density="comfortable"
                    :rules="[requiredRule]"
                    @update:model-value="setInviteSiteName"
                  ></v-select>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12">
              <v-row no-gutters>
                <InputLabel class="text-capitalize" title="Role" required />
                <v-col cols="12">
                  <v-select
                    v-model="serviceProviderInvite.role"
                    :items="serviceProviderInviteRoles"
                    item-title="name"
                    item-value="_id"
                    variant="outlined"
                    density="comfortable"
                    :loading="loadingInviteRoles"
                    :rules="[requiredRule]"
                  ></v-select>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" class="my-2">
              <v-row no-gutters>
                <v-col cols="12" class="text-center">
                  <span
                    class="text-none text-subtitle-2 font-weight-medium text-error"
                  >
                    {{ messageServiceProvider }}
                  </span>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-toolbar flat height="76" class="sp-invite-footer">
        <v-row no-gutters class="fill-height">
          <v-col cols="6" class="fill-height">
            <v-btn
              block
              variant="flat"
              class="text-none sp-invite-footer-btn"
              height="76"
              @click="setServiceProvider({ mode: 'invite', dialog: false })"
            >
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6" class="fill-height">
            <v-btn
              block
              variant="flat"
              class="text-none sp-invite-submit-btn"
              height="76"
              :disabled="!validServiceProvider"
              :loading="disableServiceProvider"
              @click="submitServiceProviderInvite()"
            >
              Submit
            </v-btn>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>

  <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
</template>

<script lang="ts" setup>
import useServiceProvider from "../composables/useServiceProvider";
import useVerification from "../composables/useVerification";
import useRole from "../composables/useRole";
import { errorConverter } from "../utils/data";

type ListTab = "active" | "pending" | "inactive";

type TableRow = {
  _id: string;
  serviceProviderOrgId: string;
  companyName: string;
  email: string;
  type: string;
  members: string;
  status: string;
  source: "provider" | "invite";
};

type ServiceProviderMemberRow = {
  _id: string;
  name: string;
  role: string;
};

const props = defineProps({
  orgId: {
    type: String,
    default: "",
  },
  customerId: {
    type: String,
    default: "",
  },
  siteId: {
    type: String,
    default: "",
  },
  siteName: {
    type: String,
    default: "",
  },
  serviceProviderOrgId: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    required: true,
    default: "app",
  },
  route: {
    type: String,
    default: "",
  },
  canAddServiceProvider: {
    type: Boolean,
    default: true,
  },
  canInviteServiceProvider: {
    type: Boolean,
    default: true,
  },
  canViewServiceProviders: {
    type: Boolean,
    default: true,
  },
  showAddButton: {
    type: Boolean,
    default: true,
  },
  showBillingButton: {
    type: Boolean,
    default: true,
  },
});

const headers = [
  {
    title: "Company name",
    value: "companyName",
    sortable: true,
    minWidth: "140px",
    maxWidth: "220px",
  },
  {
    title: "Email",
    value: "email",
    sortable: true,
    minWidth: "180px",
    maxWidth: "260px",
  },
  {
    title: "Type",
    value: "type",
    sortable: true,
    minWidth: "120px",
    maxWidth: "180px",
  },
  {
    title: "Members",
    value: "members",
    sortable: false,
    width: "88px",
    align: "start" as const,
  },
  {
    title: "Status",
    value: "status",
    sortable: true,
    width: "120px",
  },
  {
    title: "",
    value: "actions",
    sortable: false,
    align: "end" as const,
    width: "56px",
    minWidth: "56px",
  },
];

const { natureOfBusiness } = useLocal();
const { requiredRule, emailRule, debounce } = useUtils();

const listTab = ref<ListTab>("active");
const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");
const pageSize = 20;

const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");

const items = ref<TableRow[]>([]);
const loading = ref(false);

const validServiceProvider = ref(false);
const disableServiceProvider = ref(false);
const createMoreServiceProvider = ref(false);
const messageServiceProvider = ref("");
const serviceProvider = ref({
  name: "",
  type: "",
  email: "",
  description: "",
  orgId: "",
  siteId: "",
  siteName: "",
  orgName: "",
  category: "",
});
const defaultInviteApp = "property_management_agency";
const serviceProviderInvite = ref({
  email: "",
  app: defaultInviteApp,
  siteId: props.siteId,
  siteName: props.siteName,
  role: "",
});

const {
  getAll: getAllServiceProvider,
  add: addServiceProvider,
  createServiceProviderInvite,
  updateStatus: updateServiceProviderStatus,
} = useServiceProvider();
const { getAll: getAllMembers } = useMember();

const { getVerifications, cancelUserInvitation } = useVerification();
const { getRoles } = useRole();

const { getSiteById } = useSite();

const { data: site } = await useLazyAsyncData(
  "get-site-by-id-" + props.siteId,
  () => getSiteById(props.siteId)
);

const searchText = ref("");

const createDialog = ref(false);
const createInviteDialog = ref(false);
const loadingInviteRoles = ref(false);
const serviceProviderInviteRoles = ref<Array<Record<string, any>>>([]);

const serviceProviderInviteApps = computed(() =>
  natureOfBusiness.map((item) => ({
    ...item,
    title:
      item.value === "cleaning_services"
        ? "Cleaning"
        : item.title.replace(" Services", ""),
  }))
);

const serviceProviderInviteSites = computed(() => [
  {
    title: site.value?.name || props.siteName || props.siteId,
    value: props.siteId,
  },
]);

const viewDialog = ref(false);
const viewRow = ref<TableRow | null>(null);
const loadingMembers = ref(false);
const serviceProviderMembers = ref<ServiceProviderMemberRow[]>([]);
const memberDialogCount = computed(() =>
  loadingMembers.value
    ? viewRow.value?.members ?? 0
    : serviceProviderMembers.value.length
);

function canViewMembers(row: TableRow) {
  return row.source === "provider";
}

const statusDialog = ref(false);
const statusUpdating = ref(false);
const statusActionRow = ref<TableRow | null>(null);
const statusAction = ref<"delete" | "reactivate">("delete");
const statusDialogTitle = computed(() =>
  statusAction.value === "reactivate"
    ? "Reactivate Service Provider"
    : "Delete Service Provider"
);
const statusDialogQuestion = computed(() =>
  statusAction.value === "reactivate"
    ? "Are you sure you want to reactivate this service provider?"
    : "Are you sure you want to delete this service provider?"
);
const statusDialogCopy = computed(() =>
  statusAction.value === "reactivate"
    ? "This action will restore the record. The service provider will be moved to the Active tab."
    : "This action will not permanently remove the record. The service provider will be moved to the Inactive tab."
);
const statusConfirmLabel = computed(() =>
  statusAction.value === "reactivate" ? "Reactivate" : "Confirm"
);

function rowActionLabel(row: TableRow) {
  return row.source === "provider" && listTab.value === "inactive"
    ? "Reactivate"
    : "Delete";
}

function typeDisplay(type: string, nature?: string) {
  if (nature && String(nature).trim()) return String(nature);
  const list = natureOfBusiness.value as Array<{ title?: string; value?: string }>;
  const hit = list?.find((x) => x.value === type);
  return hit?.title ?? type ?? "-";
}

function statusDisplay(raw: string, source: TableRow["source"]) {
  if (source === "invite") return "Pending";
  const s = (raw || "").toLowerCase();
  if (s === "inactive") return "In-Active";
  if (!raw) return "-";
  return raw.charAt(0).toUpperCase() + raw.slice(1).toLowerCase();
}

function statusChipColor(statusLabel: string) {
  const s = statusLabel.toLowerCase();
  if (s === "active") return "success";
  if (s === "pending") return "warning";
  if (s === "in-active" || s === "inactive") return "default";
  return "primary";
}

async function loadInviteRoles() {
  loadingInviteRoles.value = true;
  serviceProviderInvite.value.role = "";
  try {
    const response = await getRoles({
      org: props.orgId,
      type: serviceProviderInvite.value.app,
      limit: 50,
    });
    serviceProviderInviteRoles.value = response?.items ?? [];
    serviceProviderInvite.value.role =
      serviceProviderInviteRoles.value[0]?._id ?? "";
  } catch (error: any) {
    serviceProviderInviteRoles.value = [];
    showMessage(errorConverter(error), "error");
  } finally {
    loadingInviteRoles.value = false;
  }
}

function setInviteSiteName(siteId: string) {
  const selectedSite = serviceProviderInviteSites.value.find(
    (item) => item.value === siteId
  );
  serviceProviderInvite.value.siteName = selectedSite?.title ?? "";
}

function formatMembersCell(value: unknown): string {
  if (value == null || value === "") return "0";
  const n = Number(value);
  if (!Number.isFinite(n)) return "0";
  return String(n);
}

function formatEmailCell(value: unknown): string {
  if (value == null) return "-";
  const s = String(value).trim();
  return s.length ? s : "-";
}

function mapProviderRows(raw: Record<string, any>[]): TableRow[] {
  return raw.map((row) => ({
    _id: String(row._id ?? ""),
    serviceProviderOrgId: String(row.serviceProviderOrgId ?? ""),
    companyName: row.name ?? "-",
    email: formatEmailCell(row.email),
    type: typeDisplay(row.type ?? "", row.nature),
    members: formatMembersCell(row.members),
    status: statusDisplay(row.status ?? "active", "provider"),
    source: "provider",
  }));
}

function inviteTypeLabel(t: string) {
  const key = (t || "").toLowerCase();
  const map: Record<string, string> = {
    "service-provider-invite": "Service provider invite",
    "service-provider-create-org": "Service provider (new org)",
  };
  return map[key] ?? (t ? t.replace(/-/g, " ") : "-");
}

function mapInviteRows(raw: Record<string, any>[]): TableRow[] {
  return raw.map((row) => ({
    _id: String(row._id ?? ""),
    serviceProviderOrgId: String(row.metadata?.serviceProviderOrgId ?? ""),
    companyName: row.metadata?.name || "-",
    email: formatEmailCell(row.email),
    type: row.metadata?.app
      ? typeDisplay(row.metadata.app)
      : inviteTypeLabel(row.type ?? ""),
    members: "-",
    status: "Pending",
    source: "invite",
  }));
}

async function loadList() {
  if (!props.siteId || !props.canViewServiceProviders) {
    items.value = [];
    pages.value = 0;
    pageRange.value = "-- - -- of --";
    return;
  }

  loading.value = true;
  try {
    if (listTab.value === "pending") {
      const data = await getVerifications({
        status: "pending",
        type: "service-provider-invite,service-provider-create-org",
        page: page.value,
        search: searchText.value?.trim() || "",
        siteId: props.siteId,
        orgId: props.orgId,
        limit: pageSize,
      });
      items.value = mapInviteRows(data.items ?? []);
      pages.value = data.pages ?? 0;
      pageRange.value = data.pageRange ?? "-- - -- of --";
      return;
    }

    const statusParam = listTab.value === "active" ? "active" : "inactive";
    const data = await getAllServiceProvider({
      page: page.value,
      siteId: props.siteId,
      search: searchText.value?.trim() || "",
      limit: pageSize,
      status: statusParam,
    });
    items.value = mapProviderRows(data.items ?? []);
    pages.value = data.pages ?? 0;
    pageRange.value = data.pageRange ?? "-- - -- of --";
  } catch (error: any) {
    showMessage(errorConverter(error), "error");
    items.value = [];
    pages.value = 0;
    pageRange.value = "-- - -- of --";
  } finally {
    loading.value = false;
  }
}

async function openView(row: TableRow) {
  viewRow.value = row;
  serviceProviderMembers.value = [];
  viewDialog.value = true;

  if (!row.serviceProviderOrgId) return;

  loadingMembers.value = true;
  try {
    const data = await getAllMembers({
      page: 1,
      limit: 1000,
      org: row.serviceProviderOrgId,
      status: "active",
    });
    serviceProviderMembers.value = (data.items ?? []).map((member: any) => ({
      _id: String(member._id ?? ""),
      name: member.name || member.fullName || member.email || "-",
      role: member.roleName || member.role?.name || "-",
    }));
  } catch (error: any) {
    showMessage(errorConverter(error), "error");
  } finally {
    loadingMembers.value = false;
  }
}

async function onDeleteRow(row: TableRow) {
  if (row.source === "invite") {
    const ok = confirm("Cancel this invitation?");
    if (!ok) return;
    try {
      await cancelUserInvitation(row._id);
      showMessage("Invitation cancelled.", "success");
      await loadList();
    } catch (error: any) {
      showMessage(errorConverter(error), "error");
    }
    return;
  }

  statusActionRow.value = row;
  statusAction.value = listTab.value === "inactive" ? "reactivate" : "delete";
  statusDialog.value = true;
}

function closeStatusDialog() {
  if (statusUpdating.value) return;
  statusDialog.value = false;
  statusActionRow.value = null;
}

async function confirmStatusChange() {
  if (!statusActionRow.value) return;

  statusUpdating.value = true;
  const nextStatus = statusAction.value === "reactivate" ? "active" : "inactive";
  try {
    await updateServiceProviderStatus(statusActionRow.value._id, nextStatus);
    showMessage(
      statusAction.value === "reactivate"
        ? "Service provider reactivated."
        : "Service provider moved to In-Active.",
      "success"
    );
    statusDialog.value = false;
    statusActionRow.value = null;
    listTab.value = nextStatus === "active" ? "active" : "inactive";
    page.value = 1;
    await loadList();
  } catch (error: any) {
    showMessage(errorConverter(error), "error");
  } finally {
    statusUpdating.value = false;
  }
}

watch(listTab, () => {
  page.value = 1;
  loadList();
});

watch(page, () => {
  loadList();
});

const debouncedSearch = debounce(() => {
  page.value = 1;
  loadList();
}, 500);

watch(
  () => searchText.value,
  () => {
    debouncedSearch();
  }
);

onMounted(() => {
  loadList();
});

function showMessage(msg: string, color: string) {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

function setServiceProvider({
  mode = "invite",
  dialog = true,
  data = {} as Record<string, any>,
} = {}) {
  if (mode === "invite") {
    createInviteDialog.value = dialog;
  }

  if (mode === "add") {
    createDialog.value = dialog;
  }

  if (dialog) {
    serviceProvider.value = {
      name: "",
      type: "",
      email: "",
      description: "",
      orgId: props.orgId,
      siteId: props.siteId,
      siteName: site.value?.name ?? "",
      orgName: "Org Name",
      category: mode === "add" ? "internal" : "external",
    };

    if (mode === "invite") {
      serviceProviderInvite.value = {
        email: "",
        app: defaultInviteApp,
        siteId: props.siteId,
        siteName: site.value?.name || props.siteName,
        role: "",
      };
      createMoreServiceProvider.value = false;
      void loadInviteRoles();
    }
    return;
  }

  serviceProvider.value.description = data.description ?? "";
  serviceProvider.value.email = data.email ?? "";
  serviceProvider.value.name = data.name ?? "";
  serviceProvider.value.type = data.type ?? "";
}

async function submitServiceProviderAdd() {
  disableServiceProvider.value = true;
  messageServiceProvider.value = "";

  try {
    const result = await addServiceProvider(serviceProvider.value);
    await setServiceProvider({ mode: "add", dialog: false });
    await loadList();

    if (result?.id) {
      showMessage(result?.message, "success");
    }
  } catch (error: any) {
    messageServiceProvider.value =
      error?.response?._data?.message ??
      "An error occurred while adding the service provider.";
    showMessage(errorConverter(error), "error");
  } finally {
    disableServiceProvider.value = false;
  }
}

async function submitServiceProviderInvite() {
  disableServiceProvider.value = true;
  messageServiceProvider.value = "";
  try {
    const payload = {
      email: serviceProviderInvite.value.email.trim(),
      name: "",
      app: serviceProviderInvite.value.app,
      role: serviceProviderInvite.value.role,
      orgId: props.orgId,
      siteId: serviceProviderInvite.value.siteId,
      siteName:
        serviceProviderInvite.value.siteName || site.value?.name || props.siteName,
    };

    await createServiceProviderInvite(payload);
    showMessage("Invitation sent.", "success");
    if (createMoreServiceProvider.value) {
      serviceProviderInvite.value.email = "";
    } else {
      await setServiceProvider({ mode: "invite", dialog: false });
    }
    await loadList();
  } catch (error: any) {
    messageServiceProvider.value =
      error?.response?._data?.message ??
      "An error occurred while inviting the service provider.";
    showMessage(errorConverter(error), "error");
  } finally {
    disableServiceProvider.value = false;
  }
}
</script>

<style scoped>
.sp-toolbar-top {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 4px;
}

.sp-table-header {
  background: #f5f5f5;
  border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}

.sp-tabs {
  width: 100%;
  min-height: 40px;
}

.sp-tabs :deep(.v-tab) {
  min-width: 120px;
  justify-content: flex-start;
  text-transform: none;
}

.sp-col-company {
  max-width: 220px;
}

.sp-col-email {
  max-width: 260px;
}

.sp-col-type {
  max-width: 180px;
}

.sp-table :deep(thead th) {
  font-weight: 600;
  font-size: 0.8125rem;
  color: rgba(0, 0, 0, 0.7);
}

.sp-table :deep(tbody td) {
  vertical-align: middle;
}

.sp-invite-card {
  overflow: hidden;
}

.sp-invite-body {
  max-height: 100vh;
  overflow-y: auto;
  padding: 48px 44px 34px;
}

.sp-invite-body :deep(.v-field) {
  border-radius: 6px;
}

.sp-invite-body :deep(.v-field__input) {
  min-height: 64px;
  font-size: 1.25rem;
}

.sp-invite-footer {
  border-top: 1px solid rgba(0, 0, 0, 0.12);
}

.sp-invite-footer-btn {
  border-radius: 0;
  background: #ffffff !important;
  color: #111827 !important;
  font-size: 1.25rem;
  font-weight: 700;
}

.sp-invite-submit-btn {
  border-radius: 0;
  background: #0b253b !important;
  color: #ffffff !important;
  font-size: 1.25rem;
  font-weight: 700;
}

.sp-members-card {
  overflow: hidden;
}

.sp-members-title {
  min-height: 56px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  font-size: 1.25rem;
  font-weight: 700;
}

.sp-members-table {
  max-height: 444px;
  overflow-y: auto;
}

.sp-members-table :deep(th) {
  height: 64px;
  color: #667085;
  font-size: 1rem;
  font-weight: 500;
}

.sp-members-table :deep(td) {
  height: 64px;
  color: #667085;
  font-size: 1rem;
}

.sp-status-card {
  overflow: hidden;
}

.sp-status-title {
  min-height: 82px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  background: #f5f5f5;
  color: #101828;
  font-size: 1.75rem;
  font-weight: 700;
}

.sp-status-body {
  padding: 44px 46px 42px;
}

.sp-status-question {
  color: #101828;
  font-size: 1.5rem;
  font-weight: 700;
  line-height: 1.35;
}

.sp-status-copy {
  margin-top: 28px;
  color: #667085;
  font-size: 1.5rem;
  line-height: 1.2;
}

.sp-status-cancel {
  color: #101828;
  background: #ffffff;
  font-size: 1.5rem;
  font-weight: 700;
}

.sp-status-confirm {
  color: #ffffff;
  background: #00263a;
  font-size: 1.5rem;
  font-weight: 700;
}
</style>
