import {
    Bot, Undo2, CheckCircle2, Clock, Download, Eye, FileSignature, Lock, Mail, MailOpen, MessageCircle, MousePointerClick, Paperclip, Radio, Send, ShieldCheck, UserCheck, XCircle,
} from 'lucide-react';
import { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardBody, CardHeader } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Dialog } from '@/components/ui/dialog';
import { Input, Textarea } from '@/components/ui/input';
import { Field } from '@/components/ui/label';
import { dateTime, money } from '@/lib/format';
import { http, HttpError, httpForm } from '@/lib/http';
import { cn } from '@/lib/utils';

type Stats = { email_opens: number; opens: number; seconds_viewed: number; pdf_downloads: number; top_sections: { key: string; seconds: number }[]; viewing_now: number[]; last_viewed_at: string | null };
type Person = { email: string; name: string | null; role: string; emails_sent: number; email_opens: number; opens: number; seconds: number; first_viewed_at: string | null; last_viewed_at: string | null; viewing_now: boolean; bounced: boolean };
type Entry = {
    id: string; kind: string; at: string; text: string; who?: string; detail?: string; email_id?: number; by?: string | null;
    device?: string | null; place?: string | null; ip?: string | null; flagged: boolean; flag_reason?: string | null;
    seconds?: number; sections?: { key: string; seconds: number }[]; pdf?: number; until?: string;
};
type Msg = { id: number; type: 'question' | 'answer' | 'comment' | 'private_note'; parent_id: number | null; body: string; answered_state: string | null; author: string; from_staff: boolean; at: string; files: { name: string; size: number; url: string }[] };
type Decision = {
    decision: 'accepted' | 'declined'; at: string; signer_name: string | null; signer_email: string | null; signature_type: string | null; signature: string | null;
    po_number: string | null; comments: string | null; reason: string | null; totals: { total_cents: number; currency: string } | null;
    selected_options: { optional?: { heading: string; selected: boolean }[]; choices?: Record<string, { heading: string }>; quantities?: { heading: string; qty: string }[] } | null;
    fingerprint: Record<string, string | number | boolean | null>; on_behalf: string | null;
};
type Activity = { stats: Stats; people: Person[]; timeline: Entry[]; messages: Msg[]; decision: Decision | null; status: string; can: { reply: boolean; on_behalf: boolean } };

