import { FileText, Sparkles } from 'lucide-react';

import { useEffect, useState } from 'react';

import { Head, useForm } from '@inertiajs/react';


import SiteNav from '@/Components/Navigation/SiteNav';
import ReportFilters from '@/Components/Reports/ReportFilters';
import ReportSectionSelector from '@/Components/Reports/ReportSectionSelector';
import TemplateCard from '@/Components/Reports/TemplateCard';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent, trackProductEvent } from '@/lib/analytics';
import { REPORT_BUILDER_OPENED, REPORT_GENERATED } from '@/lib/event-catalog';
import type { SiteBasic } from '@/types';

interface ReportTemplate {
  id: number;
  name: string;
  description: string;
  sections: Record<string, boolean>;
  filters: {
    date_start?: string;
    date_end?: string;
    comparison_start?: string;
    comparison_end?: string;
    device?: string;
    country?: string;
  };
  is_system: boolean;
}

interface Props {
  site: SiteBasic;
  templates: ReportTemplate[];
}

interface FormData {
  name: string;
  template_id: number | null;
  sections: string[];
  filters: {
    date_start: string;
    date_end: string;
    comparison_start: string;
    comparison_end: string;
    device: string;
    country: string;
  };
}

export default function Builder({ site, templates }: Props) {
  const [selectedTemplateId, setSelectedTemplateId] = useState<number | null>(null);

  useEffect(() => {
    trackProductEvent(REPORT_BUILDER_OPENED, { site_id: String(site.id) });
  }, [site.id]);

  const { data, setData, post, processing, errors } = useForm<FormData>({
    name: '',
    template_id: null,
    sections: [],
    filters: {
      date_start: '',
      date_end: '',
      comparison_start: '',
      comparison_end: '',
      device: '',
      country: '',
    },
  });

  const handleTemplateSelect = (template: ReportTemplate) => {
    setSelectedTemplateId(template.id);
    setData({
      name: template.name,
      template_id: template.id,
      sections: Object.keys(template.sections).filter((key) => template.sections[key]),
      filters: {
        date_start: template.filters.date_start ?? '',
        date_end: template.filters.date_end ?? '',
        comparison_start: template.filters.comparison_start ?? '',
        comparison_end: template.filters.comparison_end ?? '',
        device: template.filters.device ?? '',
        country: template.filters.country ?? '',
      },
    });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    trackEvent(REPORT_GENERATED, { site_id: String(site.id) });
    post(route('sites.reports.store', site.id));
  };

  return (
    <DashboardLayout>
      <Head title={`Create Report - ${site.name}`} />

      <div className="space-y-6">
        <SiteNav siteId={site.id} />

        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Create Report</h1>
            <p className="mt-2 text-muted-foreground">
              Build a custom report or start with a template
            </p>
          </div>
        </div>

        {/* Template Selection */}
        <div>
          <h2 className="mb-4 text-xl font-semibold">Start with a Template</h2>
          <div className="grid gap-4 md:grid-cols-3">
            {templates.map((template) => (
              <TemplateCard
                key={template.id}
                template={template}
                isSelected={selectedTemplateId === template.id}
                onSelect={() => handleTemplateSelect(template)}
              />
            ))}
          </div>
        </div>

        {/* Custom Report Builder */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              Report Configuration
            </CardTitle>
            <CardDescription>Customize your report settings, sections, and filters</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Report Name */}
              <div className="space-y-2">
                <Label htmlFor="name">Report Name *</Label>
                <Input
                  id="name"
                  type="text"
                  placeholder="e.g., Monthly SEO Performance Report"
                  value={data.name}
                  onChange={(e) => setData('name', e.target.value)}
                  className={errors.name ? 'border-destructive' : ''}
                />
                {errors.name && <p className="text-sm text-destructive">{errors.name}</p>}
              </div>

              {/* Section Selector */}
              <div className="space-y-2">
                <Label>Report Sections *</Label>
                <ReportSectionSelector
                  selectedSections={data.sections}
                  onChange={(sections) => setData('sections', sections)}
                  error={errors.sections}
                />
              </div>

              {/* Filters */}
              <div className="space-y-2">
                <Label>Filters & Date Range</Label>
                <ReportFilters
                  filters={data.filters}
                  onChange={(filters) => setData('filters', filters)}
                  errors={errors}
                />
              </div>

              {/* Submit */}
              <div className="flex items-center gap-3 border-t pt-6">
                <LoadingButton
                  type="submit"
                  loading={processing}
                  disabled={data.sections.length === 0}
                  loadingText="Building report (~30 seconds)..."
                  className="gap-2"
                >
                  <Sparkles className="h-4 w-4" />
                  Generate Report
                </LoadingButton>
                {data.sections.length === 0 && (
                  <p className="text-sm text-muted-foreground">
                    Select at least one section to continue
                  </p>
                )}
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
