import { format } from "date-fns";
import { Button } from "./Button";
import { DataStructure, SchemaOptions } from "./DataStructure";

export interface Props{
  modelSchema: DataStructure[];
  values: any;
  assetEndpointURL: string;
}

export const DataDetail = (props: Props) => {
  return (
    <div>
      {props.modelSchema.map((eachSchema, index) => {
        if(eachSchema.hideFromView){
          return <></>
        }

        let fieldId = eachSchema.fieldId;

        if(eachSchema.type === "reference"){
          fieldId = `${eachSchema.referenceAlias ?? eachSchema.referenceId}_${eachSchema.referenceDisplay}`
        }

        let value = props.values[fieldId];

        if(value && eachSchema.options){
          const filteredOption = eachSchema.options.filter((eachOption) => eachOption.value === value.toString());
          if(filteredOption.length > 0){
            value = filteredOption[0].label;
          }
        }

        if(((eachSchema.type === "reference" && eachSchema.referenceDisplayIsDate) || eachSchema.type === "date") && value){
          const date = new Date(value);

          value = format(date, 'yyyy-MM-dd');
        }

        if(((eachSchema.type === "reference" && eachSchema.referenceDisplayIsTime) || eachSchema.type === "datetime-local") && value){
          const date = new Date(value);

          value = format(date, 'yyyy-MM-dd HH:mm:ss');
        }

        if(typeof value === "object" && value ) {
          if(Array.isArray(value)){
            value = value.map((eachValue: SchemaOptions) => eachValue.label);
            value = value.join(", ");
          }else{
            value = undefined;
          }
        }
        return value != undefined ? (
          <div className="border-b py-5 px-2 grid sm:grid-cols-4 grid-cols-2 gap-5 text-sm" key={index}>
            <div className="font-bold">
              {eachSchema.displayName}
            </div>
            <div className="col-span-3">
              {eachSchema.type === "file" ? (
                <>
                  {value && <Button
                    text={`Preview ${typeof value !== "string" ? value.name : value}`}
                    additionalClassName="!p-0 text-left"
                    bgColor="bg-transparent"
                    color="text-primary-400 hover:text-neutral-400"
                    size="sm"
                    onClick={() => {
                      window.open(typeof value !== "string" ? URL.createObjectURL(value) : `${props.assetEndpointURL}/${value}`)
                    }}
                  />}
                </>
              ) : (
                <>{value}</>
              )}
            </div>
          </div>
        ) : <></>
      })}
    </div>
  )
}