export const duration = (s: number) => (s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${pad(s % 60)}s` : `${Math.floor(s / 3600)}h ${pad(Math.floor((s % 3600) / 60))}m`);
const pad = (n: number) => String(n).padStart(2, '0');

const ICONS: Record<string, typeof Mail> = {
    email: Send, email_delivered: Mail, email_open: MailOpen, link_click: MousePointerClick, email_bounced: XCircle, view: Eye, view_start: Eye,
    pdf_download: Download, accept: FileSignature, decline: XCircle, question: MessageCircle, unaccept: Undo2,
};

/** Activity for a sent quote: polled every 15 s while the tab is visible. */
export function ActivityPanel({ quoteId, companyId, onStatus }: { quoteId: number; companyId: number; onStatus?: (s: string) => void }) {
    const [data, setData] = useState<Activity | null>(null);
    const [emailView, setEmailView] = useState<number | null>(null);
    const [behalf, setBehalf] = useState(false);
    const [showFlagged, setShowFlagged] = useState(false);
    const [showAll, setShowAll] = useState(false);
    const scrolled = useRef(false);
    // Links like /quotes/12/edit#question-34 jump to the question once the panel has loaded.
    useEffect(() => {
        if (!data || scrolled.current) return;
        const m = window.location.hash.match(/^#question-(\d+)$/);
        if (!m) return;
        scrolled.current = true;
        requestAnimationFrame(() => {
            const el = document.getElementById(`question-${m[1]}`);
            el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
            el?.classList.add('ring-2', 'ring-amber-400');
            window.setTimeout(() => el?.classList.remove('ring-2', 'ring-amber-400'), 4000);
        });
    }, [data]);
    const statusRef = useRef<string | null>(null);

    const load = useCallback(async () => {
        try {
            const a = await http<Activity>('GET', `/quotes/${quoteId}/activity`, undefined, { 'X-Company': String(companyId) });
            setData(a);
            if (statusRef.current && statusRef.current !== a.status) onStatus?.(a.status);
            statusRef.current = a.status;
        } catch { /* keep the last good data */ }
    }, [quoteId, companyId, onStatus]);

    useEffect(() => {
        load();
        const t = window.setInterval(() => { if (document.visibilityState === 'visible') load(); }, 15000);
        const vis = () => { if (document.visibilityState === 'visible') load(); };
        document.addEventListener('visibilitychange', vis);
        return () => { window.clearInterval(t); document.removeEventListener('visibilitychange', vis); };
    }, [load]);

    if (!data) return <Card><CardHeader title="Activity" /><CardBody className="text-sm text-ink-muted">Loading…</CardBody></Card>;
    const s = data.stats;
    const live = data.people.filter((p) => p.viewing_now);
    const timeline = data.timeline.filter((e) => showFlagged || !e.flagged);
    const hidden = data.timeline.length - data.timeline.filter((e) => !e.flagged).length;

    return (
        <Card data-testid="activity-panel">
            <CardHeader title="Activity" description="Live. Staff and automated opens aren't counted." actions={
                live.length > 0 ? <span className="inline-flex items-center gap-1.5 rounded-full bg-green-100 px-2.5 py-1 text-xs font-semibold text-green-800" data-testid="viewing-now">
                    <Radio className="h-3.5 w-3.5 animate-pulse" /> Viewing now</span> : null
            } />
            <CardBody className="space-y-5">
                <div className="grid grid-cols-2 gap-2" data-testid="activity-stats">
                    <Stat label="Views" value={String(s.opens)} testId="stat-opens" />
                    <Stat label="Time viewed" value={duration(s.seconds_viewed)} testId="stat-time" />
                    <Stat label="Email opens" value={String(s.email_opens)} testId="stat-email-opens" />
                    <Stat label="PDF downloads" value={String(s.pdf_downloads)} testId="stat-pdf" />
                </div>
                {s.top_sections.length > 0 && (
                    <p className="text-xs text-ink-muted">Most read: {s.top_sections.map((t) => `${t.key} (${duration(t.seconds)})`).join(' · ')}</p>
                )}

                {data.decision && <DecisionCard d={data.decision} />}

                {data.people.length > 0 && (
                    <div>
                        <h3 className="mb-2 text-sm font-semibold">People</h3>
                        <ul className="divide-y divide-line rounded-md border border-line" data-testid="activity-people">
                            {data.people.map((p) => (
                                <li key={p.email} className="px-3 py-2 text-sm" data-testid="person-row">
                                    <div className="flex items-center justify-between gap-2">
                                        <span className="min-w-0 truncate font-medium" title={p.email}>{p.name ?? p.email}</span>
                                        <span className="flex shrink-0 items-center gap-1">
                                            {p.role === 'cc' && <Badge className="bg-stone-100 text-stone-600">CC</Badge>}
                                            {p.bounced && <Badge className="bg-red-100 text-red-800">Bounced</Badge>}
                                            {p.viewing_now && <Badge className="bg-green-100 text-green-800">Viewing now</Badge>}
                                        </span>
                                    </div>
                                    <div className="text-xs text-ink-muted">
                                        {p.emails_sent} email{p.emails_sent === 1 ? '' : 's'} · opened {p.email_opens} · {p.opens} view{p.opens === 1 ? '' : 's'} · {duration(p.seconds)}
                                        {!p.viewing_now && p.last_viewed_at && <> · last {dateTime(p.last_viewed_at)}</>}
                                    </div>
                                </li>
                            ))}
                        </ul>
                    </div>
                )}

                <Messages quoteId={quoteId} companyId={companyId} messages={data.messages} canReply={data.can.reply} onChange={load} />

                <div>
                    <h3 className="mb-2 text-sm font-semibold">Timeline</h3>
                    {timeline.length === 0 ? <p className="text-sm text-ink-muted">Nothing yet. Send the quote to start tracking.</p> : (
                        <ol className="space-y-0" data-testid="timeline">
                            {timeline.slice(0, showAll ? undefined : 6).map((e) => {
                                const Icon = e.flagged ? (e.flag_reason === 'Staff member' ? ShieldCheck : Bot) : ICONS[e.kind] ?? Clock;
                                return (
                                    <li key={e.id} className={cn('relative flex gap-3 border-l border-line pb-4 pl-5 last:pb-0', e.flagged && 'opacity-60')} data-testid={`tl-${e.kind}`}>
                                        <span className={cn('absolute -left-3 top-0 flex h-6 w-6 items-center justify-center rounded-full ring-4 ring-surface',
                                            e.kind === 'accept' ? 'bg-green-100 text-green-700' : e.kind === 'decline' || e.kind === 'email_bounced' ? 'bg-red-100 text-red-700' : 'bg-accent-soft text-link')}>
                                            <Icon className="h-3.5 w-3.5" /></span>
                                        <div className="min-w-0 flex-1 text-sm">
                                            <div className="flex flex-wrap items-baseline justify-between gap-x-3">
                                                <span><b className="font-medium">{e.text}</b>{e.who && <span className="text-ink-muted"> · {e.who}</span>}</span>
                                                <time className="text-xs text-ink-muted" dateTime={e.at}>{dateTime(e.at)}</time>
                                            </div>
                                            {e.kind === 'view' && (
                                                <div className="text-xs text-ink-muted">
                                                    {duration(e.seconds ?? 0)} on the page{e.pdf ? ` · downloaded the PDF` : ''}
                                                    {e.sections && e.sections.length > 0 && <> · most time on {e.sections.map((x) => x.key).join(', ')}</>}
                                                </div>
                                            )}
                                            {e.detail && <div className="truncate text-xs text-ink-muted">{e.detail}{e.by ? ` · sent by ${e.by}` : ''}</div>}
                                            {(e.device || e.place || e.ip) && <div className="text-xs text-ink-muted">{[e.device, e.place, e.ip].filter(Boolean).join(' · ')}</div>}
                                            {e.flagged && e.flag_reason && <div className="text-xs italic text-ink-muted">Not counted: {e.flag_reason}</div>}
                                            {e.email_id && <button type="button" className="mt-0.5 text-xs text-link underline" onClick={() => setEmailView(e.email_id!)} data-testid="view-email">View email</button>}
                                        </div>
                                    </li>
                                );
                            })}
                        </ol>
                    )}
                    <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs">
                        {timeline.length > 6 && <button type="button" className="text-link underline" onClick={() => setShowAll(!showAll)} data-testid="timeline-all">{showAll ? 'Show less' : `Show all ${timeline.length}`}</button>}
                        {hidden > 0 && <Checkbox label={`Show ${hidden} hidden (staff / automated)`} checked={showFlagged} onChange={(e) => setShowFlagged(e.target.checked)} className="text-xs" />}
                    </div>
                    {data.can.on_behalf && <Button type="button" size="sm" variant="secondary" className="mt-3 w-full" onClick={() => setBehalf(true)} data-testid="on-behalf"><UserCheck className="h-4 w-4" /> Accept / decline for client</Button>}
                </div>
            </CardBody>
            <EmailViewer quoteId={quoteId} companyId={companyId} id={emailView} onClose={() => setEmailView(null)} />
            <OnBehalfDialog open={behalf} onOpenChange={setBehalf} quoteId={quoteId} companyId={companyId} onDone={load} />
        </Card>
    );
}

function Stat({ label, value, testId }: { label: string; value: string; testId: string }) {
    return (
        <div className="rounded-md border border-line bg-page px-3 py-2.5">
            <div className="text-lg font-semibold tabular-nums" data-testid={testId}>{value}</div>
            <div className="text-xs text-ink-muted">{label}</div>
        </div>
    );
}

function DecisionCard({ d }: { d: Decision }) {
    const ok = d.decision === 'accepted';
    const fp = d.fingerprint ?? {};
    const opts = d.selected_options;
    return (
        <div className={cn('rounded-md border px-4 py-3 text-sm', ok ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50')} data-testid="decision">
            <div className="flex flex-wrap items-center gap-2 font-semibold">
                {ok ? <CheckCircle2 className="h-4 w-4 text-green-700" /> : <XCircle className="h-4 w-4 text-red-700" />}
                {ok ? 'Accepted' : 'Declined'} by {d.signer_name ?? d.signer_email ?? 'client'} · {dateTime(d.at)}
                {d.on_behalf && <Badge className="bg-white text-stone-700">Recorded by {d.on_behalf}</Badge>}
            </div>
            {ok && d.totals && <div className="mt-1">Accepted total: <b className="tabular-nums">{money(d.totals.total_cents, d.totals.currency)}</b> (locked)</div>}
            {d.po_number && <div>PO number: <b>{d.po_number}</b></div>}
            {d.comments && <div className="whitespace-pre-line">Comments: {d.comments}</div>}
            {d.reason && <div className="whitespace-pre-line">Reason: {d.reason}</div>}
            {opts && (opts.optional?.length || opts.choices || opts.quantities?.length) ? (
                <ul className="mt-1 list-disc pl-5 text-xs">
                    {opts.optional?.map((o) => <li key={o.heading}>{o.heading}: {o.selected ? 'included' : 'not included'}</li>)}
                    {opts.choices && Object.entries(opts.choices).map(([g, c]) => <li key={g}>{g}: {c.heading}</li>)}
                    {opts.quantities?.map((q) => <li key={q.heading}>{q.heading}: qty {q.qty}</li>)}
                </ul>
            ) : null}
            {d.signature && (d.signature_type === 'drawn'
                ? <img src={d.signature} alt={`Signature of ${d.signer_name}`} className="mt-2 h-16 rounded bg-white p-1" data-testid="signature-image" />
                : <div className="mt-2 inline-block rounded bg-white px-3 py-1 text-xl" style={{ fontFamily: "'Segoe Script', 'Brush Script MT', cursive" }}>{d.signature}</div>)}
            {Object.keys(fp).length > 0 && (
                <details className="mt-2 text-xs">
                    <summary className="cursor-pointer font-medium">Digital fingerprint</summary>
                    <dl className="mt-1 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5" data-testid="fingerprint">
                        {Object.entries(fp).filter(([, v]) => v !== null && v !== '').map(([k, v]) => (
                            <Fragment key={k}><dt className="text-ink-muted">{k.replace(/_/g, ' ')}</dt><dd className="break-all">{String(v)}</dd></Fragment>
                        ))}
                    </dl>
                </details>
            )}
        </div>
    );
}

function Messages({ quoteId, companyId, messages, canReply, onChange }: { quoteId: number; companyId: number; messages: Msg[]; canReply: boolean; onChange: () => void }) {
    const [replying, setReplying] = useState<number | null>(null);
    const [text, setText] = useState('');
    const [noteType, setNoteType] = useState<'comment' | 'private_note'>('private_note');
    const [note, setNote] = useState('');
    const [error, setError] = useState<string | null>(null);
    const [busy, setBusy] = useState(false);
    const questions = messages.filter((m) => m.type === 'question');
    const others = messages.filter((m) => m.type === 'comment' || m.type === 'private_note');
    const replies = (id: number) => messages.filter((m) => m.parent_id === id);
    const h = { 'X-Company': String(companyId) };

    const post = async (data: Record<string, unknown>, done: () => void) => {
        setBusy(true); setError(null);
        try { await httpForm(`/quotes/${quoteId}/messages`, data, h); done(); onChange(); }
        catch (e) { setError(e instanceof HttpError ? e.body?.message ?? 'Could not save.' : 'Could not save.'); }
        finally { setBusy(false); }
    };
    const toggleNoAnswer = async (id: number) => { await http('POST', `/quotes/${quoteId}/messages/${id}/no-answer`, {}, h); onChange(); };

    return (
        <div className="space-y-4" data-testid="activity-messages">
            {questions.length > 0 && (
                <div>
                    <h3 className="mb-2 text-sm font-semibold">Questions</h3>
                    <div className="space-y-3">
                        {questions.map((q) => (
                            <div key={q.id} id={`question-${q.id}`} className="scroll-mt-24 rounded-md border border-line p-3 text-sm transition-shadow" data-testid="question">
                                <div className="flex flex-wrap items-center justify-between gap-2">
                                    <span><b className="font-medium">{q.author}</b> <span className="text-xs text-ink-muted">{dateTime(q.at)}</span></span>
                                    <Badge className={q.answered_state === 'answered' ? 'bg-green-100 text-green-800' : q.answered_state === 'no_answer_needed' ? 'bg-stone-100 text-stone-600' : 'bg-amber-100 text-amber-900'}>
                                        {q.answered_state === 'answered' ? 'Answered' : q.answered_state === 'no_answer_needed' ? 'No answer needed' : 'Waiting for an answer'}
                                    </Badge>
                                </div>
                                <p className="mt-1 whitespace-pre-line">{q.body}</p>
                                <Files files={q.files} />
                                {replies(q.id).map((r) => (
                                    <div key={r.id} className="ml-4 mt-2 border-l-2 border-accent pl-3"><b className="font-medium">{r.author}</b> <span className="text-xs text-ink-muted">{dateTime(r.at)}</span><p className="whitespace-pre-line">{r.body}</p><Files files={r.files} /></div>
                                ))}
                                {canReply && (replying === q.id ? (
                                    <div className="mt-2 space-y-2">
                                        <Textarea rows={3} aria-label="Your answer" value={text} onChange={(e) => setText(e.target.value)} data-testid="answer-text" />
                                        <div className="flex justify-end gap-2">
                                            <Button type="button" size="sm" variant="ghost" onClick={() => setReplying(null)}>Cancel</Button>
                                            <Button type="button" size="sm" disabled={busy || !text.trim()} data-testid="answer-send"
                                                onClick={() => post({ type: 'answer', body: text, parent_id: q.id }, () => { setText(''); setReplying(null); })}>Send answer</Button>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="mt-2 flex gap-2">
                                        <Button type="button" size="sm" variant="secondary" onClick={() => { setReplying(q.id); setText(''); }} data-testid="answer-open">Answer</Button>
                                        <Button type="button" size="sm" variant="ghost" onClick={() => toggleNoAnswer(q.id)}>{q.answered_state === 'no_answer_needed' ? 'Needs an answer' : 'No answer needed'}</Button>
                                    </div>
                                ))}
                            </div>
                        ))}
                    </div>
                </div>
            )}
            {others.length > 0 && (
                <div className="space-y-2">
                    <h3 className="text-sm font-semibold">Comments &amp; notes</h3>
                    {others.map((m) => (
                        <div key={m.id} className={cn('rounded-md px-3 py-2 text-sm', m.type === 'private_note' ? 'bg-amber-50' : 'bg-accent-soft')}>
                            <div className="flex items-center gap-1.5 text-xs text-ink-muted">{m.type === 'private_note' ? <><Lock className="h-3 w-3" /> Private note</> : 'Comment to client'} · {m.author} · {dateTime(m.at)}</div>
                            <p className="whitespace-pre-line">{m.body}</p>
                        </div>
                    ))}
                </div>
            )}
            {canReply && (
                <div className="space-y-2 rounded-md border border-line p-3">
                    <div className="flex gap-4 text-sm" role="radiogroup" aria-label="Note type">
                        <label className="inline-flex items-center gap-1.5"><input type="radio" checked={noteType === 'private_note'} onChange={() => setNoteType('private_note')} /> Private note (staff only)</label>
                        <label className="inline-flex items-center gap-1.5"><input type="radio" checked={noteType === 'comment'} onChange={() => setNoteType('comment')} /> Comment to client (emailed)</label>
                    </div>
                    <Textarea rows={2} aria-label="Note" value={note} onChange={(e) => setNote(e.target.value)} data-testid="note-text" />
                    {error && <p className="text-sm text-red-700">{error}</p>}
                    <div className="flex justify-end"><Button type="button" size="sm" disabled={busy || !note.trim()} onClick={() => post({ type: noteType, body: note }, () => setNote(''))} data-testid="note-send">{noteType === 'comment' ? 'Send comment' : 'Add note'}</Button></div>
                </div>
            )}
        </div>
    );
}

function Files({ files }: { files: Msg['files'] }) {
    if (!files.length) return null;
    return <div className="mt-1 flex flex-wrap gap-2">{files.map((f) => <a key={f.url} href={f.url} className="inline-flex items-center gap-1 text-xs text-link underline"><Paperclip className="h-3 w-3" />{f.name}</a>)}</div>;
}

function EmailViewer({ quoteId, companyId, id, onClose }: { quoteId: number; companyId: number; id: number | null; onClose: () => void }) {
    const [e, setE] = useState<{ subject: string; from: string; to: string[]; status: string; error: string | null; sent_at: string | null; scheduled_at: string | null; attachments: string[]; html: string } | null>(null);
    useEffect(() => {
        setE(null);
        if (id) http('GET', `/quotes/${quoteId}/emails/${id}`, undefined, { 'X-Company': String(companyId) }).then(setE).catch(() => onClose());
    }, [id, quoteId, companyId, onClose]);
    return (
        <Dialog open={id !== null} onOpenChange={(o) => !o && onClose()} title={e?.subject ?? 'Email'} size="xl" description={e ? `From ${e.from} to ${e.to.join(', ')}` : undefined}>
            {e && (
                <div className="space-y-2" data-testid="email-viewer">
                    <div className="text-xs text-ink-muted">
                        {e.status === 'scheduled' ? `Scheduled for ${dateTime(e.scheduled_at)}` : e.sent_at ? `Sent ${dateTime(e.sent_at)}` : `Status: ${e.status}`}
                        {e.attachments.length > 0 && ` · Attachments: ${e.attachments.join(', ')}`}
                        {e.error && <span className="text-red-700"> · {e.error}</span>}
                    </div>
                    <p className="text-xs text-ink-muted">Links here open the client page without counting as a client view.</p>
                    <iframe title="Sent email" sandbox="allow-popups allow-popups-to-escape-sandbox" srcDoc={e.html.replace('<head>', '<head><base target="_blank">')} className="h-[60vh] w-full rounded border border-line bg-white" />
                </div>
            )}
        </Dialog>
    );
}

function OnBehalfDialog({ open, onOpenChange, quoteId, companyId, onDone }: { open: boolean; onOpenChange: (o: boolean) => void; quoteId: number; companyId: number; onDone: () => void }) {
    const [decision, setDecision] = useState<'accepted' | 'declined'>('accepted');
    const [name, setName] = useState('');
    const [po, setPo] = useState('');
    const [reason, setReason] = useState('');
    const [error, setError] = useState<string | null>(null);
    const submit = async () => {
        setError(null);
        try {
            await http('POST', `/quotes/${quoteId}/decision`, { decision, signer_name: name, po_number: po, reason }, { 'X-Company': String(companyId) });
            onOpenChange(false); onDone(); window.location.reload();
        } catch (e) { setError(e instanceof HttpError ? e.body?.message ?? 'Could not save.' : 'Could not save.'); }
    };
    return (
        <Dialog open={open} onOpenChange={onOpenChange} title="Record the client's decision" description="For when the client accepts or declines by phone or email. It's recorded as done by you.">
            <div className="space-y-3">
                <div className="flex gap-4 text-sm">
                    <label className="inline-flex items-center gap-1.5"><input type="radio" checked={decision === 'accepted'} onChange={() => setDecision('accepted')} /> Accepted</label>
                    <label className="inline-flex items-center gap-1.5"><input type="radio" checked={decision === 'declined'} onChange={() => setDecision('declined')} /> Declined</label>
                </div>
                {decision === 'accepted' ? <>
                    <Field label="Client's name" htmlFor="ob-name"><Input id="ob-name" value={name} onChange={(e) => setName(e.target.value)} /></Field>
                    <Field label="PO number (optional)" htmlFor="ob-po"><Input id="ob-po" value={po} onChange={(e) => setPo(e.target.value)} /></Field>
                </> : <Field label="Reason" htmlFor="ob-reason"><Textarea id="ob-reason" rows={3} value={reason} onChange={(e) => setReason(e.target.value)} /></Field>}
                {error && <p className="text-sm text-red-700">{error}</p>}
                <div className="flex justify-end gap-2">
                    <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>Cancel</Button>
                    <Button type="button" onClick={submit} disabled={decision === 'accepted' ? !name.trim() : !reason.trim()}>Save</Button>
                </div>
            </div>
        </Dialog>
    );
}
