import { useState, useMemo } from 'react';
import {
  Button,
  Space,
  Typography,
  Popconfirm,
  Tag,
  message,
  Tooltip,
  Modal,
  Select,
  Switch,
  Input,
  Form,
} from 'antd';
import {
  LinkOutlined,
  CopyOutlined,
  MailOutlined,
  DeleteOutlined,
  QrcodeOutlined,
  CheckCircleOutlined,
  ReloadOutlined,
  SettingOutlined,
  LockOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { Contact, ProfileLinkResponse } from '@/types/api';

// Use relative URL — VITE_API_URL is a Docker-internal hostname the browser cannot resolve
const API_BASE = '';

const EXPIRATION_OPTIONS = [
  { value: '24h', label: '24 hours' },
  { value: '7d', label: '7 days' },
  { value: '30d', label: '30 days' },
  { value: '90d', label: '90 days' },
  { value: '1y', label: '1 year' },
  { value: 'never', label: 'Never' },
];

interface ProfileLinkActionsProps {
  contact: Contact;
  onRefresh: () => void;
}

type ModalMode = 'generate' | 'rotate' | 'settings';

function getExpiryStatus(expiresAt: string | null): {
  color: 'green' | 'orange' | 'red';
  label: string;
} {
  if (!expiresAt) {
    return { color: 'green', label: 'Active' };
  }

  const now = new Date();
  const expiry = new Date(expiresAt);
  const diffMs = expiry.getTime() - now.getTime();

  if (diffMs <= 0) {
    return { color: 'red', label: 'Expired' };
  }

  const twentyFourHoursMs = 24 * 60 * 60 * 1000;
  if (diffMs < twentyFourHoursMs) {
    return { color: 'orange', label: 'Expiring Soon' };
  }

  return { color: 'green', label: 'Active' };
}

function formatExpiryDate(expiresAt: string | null): string {
  if (!expiresAt) return 'Never expires';
  const d = new Date(expiresAt);
  return `Expires: ${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
}

export default function ProfileLinkActions({ contact, onRefresh }: ProfileLinkActionsProps) {
  const [generating, setGenerating] = useState(false);
  const [sending, setSending] = useState(false);
  const [revoking, setRevoking] = useState(false);
  const [saving, setSaving] = useState(false);
  const [linkData, setLinkData] = useState<ProfileLinkResponse | null>(null);
  const [showQr, setShowQr] = useState(false);

  // Modal state
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<ModalMode>('generate');

  // Modal form state
  const [expiresIn, setExpiresIn] = useState<string>('never');
  const [passwordEnabled, setPasswordEnabled] = useState(false);
  const [password, setPassword] = useState('');
  const [removePassword, setRemovePassword] = useState(false);

  const hasToken = !!contact.profileToken;

  const buildProfileUrl = (token: string) => {
    return `${window.location.origin}/profile/${token}`;
  };

  const profileUrl = hasToken ? buildProfileUrl(contact.profileToken!) : null;

  const expiryStatus = useMemo(
    () => (hasToken ? getExpiryStatus(contact.profileTokenExpiresAt) : null),
    [hasToken, contact.profileTokenExpiresAt],
  );

  const resetModalForm = () => {
    setExpiresIn('never');
    setPasswordEnabled(false);
    setPassword('');
    setRemovePassword(false);
  };

  const openGenerateModal = () => {
    resetModalForm();
    setModalMode('generate');
    setModalOpen(true);
  };

  const openRotateModal = () => {
    resetModalForm();
    setModalMode('rotate');
    setModalOpen(true);
  };

  const openSettingsModal = () => {
    setModalMode('settings');
    setPasswordEnabled(false);
    setPassword('');
    setRemovePassword(false);
    // Default to 'never' for settings — the admin can pick a new value
    setExpiresIn('never');
    setModalOpen(true);
  };

  const handleModalConfirm = async () => {
    if (passwordEnabled && password.length > 0 && password.length < 4) {
      message.warning('Password must be at least 4 characters');
      return;
    }

    if (modalMode === 'settings') {
      // PUT to update settings
      setSaving(true);
      try {
        const body: Record<string, unknown> = { expiresIn };
        if (passwordEnabled && password) {
          body.password = password;
        }
        if (removePassword) {
          body.removePassword = true;
        }
        const { data } = await api.put<ProfileLinkResponse>(
          `/people/contacts/${contact.id}/profile-link`,
          body,
        );
        setLinkData(data);
        message.success('Profile link settings updated');
        setModalOpen(false);
        onRefresh();
      } catch {
        message.error('Failed to update profile link settings');
      } finally {
        setSaving(false);
      }
    } else {
      // POST to generate or rotate
      setGenerating(true);
      try {
        const body: Record<string, unknown> = { expiresIn };
        if (passwordEnabled && password) {
          body.password = password;
        }
        const { data } = await api.post<ProfileLinkResponse>(
          `/people/contacts/${contact.id}/profile-link`,
          body,
        );
        setLinkData(data);
        message.success(
          modalMode === 'rotate' ? 'Profile link rotated with new token' : 'Profile link generated',
        );
        setModalOpen(false);
        onRefresh();
      } catch {
        message.error('Failed to generate profile link');
      } finally {
        setGenerating(false);
      }
    }
  };

  const handleCopy = async () => {
    const url = linkData?.url || profileUrl;
    if (!url) return;
    try {
      await navigator.clipboard.writeText(url);
      message.success('Link copied to clipboard');
    } catch {
      message.error('Failed to copy link');
    }
  };

  const handleSendEmail = async () => {
    if (!contact.email) {
      message.warning('Contact has no email address');
      return;
    }
    setSending(true);
    try {
      await api.post(`/people/contacts/${contact.id}/send-profile-link`);
      message.success(`Profile link sent to ${contact.email}`);
    } catch {
      message.error('Failed to send profile link');
    } finally {
      setSending(false);
    }
  };

  const handleRevoke = async () => {
    setRevoking(true);
    try {
      await api.delete(`/people/contacts/${contact.id}/profile-link`);
      setLinkData(null);
      setShowQr(false);
      message.success('Profile link revoked');
      onRefresh();
    } catch {
      message.error('Failed to revoke profile link');
    } finally {
      setRevoking(false);
    }
  };

  const qrUrl = profileUrl
    ? `${API_BASE}/api/qr?data=${encodeURIComponent(profileUrl)}&size=200`
    : null;

  const isPasswordProtected = linkData?.hasPassword ?? contact.hasProfilePassword;

  const modalTitle =
    modalMode === 'generate'
      ? 'Generate Profile Link'
      : modalMode === 'rotate'
        ? 'Rotate Profile Link'
        : 'Profile Link Settings';

  const modalOkText =
    modalMode === 'generate'
      ? 'Generate'
      : modalMode === 'rotate'
        ? 'Rotate & Generate'
        : 'Save Settings';

  const passwordInvalid = passwordEnabled && password.length > 0 && password.length < 4;

  return (
    <div
      style={{
        padding: 12,
        borderRadius: 8,
        background: 'rgba(255,255,255,0.03)',
        border: '1px solid rgba(255,255,255,0.06)',
      }}
    >
      {/* Header row with status */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <LinkOutlined style={{ fontSize: 14, color: 'rgba(255,255,255,0.45)' }} />
        <Typography.Text strong style={{ fontSize: 13 }}>
          Profile Link
        </Typography.Text>
        {hasToken && expiryStatus ? (
          <Tooltip title={formatExpiryDate(contact.profileTokenExpiresAt)}>
            <Tag
              color={expiryStatus.color}
              icon={<CheckCircleOutlined />}
              style={{ margin: 0, fontSize: 11, cursor: 'default' }}
            >
              {expiryStatus.label}
            </Tag>
          </Tooltip>
        ) : (
          <Tag color="default" style={{ margin: 0, fontSize: 11 }}>
            Not Generated
          </Tag>
        )}
        {hasToken && isPasswordProtected && (
          <Tooltip title="Password protected">
            <Tag
              icon={<LockOutlined />}
              color="blue"
              style={{ margin: 0, fontSize: 11, cursor: 'default' }}
            >
              Protected
            </Tag>
          </Tooltip>
        )}
        {hasToken && contact.profileTokenExpiresAt && (
          <Tooltip title={formatExpiryDate(contact.profileTokenExpiresAt)}>
            <ClockCircleOutlined
              style={{ fontSize: 12, color: 'rgba(255,255,255,0.35)', cursor: 'default' }}
            />
          </Tooltip>
        )}
      </div>

      {/* Action buttons */}
      <Space size={6} wrap>
        {!hasToken ? (
          <Button
            size="small"
            icon={<LinkOutlined />}
            loading={generating}
            onClick={openGenerateModal}
            type="primary"
          >
            Generate Link
          </Button>
        ) : (
          <>
            <Tooltip title="Copy profile link to clipboard">
              <Button size="small" icon={<CopyOutlined />} onClick={handleCopy}>
                Copy Link
              </Button>
            </Tooltip>
            {contact.email && (
              <Tooltip title={`Send link to ${contact.email}`}>
                <Button
                  size="small"
                  icon={<MailOutlined />}
                  loading={sending}
                  onClick={handleSendEmail}
                >
                  Send Email
                </Button>
              </Tooltip>
            )}
            <Tooltip title="Show QR code">
              <Button
                size="small"
                icon={<QrcodeOutlined />}
                onClick={() => setShowQr(!showQr)}
                type={showQr ? 'primary' : 'default'}
              >
                QR
              </Button>
            </Tooltip>
            <Tooltip title="Link settings (expiration, password)">
              <Button
                size="small"
                icon={<SettingOutlined />}
                onClick={openSettingsModal}
              />
            </Tooltip>
            <Tooltip title="Generate new token (invalidates old link)">
              <Button
                size="small"
                icon={<ReloadOutlined />}
                loading={generating}
                onClick={openRotateModal}
              />
            </Tooltip>
            <Popconfirm
              title="Revoke this profile link?"
              description="The contact will no longer be able to access their profile page."
              onConfirm={handleRevoke}
              okText="Revoke"
              okButtonProps={{ danger: true }}
            >
              <Button size="small" icon={<DeleteOutlined />} danger loading={revoking} />
            </Popconfirm>
          </>
        )}
      </Space>

      {/* QR Code Preview */}
      {showQr && qrUrl && (
        <div style={{ marginTop: 12, textAlign: 'center' }}>
          <img
            src={qrUrl}
            alt="Profile QR Code"
            style={{ borderRadius: 8, background: 'white', padding: 8 }}
            width={200}
            height={200}
          />
          <Typography.Text
            type="secondary"
            style={{ display: 'block', fontSize: 11, marginTop: 4 }}
          >
            Scan to open profile
          </Typography.Text>
        </div>
      )}

      {/* Generate / Rotate / Settings Modal */}
      <Modal
        title={modalTitle}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={handleModalConfirm}
        okText={modalOkText}
        okButtonProps={{
          loading: modalMode === 'settings' ? saving : generating,
          disabled: passwordInvalid,
        }}
        destroyOnClose
      >
        {modalMode === 'rotate' && (
          <Typography.Paragraph type="warning" style={{ marginBottom: 16 }}>
            This will generate a new token and invalidate the existing link. Anyone with the old link
            will no longer be able to access the profile.
          </Typography.Paragraph>
        )}

        <Form layout="vertical">
          <Form.Item label="Link Expiration" style={{ marginBottom: 16 }}>
            <Select
              value={expiresIn}
              onChange={setExpiresIn}
              options={EXPIRATION_OPTIONS}
              style={{ width: '100%' }}
            />
          </Form.Item>

          {modalMode === 'settings' && isPasswordProtected && !passwordEnabled && (
            <Form.Item style={{ marginBottom: 16 }}>
              <Space>
                <Typography.Text type="secondary">
                  <LockOutlined /> Currently password protected
                </Typography.Text>
                <Button
                  size="small"
                  danger
                  onClick={() => {
                    setRemovePassword(true);
                    setPasswordEnabled(false);
                    setPassword('');
                  }}
                  disabled={removePassword}
                >
                  {removePassword ? 'Password will be removed' : 'Remove Password'}
                </Button>
                {removePassword && (
                  <Button
                    size="small"
                    onClick={() => setRemovePassword(false)}
                  >
                    Undo
                  </Button>
                )}
              </Space>
            </Form.Item>
          )}

          <Form.Item
            label={
              <Space>
                <span>
                  {modalMode === 'settings' && isPasswordProtected
                    ? 'Change Password'
                    : 'Password Protection'}
                </span>
                <Switch
                  size="small"
                  checked={passwordEnabled}
                  onChange={(checked) => {
                    setPasswordEnabled(checked);
                    if (checked) {
                      setRemovePassword(false);
                    }
                    if (!checked) {
                      setPassword('');
                    }
                  }}
                />
              </Space>
            }
            style={{ marginBottom: 0 }}
            help={
              passwordInvalid
                ? 'Password must be at least 4 characters'
                : passwordEnabled
                  ? 'Visitors will need this password to view the profile'
                  : undefined
            }
            validateStatus={passwordInvalid ? 'error' : undefined}
          >
            {passwordEnabled && (
              <Input.Password
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Enter password (min 4 characters)"
                style={{ marginTop: 8 }}
              />
            )}
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
