"use client";

import { FC, useState } from "react";
import { Grid, Box } from "@mui/material";
import { useRouter } from "next/navigation";
import {
  DisplayTextField,
  Button,
  Dialog,
  colors,
  typography,
} from "@link-stack/ui";
import { Selectable } from "kysely";
import { type Database } from "@link-stack/bridge-common";
import { QRCode } from "./QRCode";
import { generateDeleteAction } from "../lib/actions";
import { serviceConfig } from "../config/config";
import { FieldDescription } from "../lib/service";
import { getBasePath } from "../lib/frontendUtils";

type DetailProps = {
  service: string;
  row: Selectable<keyof Database>;
};

export const Detail: FC<DetailProps> = ({ service, row }) => {
  const {
    [service]: { entity, table, displayName, displayFields: fields },
  } = serviceConfig;
  const id = row.id as string;
  const token = row.token as string;
  const deleteAction = generateDeleteAction({ entity, table });
  const router = useRouter();
  const { almostBlack } = colors;
  const { bodyLarge } = typography;
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);
  const [showRelinkConfirmation, setShowRelinkConfirmation] = useState(false);
  const [isRelinking, setIsRelinking] = useState(false);

  const continueDeleteAction = async () => {
    await deleteAction?.(id);
    setShowDeleteConfirmation(false);
    router.push(`${getBasePath()}${entity}`);
  };

  const continueRelinkAction = async () => {
    setIsRelinking(true);
    try {
      const response = await fetch(`/link/api/${entity}/bots/${token}/relink`, {
        method: "POST",
      });
      if (response.ok) {
        setShowRelinkConfirmation(false);
        router.refresh();
      }
    } catch (error) {
      console.error("Relink failed:", error);
    } finally {
      setIsRelinking(false);
    }
  };

  return (
    <>
      <Dialog
        open
        title={`${displayName} Detail`}
        onClose={() => router.push(`${getBasePath()}${entity}`)}
        buttons={
          <Grid container justifyContent="space-between">
            <Grid item container xs="auto" spacing={2}>
              <Grid item>
                <Button
                  text="Delete"
                  kind="destructive"
                  onClick={() => setShowDeleteConfirmation(true)}
                />
              </Grid>
              {service === "whatsapp" && (
                <Grid item>
                  <Button
                    text="Relink"
                    kind="secondary"
                    onClick={() => setShowRelinkConfirmation(true)}
                  />
                </Grid>
              )}
              <Grid item>
                <Button
                  text="Edit"
                  kind="secondary"
                  href={`${getBasePath()}${entity}/${id}/edit`}
                />
              </Grid>
            </Grid>
            <Grid item>
              <Button
                text="Done"
                kind="primary"
                href={`${getBasePath()}${entity}`}
              />
            </Grid>
          </Grid>
        }
      >
        <Grid container direction="row" rowSpacing={3} columnSpacing={2}>
          {fields.map((field: FieldDescription) => (
            <Grid item xs={field.size ?? 6} key={field.name}>
              {field.kind === "qrcode" && (
                <QRCode
                  name={field.name}
                  label={field.label}
                  getValue={field.getQRCode}
                  refreshInterval={field.refreshInterval}
                  token={token}
                  verified={row.verified as boolean}
                  helperText={field.helperText}
                />
              )}
              {(!field.kind || field.kind === "text") && (
                <DisplayTextField
                  name={field.name}
                  label={field.label}
                  lines={field.lines ?? 1}
                  value={row[field.name] as string}
                  copyable={field.copyable ?? false}
                />
              )}
            </Grid>
          ))}
        </Grid>
      </Dialog>
      <Dialog
        open={showDeleteConfirmation}
        size="xs"
        title="Really delete?"
        buttons={
          <Grid container justifyContent="space-between">
            <Grid item>
              <Button
                text="Cancel"
                kind="secondary"
                onClick={() => setShowDeleteConfirmation(false)}
              />
            </Grid>
            <Grid item>
              <Button
                text="Delete"
                kind="destructive"
                onClick={continueDeleteAction}
              />
            </Grid>
          </Grid>
        }
      >
        <Box sx={{ ...bodyLarge, color: almostBlack }}>
          Are you sure you want to delete this record?
        </Box>
      </Dialog>
      <Dialog
        open={showRelinkConfirmation}
        size="xs"
        title="Relink WhatsApp Connection?"
        buttons={
          <Grid container justifyContent="space-between">
            <Grid item>
              <Button
                text="Cancel"
                kind="secondary"
                onClick={() => setShowRelinkConfirmation(false)}
                disabled={isRelinking}
              />
            </Grid>
            <Grid item>
              <Button
                text={isRelinking ? "Relinking..." : "Relink"}
                kind="primary"
                onClick={continueRelinkAction}
                disabled={isRelinking}
              />
            </Grid>
          </Grid>
        }
      >
        <Box sx={{ ...bodyLarge, color: almostBlack }}>
          This will disconnect the current WhatsApp link and generate a new QR code. You will need to scan the new QR code to reconnect. Continue?
        </Box>
      </Dialog>
    </>
  );
};
