import { ReactNode, useEffect, useRef, useState } from "react";
import { Alert, Button, Card, Divider, Form, Input, Segmented, Space, Typography } from "antd";
import type { InputRef } from "antd";
import { sendLoginSMS } from "./api";

export type LoginMode = "account_password" | "phone_password" | "phone_sms";

type LoginProps = {
  username: string;
  password: string;
  displayName: string;
  busy: boolean;
  error: string;
  info: string;
  onUsername: (v: string) => void;
  onPassword: (v: string) => void;
  onDisplayName: (v: string) => void;
  onLogin: (payload: {
    mode: LoginMode;
    username?: string;
    phone?: string;
    password?: string;
    sms_code?: string;
  }) => void;
  onRegister: (username: string, password: string, displayName: string) => void;
};

type PendingProps = {
  displayLabel: string;
  inviteCode: string;
  companyName: string;
  busy: boolean;
  error: string;
  info: string;
  onInviteCode: (v: string) => void;
  onCompanyName: (v: string) => void;
  onAcceptInvite: () => void;
  onCreateCompany: () => void;
  onLogout: () => void;
};

function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }) {
  return (
    <div className="auth-shell">
      <div className="auth-backdrop" aria-hidden />
      <Card className="auth-card" bordered={false}>
        <Typography.Title level={2} className="auth-brand">
          宇信达智建
        </Typography.Title>
        <Typography.Paragraph type="secondary" style={{ marginTop: -8 }}>
          {subtitle}
        </Typography.Paragraph>
        {children}
      </Card>
    </div>
  );
}

function readInputValue(ref: React.RefObject<InputRef | null>, fallback: string): string {
  const el = ref.current?.input;
  if (el && typeof el.value === "string") return el.value;
  return fallback;
}

export function LoginShell(props: LoginProps) {
  const [mode, setMode] = useState<LoginMode>("account_password");
  const [smsCode, setSmsCode] = useState("");
  const [smsHint, setSmsHint] = useState("");
  const [cooldown, setCooldown] = useState(0);
  const [sending, setSending] = useState(false);
  const userRef = useRef<InputRef>(null);
  const passRef = useRef<InputRef>(null);
  const nameRef = useRef<InputRef>(null);
  const phoneRef = useRef<InputRef>(null);
  const codeRef = useRef<InputRef>(null);

  useEffect(() => {
    if (cooldown <= 0) return;
    const t = window.setTimeout(() => setCooldown((c) => c - 1), 1000);
    return () => window.clearTimeout(t);
  }, [cooldown]);

  const doLogin = () => {
    if (mode === "phone_sms") {
      const phone = readInputValue(phoneRef, props.username).trim();
      const code = readInputValue(codeRef, smsCode).trim();
      props.onUsername(phone);
      props.onLogin({ mode, phone, sms_code: code });
      return;
    }
    if (mode === "phone_password") {
      const phone = readInputValue(phoneRef, props.username).trim();
      const p = readInputValue(passRef, props.password);
      props.onUsername(phone);
      props.onPassword(p);
      props.onLogin({ mode, phone, password: p });
      return;
    }
    const u = readInputValue(userRef, props.username).trim();
    const p = readInputValue(passRef, props.password);
    props.onUsername(u);
    props.onPassword(p);
    props.onLogin({ mode, username: u, password: p });
  };

  const doRegister = () => {
    const u = readInputValue(userRef, props.username).trim() || readInputValue(phoneRef, props.username).trim();
    const p = readInputValue(passRef, props.password);
    const n = readInputValue(nameRef, props.displayName).trim();
    props.onUsername(u);
    props.onPassword(p);
    props.onDisplayName(n);
    props.onRegister(u, p, n);
  };

  async function onSendSMS() {
    const phone = readInputValue(phoneRef, props.username).trim();
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      setSmsHint("请先填写正确的 11 位手机号");
      return;
    }
    setSending(true);
    setSmsHint("");
    try {
      const res = await sendLoginSMS(phone);
      setCooldown(res.retry_after && res.retry_after > 0 ? res.retry_after : 60);
      if (res.debug_code) {
        setSmsCode(res.debug_code);
        setSmsHint(`开发模式验证码：${res.debug_code}（正式环境将发短信）`);
      } else {
        setSmsHint(res.message || "验证码已发送");
      }
    } catch (e: any) {
      setSmsHint(e.message || String(e));
    } finally {
      setSending(false);
    }
  }

  return (
    <Shell subtitle="描述 + Excel/CSV/JSON → 自动建库建 API → 生成可操作的前端页面">
      <Segmented
        block
        style={{ marginBottom: 16 }}
        value={mode}
        onChange={(v) => setMode(v as LoginMode)}
        options={[
          { label: "账号密码", value: "account_password" },
          { label: "手机密码", value: "phone_password" },
          { label: "短信登录", value: "phone_sms" },
        ]}
      />
      <Form layout="vertical" requiredMark={false} onFinish={doLogin}>
        {mode === "account_password" ? (
          <Form.Item label="用户名">
            <Input
              ref={userRef}
              size="large"
              value={props.username}
              onChange={(e) => props.onUsername(e.target.value)}
              autoComplete="username"
              placeholder="系统分配的用户名"
              allowClear
            />
          </Form.Item>
        ) : (
          <Form.Item label="手机号">
            <Input
              ref={phoneRef}
              size="large"
              value={props.username}
              onChange={(e) => props.onUsername(e.target.value)}
              autoComplete="tel"
              placeholder="已绑定的 11 位手机号"
              allowClear
            />
          </Form.Item>
        )}

        {mode === "phone_sms" ? (
          <Form.Item label="短信验证码">
            <Space.Compact style={{ width: "100%" }}>
              <Input
                ref={codeRef}
                size="large"
                value={smsCode}
                onChange={(e) => setSmsCode(e.target.value)}
                placeholder="6 位验证码"
                maxLength={8}
              />
              <Button size="large" loading={sending} disabled={cooldown > 0 || props.busy} onClick={() => void onSendSMS()}>
                {cooldown > 0 ? `${cooldown}s` : "获取验证码"}
              </Button>
            </Space.Compact>
          </Form.Item>
        ) : (
          <Form.Item label="密码">
            <Input.Password
              ref={passRef}
              size="large"
              value={props.password}
              onChange={(e) => props.onPassword(e.target.value)}
              autoComplete="current-password"
            />
          </Form.Item>
        )}

        {mode === "account_password" ? (
          <Form.Item label="显示名（仅注册用，登录可忽略）">
            <Input
              ref={nameRef}
              size="large"
              value={props.displayName}
              onChange={(e) => props.onDisplayName(e.target.value)}
            />
          </Form.Item>
        ) : null}

        {props.error ? (
          <Alert type="error" showIcon message={props.error} style={{ marginBottom: 16 }} />
        ) : null}
        {smsHint ? <Alert type="info" showIcon message={smsHint} style={{ marginBottom: 16 }} /> : null}
        {props.info && !props.info.startsWith("已填入测试默认") ? (
          <Alert type="success" showIcon message={props.info} style={{ marginBottom: 16 }} />
        ) : null}

        {mode === "account_password" ? (
          <Space wrap style={{ marginBottom: 12 }}>
            <Button
              type="link"
              size="small"
              onClick={() => {
                props.onUsername("demo");
                props.onPassword("demo123");
                props.onDisplayName("演示用户");
              }}
            >
              填入 demo
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() => {
                props.onUsername("ljk_admin");
                props.onPassword("ljk_admin");
                props.onDisplayName("平台超级管理员");
              }}
            >
              填入 ljk_admin
            </Button>
          </Space>
        ) : (
          <Space wrap style={{ marginBottom: 12 }}>
            <Button
              type="link"
              size="small"
              onClick={() => {
                props.onUsername("13800000001");
                props.onPassword("demo123");
              }}
            >
              填入 demo 手机
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() => {
                props.onUsername("13531041945");
                props.onPassword("ljk_admin");
              }}
            >
              填入超管手机
            </Button>
          </Space>
        )}

        <div className="auth-actions">
          <Button type="primary" htmlType="submit" size="large" block loading={props.busy}>
            登录
          </Button>
          {mode === "account_password" ? (
            <Button htmlType="button" size="large" block disabled={props.busy} onClick={doRegister}>
              注册
            </Button>
          ) : null}
        </div>
        <Typography.Paragraph type="secondary" style={{ marginTop: 20, marginBottom: 0, fontSize: 13 }}>
          支持用户名+密码、手机号+密码、手机号+短信。外公司部署用 License 控期限时，不必强制手机登录。
        </Typography.Paragraph>
      </Form>
    </Shell>
  );
}

