import { Card, Checkbox, Field, Label, Select } from '@/Components/ui';
import { AlertCircle } from 'lucide-react';
import type { FormErrors, FormShape, SettingsPayload, UpdateFn } from './types';

type Props = {
    form: FormShape;
    errors: FormErrors;
    update: UpdateFn;
    settings: SettingsPayload;
};

export default function AppTab({ form, errors, update, settings }: Props) {
    // Backend exposes app.* + session.driver only after Phase 6 ships. Until
    // those keys land in the payload we hide the controls so the tab doesn't
    // imply "wired" without the boot-time overlay being in place.
    const hasAppToggles =
        settings.app_debug !== undefined &&
        settings.app_cache_enabled !== undefined &&
        settings.session_driver !== undefined;

    return (
        <div className="space-y-6">
            <CronStatusCard />

            <Card padding="lg">
                <header className="mb-5">
                    <h2 className="text-base font-semibold tracking-tight text-foreground">
                        Branding & metadata
                    </h2>
                    <p className="mt-1 text-[12px] text-muted-foreground">
                        Site name in the header, page titles, and emails. Logos
                        and favicon live in{' '}
                        <a
                            href="/admin/appearance"
                            className="font-medium text-accent underline underline-offset-2 hover:no-underline"
                        >
                            Appearance → Brand assets
                        </a>
                        .
                    </p>
                </header>

                <div className="space-y-4">
                    <Field
                        id="site_name"
                        label="App name"
                        value={form.site_name}
                        onChange={(e) => update('site_name', e.target.value)}
                        error={errors.site_name}
                        required
                        data-testid="admin-settings-site-name"
                    />

                    <div className="space-y-1.5">
                        <Label htmlFor="default_currency">
                            Default currency
                        </Label>
                        <Select
                            id="default_currency"
                            value={form.default_currency}
                            onChange={(e) =>
                                update('default_currency', e.target.value)
                            }
                            data-testid="admin-settings-default-currency"
                        >
                            <option value="USD">USD — US Dollar</option>
                            <option value="INR">INR — Indian Rupee</option>
                            <option value="EUR">EUR — Euro</option>
                            <option value="GBP">GBP — British Pound</option>
                        </Select>
                        <p className="text-[11px] text-muted-foreground">
                            Replaced by Currencies tab once enabled — admin
                            manages a CRUD list there with rates and
                            formatting.
                        </p>
                    </div>

                    {hasAppToggles && (
                        <div className="space-y-1.5">
                            <Label htmlFor="session_driver">
                                Session driver
                            </Label>
                            <Select
                                id="session_driver"
                                value={form.session_driver}
                                onChange={(e) =>
                                    update(
                                        'session_driver',
                                        e.target.value as 'database' | 'file',
                                    )
                                }
                                data-testid="admin-settings-session-driver"
                            >
                                <option value="database">Database</option>
                                <option value="file">File</option>
                            </Select>
                            <p className="text-[11px] text-muted-foreground">
                                Database persists sessions across worker
                                processes. File is faster for single-host
                                installs without a load balancer.
                            </p>
                        </div>
                    )}

                    <Field
                        id="site_support_email"
                        label="Support email"
                        type="email"
                        value={form.site_support_email}
                        onChange={(e) =>
                            update('site_support_email', e.target.value)
                        }
                        error={errors.site_support_email}
                        hint="Shown in transactional emails and the help footer. Leave blank to omit."
                        data-testid="admin-settings-support-email"
                    />
                    <Field
                        id="site_terms_url"
                        label="Terms URL"
                        type="url"
                        value={form.site_terms_url}
                        onChange={(e) =>
                            update('site_terms_url', e.target.value)
                        }
                        error={errors.site_terms_url}
                        placeholder="https://"
                        data-testid="admin-settings-terms-url"
                    />
                    <Field
                        id="site_privacy_url"
                        label="Privacy URL"
                        type="url"
                        value={form.site_privacy_url}
                        onChange={(e) =>
                            update('site_privacy_url', e.target.value)
                        }
                        error={errors.site_privacy_url}
                        placeholder="https://"
                        data-testid="admin-settings-privacy-url"
                    />

                    {hasAppToggles && (
                        <div className="space-y-3 border-t border-border pt-4">
                            <label className="flex items-start gap-3">
                                <Checkbox
                                    checked={form.app_debug}
                                    onChange={(e) =>
                                        update('app_debug', e.target.checked)
                                    }
                                    wrapperClassName="mt-0.5"
                                    data-testid="admin-settings-app-debug"
                                />
                                <span>
                                    <span className="block text-sm font-medium text-foreground">
                                        App debug
                                    </span>
                                    <span className="mt-1 block text-[12px] text-muted-foreground">
                                        Verbose error pages with stack traces.
                                        Leave off in production — exposes
                                        config + DB shape on errors.
                                    </span>
                                    {form.app_debug && (
                                        <span className="mt-2 inline-flex items-start gap-1.5 rounded-md border border-warning/30 bg-warning/10 px-2 py-1 text-[11px] font-medium text-foreground">
                                            <AlertCircle
                                                className="mt-0.5 h-3 w-3 flex-none"
                                                strokeWidth={2.5}
                                            />
                                            Stack traces visible to all
                                            visitors while this is on.
                                        </span>
                                    )}
                                </span>
                            </label>

                            <label className="flex items-start gap-3">
                                <Checkbox
                                    checked={form.app_cache_enabled}
                                    onChange={(e) =>
                                        update(
                                            'app_cache_enabled',
                                            e.target.checked,
                                        )
                                    }
                                    wrapperClassName="mt-0.5"
                                    data-testid="admin-settings-app-cache"
                                />
                                <span>
                                    <span className="block text-sm font-medium text-foreground">
                                        Enable cache
                                    </span>
                                    <span className="mt-1 block text-[12px] text-muted-foreground">
                                        Persistent app cache (sessions,
                                        config). Disable to force fresh
                                        reads — useful when debugging stale
                                        config.
                                    </span>
                                </span>
                            </label>
                        </div>
                    )}

                    <Field
                        id="audit_retention_days"
                        label="Audit log retention (days)"
                        type="number"
                        value={form.audit_retention_days}
                        onChange={(e) =>
                            update('audit_retention_days', e.target.value)
                        }
                        error={errors.audit_retention_days}
                        min={30}
                        max={3650}
                        hint="How long admin-action audit rows are kept before the weekly purge sweep. 30-3650 days; default 730 (~2 years)."
                        data-testid="admin-settings-audit-retention"
                    />
                </div>
            </Card>

            <DeviceFrameAttributionsCard />
        </div>
    );
}

