'use client';

import { ArrowLeft, ArrowRight, Loader2, Sparkles } from 'lucide-react';
import { useRouter } from 'next/navigation';
import * as React from 'react';
import { REPORT_TYPES } from '@/components/reports/report-type-badge';
import { Button } from '@/components/ui/button';
import { Link } from '@/i18n/navigation';
import { useGenerateReport } from '@/lib/hooks/use-reports';
import type { ReportType } from '@/lib/reports-api';

type Step = 'type' | 'params' | 'confirm';

const PARAM_FIELDS: Record<ReportType, Array<{ key: string; label: string; placeholder: string; required: boolean }>> = {
  RESIDENTIAL_MARKET: [
    { key: 'city', label: 'Thành phố', placeholder: 'Hồ Chí Minh', required: true },
    { key: 'period', label: 'Kỳ báo cáo', placeholder: '2026-Q1', required: true },
  ],
  INDUSTRIAL_MARKET: [
    { key: 'province', label: 'Tỉnh/TP', placeholder: 'Bình Dương', required: true },
  ],
  DISTRICT_ANALYSIS: [
    { key: 'city', label: 'Thành phố', placeholder: 'Hồ Chí Minh', required: true },
    { key: 'district', label: 'Quận/Huyện', placeholder: 'Quận 2', required: true },
  ],
  INVESTMENT_FEASIBILITY: [
    { key: 'city', label: 'Thành phố', placeholder: 'Hồ Chí Minh', required: true },
    { key: 'propertyType', label: 'Loại BĐS', placeholder: 'APARTMENT', required: true },
  ],
  INDUSTRIAL_LOCATION: [
    { key: 'province', label: 'Tỉnh', placeholder: 'Bình Dương', required: true },
  ],
  PROPERTY_VALUATION: [
    { key: 'propertyId', label: 'ID Bất động sản', placeholder: 'clx...', required: true },
  ],
  PORTFOLIO: [
    { key: 'city', label: 'Thành phố', placeholder: 'Hồ Chí Minh', required: false },
  ],
};

export default function NewReportPage() {
  const router = useRouter();
  const { mutateAsync: trigger, isPending: isMutating } = useGenerateReport();

  const [step, setStep] = React.useState<Step>('type');
  const [selectedType, setSelectedType] = React.useState<ReportType | null>(null);
  const [title, setTitle] = React.useState('');
  const [params, setParams] = React.useState<Record<string, string>>({});

  const typeInfo = selectedType ? REPORT_TYPES.find((t) => t.value === selectedType) : null;
  const paramFields = selectedType ? PARAM_FIELDS[selectedType] : [];

  const handleSelectType = (type: ReportType) => {
    setSelectedType(type);
    setParams({});
    const label = REPORT_TYPES.find((t) => t.value === type)?.label ?? type;
    setTitle(`Báo cáo ${label}`);
    setStep('params');
  };

  const handleSubmit = async () => {
    if (!selectedType) return;
    const result = await trigger({
      type: selectedType,
      title,
      params,
    });
    if (result?.reportId) {
      router.push(`/dashboard/reports/${result.reportId}`);
    }
  };

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Link href="/dashboard/reports">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="h-4 w-4" />
          </Button>
        </Link>
        <div>
          <h1 className="text-xl font-bold">Tạo báo cáo mới</h1>
          <p className="text-sm text-muted-foreground">
            {step === 'type' && 'Bước 1: Chọn loại báo cáo'}
            {step === 'params' && 'Bước 2: Nhập thông tin'}
            {step === 'confirm' && 'Bước 3: Xác nhận'}
          </p>
        </div>
      </div>

      {/* Step 1: Select type */}
      {step === 'type' && (
        <div className="grid gap-3 sm:grid-cols-2">
          {REPORT_TYPES.map((rt) => (
            <button
              key={rt.value}
              type="button"
              className="flex items-center gap-3 rounded-lg border p-4 text-left transition-colors hover:border-primary hover:bg-primary/5"
              onClick={() => handleSelectType(rt.value)}
            >
              <rt.icon className="h-8 w-8 text-primary" />
              <div>
                <p className="font-medium">{rt.label}</p>
                <p className="text-xs text-muted-foreground">Báo cáo {rt.label.toLowerCase()}</p>
              </div>
            </button>
          ))}
        </div>
      )}

      {/* Step 2: Parameters */}
      {step === 'params' && selectedType && (
        <div className="space-y-4 rounded-lg border p-6">
          <div>
            <label className="mb-1 block text-sm font-medium">Tiêu đề báo cáo</label>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full rounded-md border px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>

          {paramFields.map((field) => (
            <div key={field.key}>
              <label className="mb-1 block text-sm font-medium">
                {field.label}
                {field.required && <span className="text-destructive"> *</span>}
              </label>
              <input
                type="text"
                placeholder={field.placeholder}
                value={params[field.key] ?? ''}
                onChange={(e) => setParams({ ...params, [field.key]: e.target.value })}
                className="w-full rounded-md border px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
              />
            </div>
          ))}

          <div className="flex justify-between pt-2">
            <Button variant="outline" onClick={() => setStep('type')}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Quay lại
            </Button>
            <Button onClick={() => setStep('confirm')}>
              Tiếp theo
              <ArrowRight className="ml-2 h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Step 3: Confirm */}
      {step === 'confirm' && selectedType && (
        <div className="space-y-4 rounded-lg border p-6">
          <h3 className="font-semibold">Xác nhận tạo báo cáo</h3>

          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">Loại báo cáo:</span>
              <span className="font-medium">{typeInfo?.label}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Tiêu đề:</span>
              <span className="font-medium">{title}</span>
            </div>
            {Object.entries(params)
              .filter(([, v]) => v)
              .map(([key, value]) => (
                <div key={key} className="flex justify-between">
                  <span className="text-muted-foreground">{key}:</span>
                  <span className="font-medium">{value}</span>
                </div>
              ))}
          </div>

          <div className="flex justify-between pt-2">
            <Button variant="outline" onClick={() => setStep('params')}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Quay lại
            </Button>
            <Button onClick={handleSubmit} disabled={isMutating}>
              {isMutating ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Đang tạo...
                </>
              ) : (
                <>
                  <Sparkles className="mr-2 h-4 w-4" />
                  Tạo báo cáo
                </>
              )}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
