import {Page,InlineGrid,Card,BlockStack,Select,Text, Button,SkeletonBodyText} from "@shopify/polaris";
import {useLoaderData} from "@remix-run/react";
import{ useEffect, useState } from "react";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";
import { json } from "@remix-run/node";

export const loader = async ({ request }) => {
  const {session} = await authenticate.admin(request);

  console.log(session);

  const user = await prisma.users.findFirst({
    where:{
      shopurl:session.shop
    }
  });
  console.log(user);

  return json({user});
};

export default function Setting() {
const {user} = useLoaderData();

const [loading, setLoading] = useState(true);
const [productSetting, setProductSetting] = useState('');
const [fulfillmentService, setFulfillmentService] = useState('');
const [inventoryPolicy, setInventoryPolicy] = useState("");

const [inSynchronization, setInSynchronization] = useState('');
const [prSynchronization, setPrSynchronization] = useState('');
const [autoImport, setAutoImport] = useState('');

  const productSettingOptions = [
    { label: 'Draft', value: 'Draft' },
    { label: 'Active', value: 'Active' },
  ];
  const fulfillmentServiceOptions = [
    { label: 'Manual', value: 'Manual' },
    { label: 'Amazon Marketplace Web', value: 'Amazon Marketplace Web' },
  ];
  const inventoryPolicyOptions = [
    { label: "Don't track inventory", value: "Don't track inventory" },
    { label: "Shopify tracks this product's inventory" ,value: "Shopify tracks this product's inventory" },
  ];

  const inSynchronizationOptions = [
    { label: 'Enable', value: 'Enable' },
    { label: 'Disable', value: 'Disable' },
  ];
  const prSynchronizationOptions = [
    { label: 'Enable', value: 'Enable' },
    { label: 'Disable', value: 'Disable' },
  ];
  const autoImportOptions = [
    { label: 'Enable', value: 'Enable' },
    { label: 'Disable', value: 'Disable' },
  ];

    useEffect(() => {
  if (user?.id) {
    const fetchSettings = async () => {
      try {
        const response = await fetch("/api/settings", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ userId: user.id }),
        });

        const result = await response.json();
        if (result.data) {
          const s = result.data;
          console.log("settings table data : ", s);

          setProductSetting(s.published === true ? "Active" : "Draft" || 'Active');
          setFulfillmentService(s.fulfilment_service || 'Manual');
          setInventoryPolicy(s.inventory_policy || "Don't track inventory");
          setInSynchronization(s.inventory_sync || "Disable");
          setPrSynchronization(s.price_sync || "Disable");
          setAutoImport(s.autoimport || "Disable");
        }

      } catch (err) {
        console.error("Failed to fetch settings:", err);
      }finally {
        setLoading(false);
      }
    };

    fetchSettings();
  }
}, [user]);

  const handleSubmit = async () => {
    const payload = {
        productSetting ,
        fulfillmentService,
        inventoryPolicy,
        inSynchronization,
        prSynchronization,
        autoImport,
    };

    console.log("Submitting payload:", payload);
    try {
      const response = await fetch("/api/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ data: payload }),
      });
       
      const data = await response.json();
      console.log("Data is : ",data);

      if (data.success) {
        shopify.toast.show("Submitted");
      } else {
        shopify.toast.show("Error while saving");
      }
    } catch (error) {
      console.error(error);
      shopify.toast.show("Server error");
    }
  };


return(
  <>
    <Page 
     title="Settings"
     subtitle="Configure your import and sync preferences">
      
      <div style={{padding:"20px"}}>
        <InlineGrid  columns={{ xs: 1, sm: 1, md: 2 }} gap="500">
        {loading ? (
                  <Card roundedAbove="sm">
                    <SkeletonBodyText lines={15} />
                  </Card>
                ) : (       
            <Card roundedAbove="sm">
                <BlockStack gap="200">
                 <Text variant="headingMd">Product Import Settings</Text>

                 <Select
                   label="Products should be published?"
                   onChange={setProductSetting}
                   value={productSetting}
                   options={productSettingOptions}
                 />
                 <Select
                   label="Fulfillment service"
                   onChange={setFulfillmentService}
                   value={fulfillmentService}
                   options={fulfillmentServiceOptions}
                 />
                 <Select
                   label="Inventory policy"
                   onChange={setInventoryPolicy}
                   value={inventoryPolicy}
                   options={inventoryPolicyOptions}
                 />
                </BlockStack>
            </Card>
                )}

            {loading ? (
                  <Card roundedAbove="sm">
                    <SkeletonBodyText lines={15} />
                  </Card>
                ) : (
             <Card roundedAbove="sm">
                <BlockStack gap="200">
                <Text variant="headingMd">Sync Settings</Text>

                <Select
                   label="Inventory Synchronization"
                   onChange={setInSynchronization}
                   value={inSynchronization}
                   options={inSynchronizationOptions}
                   helpText="Sync inventory levels between Amazon and Shopify"
                 />
                 <Select
                   label="Price Synchronization"
                   onChange={setPrSynchronization}
                   value={prSynchronization}
                   options={prSynchronizationOptions}
                   helpText="Sync prices between Amazon and Shopify"
                 />
                 <Select
                   label="Auto Import"
                   onChange={setAutoImport}
                   value={autoImport}
                   options={autoImportOptions}
                   helpText="Automatically import new products"
                 />
                </BlockStack>
            </Card>
                )}
        </InlineGrid>

         <div style={{ marginTop:"20px"}}>
         <Button fullWidth variant="primary" onClick={handleSubmit}>Save Settings</Button>
        </div>
       </div>

        <p style={{ textAlign:"center", marginTop: "30px",color:"#666"}}>
          Copyright 2022 InfoShore Technology Solutions LLP. All rights reserved.
        </p>
    </Page>
    <style>
        {`
          {/* .settings-grid {
            grid-template-columns: repeat(2, 1fr);
          }

          @media (max-width: 768px) 
            .settings-grid {
              grid-template-columns: repeat(1, 1fr) !important;
              backgroundColor:"blue";
            }
          } */}
       `}
      </style>
  </>
);
}