import { useState, useEffect } from 'react';
import {
    Form, Input, Button, Card, Divider, Row, Col,
    message, Tabs, Alert, Tooltip, Upload, Select
} from 'antd';
import {
    SaveOutlined,
    MailOutlined,
    BankOutlined,
    CloudOutlined,
    CreditCardOutlined,
    EyeInvisibleOutlined,
    UploadOutlined,
    GlobalOutlined,
} from '@ant-design/icons';
import { getWebsite, updateWebsite } from '../../config/website';
import { getSystemConfig, updateSystemConfig } from '../../config/systemConfig';

const { Password } = Input;

const MASK_PLACEHOLDER = '••••••••';

// ─── Helper: mask badge ───────────────────────────────────────────────────────
const SecretLabel = ({ label, hasVal }) => (
    <span className="flex items-center gap-2">
        {label}
        {hasVal && (
            <Tooltip title="Đã có giá trị. Để trống nếu không muốn thay đổi.">
                <span className="inline-flex items-center gap-1 text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full border border-green-200">
                    <span className="w-1.5 h-1.5 rounded-full bg-green-500 inline-block" />
                    Đã cấu hình
                </span>
            </Tooltip>
        )}
    </span>
);

// ─── Tab 1: Cấu hình Website ─────────────────────────────────────────────────
const WebsiteTab = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [logoFileList, setLogoFileList] = useState([]);
    const [faviconFileList, setFaviconFileList] = useState([]);
    const [bannerFileList, setBannerFileList] = useState([]);

    const fetchData = async () => {
        try {
            setLoading(true);
            const res = await getWebsite();
            const data = res?.metadata;
            if (data) {
                if (data.logo) setLogoFileList([{ uid: '-1', name: 'logo', status: 'done', url: data.logo }]);
                if (data.favicon) setFaviconFileList([{ uid: '-2', name: 'favicon', status: 'done', url: data.favicon }]);
                if (data.banner?.length) {
                    setBannerFileList(data.banner.map((url, i) => ({ uid: `-${i + 3}`, name: `banner-${i + 1}`, status: 'done', url })));
                }
                form.setFieldsValue(data);
            }
        } catch {
            message.error('Không thể tải cấu hình website!');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchData(); }, []);

    const onFinish = async (values) => {
        try {
            setSaving(true);
            const formData = new FormData();

            // Text fields
            Object.entries(values).forEach(([k, v]) => {
                if (!['logo', 'favicon', 'banner'].includes(k) && v != null) {
                    formData.append(k, v);
                }
            });

            // Logo / favicon
            if (logoFileList[0]?.originFileObj) formData.append('logo', logoFileList[0].originFileObj);
            if (faviconFileList[0]?.originFileObj) formData.append('favicon', faviconFileList[0].originFileObj);

            // Banner
            const existingBanners = [];
            bannerFileList.forEach((f) => {
                if (f.originFileObj) formData.append('banner', f.originFileObj);
                else if (f.url) existingBanners.push(f.url.replace(`${import.meta.env.VITE_API_URL}/uploads/websites`, ''));
            });
            existingBanners.forEach((b) => formData.append('banner', b));
            if (bannerFileList.length === 0) formData.append('banner', '');

            await updateWebsite(formData);
            message.success('Cập nhật website thành công!');
            await fetchData();
        } catch {
            message.error('Cập nhật thất bại!');
        } finally {
            setSaving(false);
        }
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} disabled={loading}>
            <Row gutter={24}>
                <Col span={24} md={12}>
                    <Divider orientation="left">Thông tin chung</Divider>
                    <Form.Item name="nameWebsite" label="Tên Website" rules={[{ required: true, message: 'Vui lòng nhập tên website!' }]}>
                        <Input placeholder="Nhập tên website" />
                    </Form.Item>
                    <Form.Item
                        name="domain"
                        label="Tên miền (Domain)"
                        help="VD: https://yourdomain.com — dùng cho link redirect sau thanh toán"
                    >
                        <Input placeholder="https://yourdomain.com" />
                    </Form.Item>
                    <Form.Item name="description" label="Mô tả">
                        <Input.TextArea rows={3} placeholder="Mô tả website" />
                    </Form.Item>
                    <Form.Item name="keywords" label="Từ khóa" help="Ngăn cách bằng dấu phẩy">
                        <Input.TextArea rows={2} placeholder="game, nick, acc..." />
                    </Form.Item>
                    <Form.Item name="status" label="Trạng thái">
                        <Select placeholder="Chọn trạng thái">
                            <Select.Option value="active">
                                <span className="flex items-center gap-2">
                                    <span className="inline-block w-2 h-2 rounded-full bg-green-500" />
                                    Hoạt động
                                </span>
                            </Select.Option>
                            <Select.Option value="maintenance">
                                <span className="flex items-center gap-2">
                                    <span className="inline-block w-2 h-2 rounded-full bg-orange-400" />
                                    Bảo trì
                                </span>
                            </Select.Option>
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={24} md={12}>
                    <Divider orientation="left">Liên hệ & Chủ sở hữu</Divider>
                    <Form.Item name="author" label="Tác giả / Chủ sở hữu">
                        <Input placeholder="Tên tác giả" />
                    </Form.Item>
                    <Form.Item name="contact" label="Email / SĐT liên hệ">
                        <Input placeholder="Email hoặc số điện thoại" />
                    </Form.Item>
                    <Form.Item name="social" label="Mạng xã hội">
                        <Input placeholder="Link Facebook, Zalo..." />
                    </Form.Item>
                </Col>
            </Row>

            <Divider orientation="left">Hình ảnh</Divider>
            <Row gutter={24}>
                <Col span={24} md={8}>
                    <Form.Item label="Logo Website">
                        <Upload listType="picture-card" fileList={logoFileList} onChange={({ fileList }) => setLogoFileList(fileList)} beforeUpload={() => false} maxCount={1} accept="image/*">
                            {logoFileList.length < 1 && <div><UploadOutlined /><div style={{ marginTop: 8 }}>Upload</div></div>}
                        </Upload>
                    </Form.Item>
                </Col>
                <Col span={24} md={8}>
                    <Form.Item label="Favicon">
                        <Upload listType="picture-card" fileList={faviconFileList} onChange={({ fileList }) => setFaviconFileList(fileList)} beforeUpload={() => false} maxCount={1} accept="image/*">
                            {faviconFileList.length < 1 && <div><UploadOutlined /><div style={{ marginTop: 8 }}>Upload</div></div>}
                        </Upload>
                    </Form.Item>
                </Col>
                <Col span={24} md={8}>
                    <Form.Item label="Banner (Nhiều ảnh)">
                        <Upload listType="picture-card" fileList={bannerFileList} onChange={({ fileList }) => setBannerFileList(fileList)} beforeUpload={() => false} multiple accept="image/*">
                            <div><UploadOutlined /><div style={{ marginTop: 8 }}>Upload</div></div>
                        </Upload>
                    </Form.Item>
                </Col>
            </Row>

            <div className="flex justify-end">
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />} size="large" loading={saving} className="bg-blue-600 min-w-[160px]">
                    Lưu Website
                </Button>
            </div>
        </Form>
    );
};