export function PendingShell(props: PendingProps) {
  return (
    <Shell subtitle="账号已注册，但尚未加入任何公司。未入驻前不能查看未公布数据与业务页面。">
      <Typography.Text type="secondary">{props.displayLabel} · pending</Typography.Text>
      {props.error && <Alert type="error" showIcon message={props.error} style={{ margin: "16px 0" }} />}
      {props.info && <Alert type="success" showIcon message={props.info} style={{ margin: "16px 0" }} />}
      <Form layout="vertical" style={{ marginTop: 16 }} requiredMark={false}>
        <Form.Item label="邀请码">
          <Input
            size="large"
            value={props.inviteCode}
            onChange={(e) => props.onInviteCode(e.target.value)}
            placeholder="粘贴公司管理员发来的邀请码"
          />
        </Form.Item>
        <Button
          type="primary"
          size="large"
          block
          loading={props.busy}
          disabled={!props.inviteCode.trim()}
          onClick={props.onAcceptInvite}
        >
          加入已有公司
        </Button>
        <Divider>或</Divider>
        <Form.Item label="公司名称">
          <Input
            size="large"
            value={props.companyName}
            onChange={(e) => props.onCompanyName(e.target.value)}
            placeholder="创建自己的公司（成为管理员）"
          />
        </Form.Item>
        <Space direction="vertical" style={{ width: "100%" }}>
          <Button size="large" block loading={props.busy} onClick={props.onCreateCompany}>
            创建公司
          </Button>
          <Button size="large" block onClick={props.onLogout}>
            退出
          </Button>
        </Space>
      </Form>
    </Shell>
  );
}

export function LoadingShell(props: { message: string; error?: string }) {
  return (
    <Shell subtitle={props.message}>
      {props.error ? <Alert type="error" showIcon message={props.error} /> : null}
    </Shell>
  );
}