/**
 * Required attribution for the photorealistic device frames bundled under
 * `public/device-frames/`. Apple's Marketing Guidelines and Google's Play
 * Console asset library both grant free use for promoting App Store / Play
 * Store apps but ask for visible attribution acknowledging trademark
 * ownership. Surfaced in admin settings so the operator can copy the text
 * into their own site footer / About page if their distribution channel
 * requires it.
 */
function DeviceFrameAttributionsCard() {
    return (
        <Card padding="lg">
            <header className="mb-3">
                <h2 className="text-base font-semibold tracking-tight text-foreground">
                    Device frame attributions
                </h2>
                <p className="mt-1 text-[12px] text-muted-foreground">
                    Photorealistic device frames bundled under{' '}
                    <code>public/device-frames/</code> are used under each
                    vendor's marketing guidelines. Copy this text into your
                    site's footer or About page if your distribution channel
                    requires explicit attribution.
                </p>
            </header>
            <div className="space-y-2 rounded-lg border border-border bg-muted/30 px-4 py-3 text-[12px] leading-relaxed text-foreground">
                <p>
                    iPhone and iPad device frames are used under{' '}
                    <a
                        href="https://developer.apple.com/app-store/marketing/guidelines/"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-medium text-accent underline underline-offset-2 hover:no-underline"
                    >
                        Apple Marketing Guidelines
                    </a>{' '}
                    for promoting App Store apps. iPhone, iPad, and all related
                    marks are trademarks of Apple Inc.
                </p>
                <p>
                    Pixel device frames are used under{' '}
                    <a
                        href="https://play.google.com/console/about/assetlibrary/"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-medium text-accent underline underline-offset-2 hover:no-underline"
                    >
                        Google's Play Console asset library
                    </a>{' '}
                    terms for promoting Play Store apps. Pixel and all related
                    marks are trademarks of Google LLC.
                </p>
            </div>
        </Card>
    );
}

function CronStatusCard() {
    return (
        <Card padding="lg">
            <header className="mb-3">
                <h2 className="text-base font-semibold tracking-tight text-foreground">
                    Cron job
                </h2>
                <p className="mt-1 text-[12px] text-muted-foreground">
                    The scheduler dispatches background jobs (queue worker,
                    invoice retries, audit-log purge). Add this entry to your
                    server crontab so AppShot AI can fire scheduled work.
                </p>
            </header>
            <div className="rounded-lg border border-border bg-muted/30 px-3 py-2 font-mono text-[12px] text-foreground">
                * * * * * cd /path/to/appshot-studio && php artisan
                schedule:run &gt;&gt; /dev/null 2&gt;&amp;1
            </div>
            <p className="mt-2 text-[11px] text-muted-foreground">
                Replace <code>/path/to/appshot-studio</code> with the
                absolute path to this install. Most shared hosts (Hostinger,
                cPanel) expose a "Cron Jobs" UI — paste the line above.
            </p>
        </Card>
    );
}