// ─── Tab 2-5: System Config ──────────────────────────────────────────────────
const SystemTab = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [originalData, setOriginalData] = useState({});

    const SENSITIVE = ['emailClientSecret', 'emailRefreshToken', 'sepaySecret', 'cloudinarySecret', 'tsrPartnerKey'];

    const fetchConfig = async () => {
        try {
            setLoading(true);
            const data = await getSystemConfig();
            if (data) {
                setOriginalData(data);
                form.setFieldsValue({
                    emailUser: data.emailUser || '',
                    emailClientId: data.emailClientId || '',
                    emailClientSecret: data.emailClientSecret || '',
                    emailRedirectUri: data.emailRedirectUri || '',
                    emailRefreshToken: data.emailRefreshToken || '',
                    sepayMode: data.sepayMode || 'sandbox',
                    sepayId: data.sepayId || '',
                    sepaySecret: data.sepaySecret || '',
                    cloudinaryName: data.cloudinaryName || '',
                    cloudinaryKey: data.cloudinaryKey || '',
                    cloudinarySecret: data.cloudinarySecret || '',
                    tsrPartnerId: data.tsrPartnerId || '',
                    tsrPartnerKey: data.tsrPartnerKey || '',
                    tsrUrl: data.tsrUrl || 'https://thesieure.com/chargingws/v2',
                });
            }
        } catch {
            message.error('Không thể tải cấu hình hệ thống!');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchConfig(); }, []);

    const onFinish = async (values) => {
        try {
            setSaving(true);
            await updateSystemConfig(values);
            message.success('Cập nhật cấu hình thành công!');
            await fetchConfig();
        } catch {
            message.error('Cập nhật thất bại!');
        } finally {
            setSaving(false);
        }
    };

    const hasVal = (field) => {
        const v = originalData[field];
        return v && v.length > 0 && !v.startsWith('***');
    };

    const SLabel = ({ label, field }) => <SecretLabel label={label} hasVal={hasVal(field)} />;

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} disabled={loading}>
            <Alert
                type="info" showIcon icon={<EyeInvisibleOutlined />} className="mb-6"
                message="Bảo mật"
                description="Các trường mật khẩu / secret key được ẩn. Để trống nếu không muốn thay đổi giá trị hiện tại."
            />

            <Tabs type="card">
                {/* Email */}
                <Tabs.TabPane tab={<span><MailOutlined /> Email</span>} key="email">
                    <Card className="shadow-sm">
                        <Alert type="warning" showIcon className="mb-4"
                            message="Google OAuth2"
                            description={<>Tạo tại <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noreferrer" className="underline">Google Cloud Console</a> và lấy Refresh Token từ <a href="https://developers.google.com/oauthplayground" target="_blank" rel="noreferrer" className="underline">OAuth Playground</a></>}
                        />
                        <Row gutter={24}>
                            <Col span={24} md={12}><Form.Item name="emailUser" label="Gmail gửi mail"><Input prefix={<MailOutlined />} placeholder="example@gmail.com" /></Form.Item></Col>
                            <Col span={24} md={12}><Form.Item name="emailRedirectUri" label="Redirect URI"><Input placeholder="https://developers.google.com/oauthplayground" /></Form.Item></Col>
                            <Col span={24} md={12}><Form.Item name="emailClientId" label="Client ID"><Input placeholder="Nhập Client ID" /></Form.Item></Col>
                            <Col span={24} md={12}><Form.Item name="emailClientSecret" label="Client Secret"><Password placeholder="Nhập Client Secret" autoComplete="new-password" /></Form.Item></Col>
                            <Col span={24}><Form.Item name="emailRefreshToken" label="Refresh Token"><Password placeholder="Nhập Refresh Token" autoComplete="new-password" /></Form.Item></Col>
                        </Row>
                    </Card>
                </Tabs.TabPane>

                {/* SePay */}
                <Tabs.TabPane tab={<span><BankOutlined /> SePay</span>} key="sepay">
                    <Card className="shadow-sm">
                        <Alert type="info" showIcon className="mb-4" message="SePay — Thanh toán QR ngân hàng"
                            description={<>Lấy thông tin tại <a href="https://sepay.vn" target="_blank" rel="noreferrer" className="underline">sepay.vn</a></>}
                        />
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item name="sepayMode" label="Chế độ">
                                    <Select>
                                        <Select.Option value="sandbox">
                                            <span className="flex items-center gap-2">
                                                <span className="inline-block w-2 h-2 rounded-full bg-yellow-400" />
                                                Thử nghiệm (Sandbox)
                                            </span>
                                        </Select.Option>
                                        <Select.Option value="production">
                                            <span className="flex items-center gap-2">
                                                <span className="inline-block w-2 h-2 rounded-full bg-green-500" />
                                                Sản xuất (Production)
                                            </span>
                                        </Select.Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={24} md={12}><Form.Item name="sepayId" label="SePay ID"><Input placeholder="SP-TEST-xxxxxxxx" /></Form.Item></Col>
                            <Col span={24} md={12}><Form.Item name="sepaySecret" label="Secret Key"><Password placeholder="Nhập Secret Key" autoComplete="new-password" /></Form.Item></Col>
                        </Row>
                    </Card>
                </Tabs.TabPane>

                {/* Cloudinary */}
                <Tabs.TabPane tab={<span><CloudOutlined /> Cloudinary</span>} key="cloudinary">
                    <Card className="shadow-sm">
                        <Alert type="info" showIcon className="mb-4" message="Cloudinary — Lưu trữ ảnh"
                            description={<>Lấy tại <a href="https://cloudinary.com/console" target="_blank" rel="noreferrer" className="underline">Cloudinary Console</a></>}
                        />
                        <Row gutter={24}>
                            <Col span={24} md={8}><Form.Item name="cloudinaryName" label="Cloud Name"><Input placeholder="Cloud Name" /></Form.Item></Col>
                            <Col span={24} md={8}><Form.Item name="cloudinaryKey" label="API Key"><Input placeholder="API Key" /></Form.Item></Col>
                            <Col span={24} md={8}><Form.Item name="cloudinarySecret" label="API Secret"><Password placeholder="API Secret" autoComplete="new-password" /></Form.Item></Col>
                        </Row>
                    </Card>
                </Tabs.TabPane>

                {/* TSR */}
                <Tabs.TabPane tab={<span><CreditCardOutlined /> Thẻ cào</span>} key="tsr">
                    <Card className="shadow-sm">
                        <Alert type="info" showIcon className="mb-4" message="TheSieuRe — Nạp thẻ"
                            description={<>Lấy tại <a href="https://thesieure.com" target="_blank" rel="noreferrer" className="underline">thesieure.com</a></>}
                        />
                        <Row gutter={24}>
                            <Col span={24} md={8}><Form.Item name="tsrPartnerId" label="Partner ID"><Input placeholder="Partner ID" /></Form.Item></Col>
                            <Col span={24} md={8}><Form.Item name="tsrPartnerKey" label="Partner Key"><Password placeholder="Partner Key" autoComplete="new-password" /></Form.Item></Col>
                            <Col span={24} md={8}><Form.Item name="tsrUrl" label="API URL"><Input placeholder="https://thesieure.com/chargingws/v2" /></Form.Item></Col>
                        </Row>
                    </Card>
                </Tabs.TabPane>
            </Tabs>

            <Divider />
            <div className="flex justify-end">
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />} size="large" loading={saving} className="bg-blue-600 min-w-[160px]">
                    Lưu cấu hình
                </Button>
            </div>
        </Form>
    );
};

// ─── Main Page ────────────────────────────────────────────────────────────────
const SystemConfigManager = () => (
    <div className="p-4 mx-auto">
        <div className="mb-6">
            <h2 className="text-2xl font-bold text-gray-800 mb-1">Cấu hình hệ thống</h2>
            <p className="text-gray-500 text-sm">Quản lý website và các tích hợp dịch vụ bên thứ ba</p>
        </div>

        <Tabs defaultActiveKey="website" type="line" size="large"
            items={[
                {
                    key: 'website',
                    label: <span className="flex items-center gap-2"><GlobalOutlined /> Cấu hình Website</span>,
                    children: (
                        <Card className="shadow-sm">
                            <WebsiteTab />
                        </Card>
                    ),
                },
                {
                    key: 'integrations',
                    label: <span className="flex items-center gap-2"><CloudOutlined /> Tích hợp dịch vụ</span>,
                    children: <SystemTab />,
                },
            ]}
        />
    </div>
);

export default SystemConfigManager;
