import { useMemo, useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { serializeDraftDataForExport } from '@/components/applicant/applicationDrafts';
import {
  toFullApplicationJson,
  toFullContributionJson,
  toFullReportJson,
} from '@/components/applicant/initiative-draft/draftJsonFullShape';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

export interface DraftJsonPanelProps {
  /** Server case id — used in download filenames. */
  caseId?: string;
  application: Record<string, unknown>;
  report: Record<string, unknown>;
  contribution: Record<string, unknown>;
  draftUpdatedAt?: string;
  className?: string;
}

type TabKey = 'application' | 'report' | 'contribution';

const TAB_LABEL: Record<TabKey, string> = {
  application: 'Đơn đề nghị',
  report: 'Báo cáo mô tả',
  contribution: 'Tỷ lệ đóng góp',
};

function fileBase(caseId: string | undefined): string {
  const raw = (caseId ?? 'draft').replace(/[^a-zA-Z0-9_\-\u00C0-\u024F]+/g, '-').trim();
  return raw || 'draft';
}

function formatJson(data: unknown): string {
  return JSON.stringify(serializeDraftDataForExport(data), null, 2);
}

async function copyText(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    toast.success('Đã sao chép vào bộ nhớ tạm.');
  } catch {
    toast.error('Không thể sao chép.');
  }
}

function downloadJson(filename: string, data: unknown) {
  const body = JSON.stringify(serializeDraftDataForExport(data), null, 2);
  const blob = new Blob([body], { type: 'application/json;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

export function DraftJsonPanel({
  caseId,
  application,
  report,
  contribution,
  draftUpdatedAt,
  className,
}: DraftJsonPanelProps) {
  const [tab, setTab] = useState<TabKey>('application');
  const [open, setOpen] = useState(false);

  const base = useMemo(() => fileBase(caseId), [caseId]);

  const fullTabData = useMemo(
    (): Record<TabKey, Record<string, unknown>> => ({
      application: toFullApplicationJson(application),
      report: toFullReportJson(report),
      contribution: toFullContributionJson(contribution),
    }),
    [application, report, contribution],
  );

  const currentText = useMemo(() => formatJson(fullTabData[tab]), [fullTabData, tab]);

  const bundle = useMemo(
    () => ({
      caseId: caseId ?? null,
      draftUpdatedAt: draftUpdatedAt ?? null,
      exportedAt: new Date().toISOString(),
      application: fullTabData.application,
      report: fullTabData.report,
      contribution: fullTabData.contribution,
    }),
    [caseId, draftUpdatedAt, fullTabData],
  );

  const handleDownloadTab = (key: TabKey) => {
    const name =
      key === 'application'
        ? `${base}-don-de-nghi.json`
        : key === 'report'
          ? `${base}-bao-cao.json`
          : `${base}-dong-gop.json`;
    downloadJson(name, fullTabData[key]);
  };

  const handleDownloadBundle = () => {
    downloadJson(`${base}-draft-bundle.json`, bundle);
  };

  return (
    <Card className={cn('border-dashed', className)}>
      <Collapsible open={open} onOpenChange={setOpen}>
        {/* <CardHeader className="space-y-2 pb-2">
          <div className="flex flex-wrap items-start justify-between gap-2">
            <div>
              <CardTitle className="text-base">Dữ liệu JSON (3 tab)</CardTitle>
              <CardDescription>
                Đầy đủ trường theo 3 biểu mẫu (Đơn, Báo cáo, Đóng góp); giá trị trống hiển thị là{' '}
                <code className="rounded bg-muted px-1 text-xs">null</code>. File PDF minh chứng trong
                Đơn chỉ lưu tên/kích thước (metadata), không gửi nội dung nhị phân trong JSON.
              </CardDescription>
            </div>
            <CollapsibleTrigger asChild>
              <Button type="button" variant="outline" size="sm" className="gap-1 shrink-0">
                {open ? 'Thu gọn' : 'Mở rộng'}
                <ChevronDown
                  className={cn('h-4 w-4 transition-transform', open && 'rotate-180')}
                />
              </Button>
            </CollapsibleTrigger>
          </div>
        </CardHeader> */}
        <CollapsibleContent>
          <CardContent className="space-y-3 pt-0">
            <Tabs value={tab} onValueChange={(v) => setTab(v as TabKey)}>
              <div className="flex flex-wrap items-center justify-between gap-2">
                <TabsList className="h-auto flex-wrap">
                  {(Object.keys(TAB_LABEL) as TabKey[]).map((k) => (
                    <TabsTrigger key={k} value={k} className="text-xs sm:text-sm">
                      {TAB_LABEL[k]}
                    </TabsTrigger>
                  ))}
                </TabsList>
                <div className="flex flex-wrap gap-2">
                  <Button type="button" variant="secondary" size="sm" onClick={() => copyText(currentText)}>
                    Sao chép tab này
                  </Button>
                  <Button type="button" variant="secondary" size="sm" onClick={() => handleDownloadTab(tab)}>
                    Tải .json tab này
                  </Button>
                </div>
              </div>
              <TabsContent value={tab} className="mt-2">
                <ScrollArea className="h-[min(320px,50vh)] rounded-md border bg-muted/30 p-3">
                  <pre className="text-xs font-mono whitespace-pre-wrap break-words text-foreground/90">
                    {currentText}
                  </pre>
                </ScrollArea>
              </TabsContent>
            </Tabs>
            <div className="flex flex-wrap gap-2 pt-1 border-t border-border/60">
              <Button type="button" variant="outline" size="sm" onClick={handleDownloadBundle}>
                Tải một file gộp (bundle)
              </Button>
              <p className="text-xs text-muted-foreground self-center">
                Bundle gồm <code className="rounded bg-muted px-1">application</code>,{' '}
                <code className="rounded bg-muted px-1">report</code>,{' '}
                <code className="rounded bg-muted px-1">contribution</code> và mốc thời gian xuất.
              </p>
            </div>
          </CardContent>
        </CollapsibleContent>
      </Collapsible>
    </Card>
  );
}
