"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 "ui";
import { Selectable } from "kysely";
import { type Database } from "bridge-common";
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 deleteAction = generateDeleteAction({ entity, table });
  const router = useRouter();
  const { almostBlack } = colors;
  const { bodyLarge } = typography;
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);

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

  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>
              <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}>
              <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>
    </>
  );
};
