"use client";

import { EMAIL_HOST, IMAP_PORT, IMAP_SECURITY, SMTP_PORT, SMTP_SECURITY, WEBMAIL_URL } from "@/lib/constants";
import { Box, Button, Card, Flex, Heading, IconButton, Link, Tabs, Text, TextField } from "@radix-ui/themes";
import { CheckIcon, CopyIcon, ExternalLinkIcon } from "lucide-react";
import { useState } from "react";

function StaticValueField({ label, value }: { label: string, value: string }) {
  const [checked, setChecked] = useState(false);

  return (
    <>
      <Text weight="light" size="2">{label}</Text>
      <TextField.Root>
        <TextField.Input disabled value={value} />
        <TextField.Slot>
          <IconButton
            size="1"
            variant="ghost"
            onClick={() => {
              navigator.clipboard.writeText(value);
              setChecked(true);
              setTimeout(() => setChecked(false), 1000);
            }}
          >
            {checked
              ? <CheckIcon width={16} height={16} />
              : <CopyIcon width={16} height={16} />
            }
          </IconButton>
        </TextField.Slot>
      </TextField.Root>
    </>
  );
}

export default function ConnectionDetailsCard() {
  return (
    <Card className="h-fit">
      <Heading size="3">Server configuration</Heading>
      <Text weight="light" size="2">You can use these details to log in using any mail client.</Text>

      <Box pt="2">
        <Tabs.Root defaultValue="smtp">
          <Tabs.List size="2">
            <Tabs.Trigger value="smtp">Outgoing</Tabs.Trigger>
            <Tabs.Trigger value="imap">Incoming</Tabs.Trigger>
            <Flex align="center" justify="end" grow="1" pr="3">
              <Link href={WEBMAIL_URL} target="_blank">
                <Button variant="ghost">Webmail <ExternalLinkIcon size="14" /></Button>
              </Link>
            </Flex>
          </Tabs.List>

          <Box pt="3" pb="2">
            <Tabs.Content value="smtp">
              <StaticValueField label="SMTP Server" value={EMAIL_HOST} />
              <StaticValueField label="SMTP Port" value={SMTP_PORT} />
              <StaticValueField label="Connection security" value={SMTP_SECURITY} />
            </Tabs.Content>
            <Tabs.Content value="imap">
              <StaticValueField label="IMAP Server" value={EMAIL_HOST} />
              <StaticValueField label="IMAP Port" value={IMAP_PORT} />
              <StaticValueField label="Connection security" value={IMAP_SECURITY} />
            </Tabs.Content>
          </Box>
        </Tabs.Root>
      </Box>
    </Card>
  );
}