import { ReactNode } from 'react';
import { Head } from '@inertiajs/react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import AdminLayout from '@/layouts/AdminLayout';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ExternalLink, Palette, BookOpen, Newspaper, Star, Eye, Layout, Navigation, Settings, Plus } from 'lucide-react';
import CompanyBrandingPanel from '@/components/admin/CompanyBrandingPanel';
import CompanyFeaturedCoursesTab from '@/components/admin/company-detail/CompanyFeaturedCoursesTab';
import CompanyBlogTab from '@/components/admin/company-detail/CompanyBlogTab';
import CompanyTestimonialsTab from '@/components/admin/company-detail/CompanyTestimonialsTab';
import { toast } from 'sonner';

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const LocktelCMSPage = () => {
  const queryClient = useQueryClient();

  // Find the company with branding subdomain = locktel-academy, or by name
  const { data: locktelCompany, isLoading } = useQuery<any>({
    queryKey: ['locktel-company'],
    queryFn: async () => {
      const res = await fetch('/api/admin/locktel-cms/company');
      if (!res.ok) return null;
      const data = await res.json().catch(() => null);
      return data || null;
    },
  });

  // Auto-create Locktel Academy company if not found
  const createCompanyMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch('/api/admin/locktel-cms/company', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          name: 'Locktel Academy',
          company_type: 'training_provider',
          status: 'approved',
          contact_email: 'info@locktelacademy.co.uk',
          branding: {
            subdomain: 'locktel-academy',
            is_active: true,
            tagline: 'From theory to the field',
            primary_color: '#DC2626',
            secondary_color: '#1E40AF',
            background_color: '#0F172A',
            font_color: '#FFFFFF',
            card_color: '#1E293B',
            card_font_color: '#F1F5F9',
          },
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || 'Failed to create');
      }
      return res.json();
    },
    onSuccess: () => {
      toast.success('Locktel Academy company and branding created!');
      queryClient.invalidateQueries({ queryKey: ['locktel-company'] });
    },
    onError: (error: any) => {
      toast.error('Failed to create: ' + error.message);
    },
  });

  if (isLoading) {
    return (
      <>
        <Head title="Locktel Academy CMS" />
        <div className="flex items-center justify-center py-20">
          <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full" />
        </div>
      </>
    );
  }

  if (!locktelCompany) {
    return (
      <>
        <Head title="Locktel Academy CMS" />
        <div className="max-w-2xl">
          <h1 className="text-2xl font-bold text-foreground mb-4">Locktel Academy CMS</h1>
          <Card>
            <CardContent className="p-6">
              <p className="text-muted-foreground mb-4">
                No Locktel Academy company found. Click below to auto-create the company with default branding.
              </p>
              <Button
                onClick={() => createCompanyMutation.mutate()}
                disabled={createCompanyMutation.isPending}
                className="gap-2"
              >
                <Plus className="h-4 w-4" />
                {createCompanyMutation.isPending ? 'Creating...' : 'Create Locktel Academy'}
              </Button>
            </CardContent>
          </Card>
        </div>
      </>
    );
  }

  const previewUrl = `${window.location.origin}/?tenant=locktel-academy`;

  return (
    <>
      <Head title="Locktel Academy CMS" />
      <div>
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-foreground">Locktel Academy CMS</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Manage the dedicated Locktel Academy frontend — branding, courses, content, and testimonials.
            </p>
          </div>
          <div className="flex items-center gap-3">
            <Badge variant="outline" className="capitalize">{locktelCompany.status}</Badge>
            <a href={previewUrl} target="_blank" rel="noopener noreferrer">
              <Button variant="outline" size="sm" className="gap-1.5">
                <Eye className="h-4 w-4" /> Preview Site
                <ExternalLink className="h-3 w-3" />
              </Button>
            </a>
          </div>
        </div>

        <Tabs defaultValue="branding" className="space-y-6">
          <TabsList className="flex-wrap">
            <TabsTrigger value="branding" className="gap-1.5">
              <Palette className="h-4 w-4" /> Branding & Theme
            </TabsTrigger>
            <TabsTrigger value="homepage" className="gap-1.5">
              <Layout className="h-4 w-4" /> Homepage Content
            </TabsTrigger>
            <TabsTrigger value="navigation" className="gap-1.5">
              <Navigation className="h-4 w-4" /> Navigation
            </TabsTrigger>
            <TabsTrigger value="courses" className="gap-1.5">
              <BookOpen className="h-4 w-4" /> Featured Courses
            </TabsTrigger>
            <TabsTrigger value="blog" className="gap-1.5">
              <Newspaper className="h-4 w-4" /> Blog / News
            </TabsTrigger>
            <TabsTrigger value="testimonials" className="gap-1.5">
              <Star className="h-4 w-4" /> Testimonials
            </TabsTrigger>
            <TabsTrigger value="settings" className="gap-1.5">
              <Settings className="h-4 w-4" /> Domain Settings
            </TabsTrigger>
          </TabsList>

          <TabsContent value="branding">
            <CompanyBrandingPanel companyId={locktelCompany.id} companyName={locktelCompany.name} />
          </TabsContent>

          <TabsContent value="homepage">
            <HomepageContentTab />
          </TabsContent>

          <TabsContent value="navigation">
            <NavigationTab />
          </TabsContent>

          <TabsContent value="courses">
            <CompanyFeaturedCoursesTab companyId={locktelCompany.id} />
          </TabsContent>

          <TabsContent value="blog">
            <CompanyBlogTab companyId={locktelCompany.id} />
          </TabsContent>

          <TabsContent value="testimonials">
            <CompanyTestimonialsTab companyId={locktelCompany.id} />
          </TabsContent>

          <TabsContent value="settings">
            <DomainSettingsTab />
          </TabsContent>
        </Tabs>
      </div>
    </>
  );
};

const HomepageContentTab = () => (
  <div className="space-y-6">
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Hero Section</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <p className="text-sm text-muted-foreground">
          The hero section uses the hero image/video and tagline from the Branding & Theme tab.
          Stats shown are: 50+ Classroom Courses, 100+ E-Learning Modules, 10k+ Delegates Trained.
        </p>
        <div className="grid sm:grid-cols-3 gap-4">
          {['50+ Classroom Courses', '100+ E-Learning Modules', '10k+ Delegates Trained'].map((stat) => (
            <div key={stat} className="border border-border rounded-md p-3 text-center">
              <p className="text-sm font-medium text-foreground">{stat}</p>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>

    <Card>
      <CardHeader>
        <CardTitle className="text-lg">About Introduction</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-sm text-muted-foreground mb-2">
          This section appears below the hero and provides an overview of Locktel Academy's offerings.
          Content is currently hardcoded — edit the LocktelHomePage component to customise.
        </p>
      </CardContent>
    </Card>

    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Training Sections</CardTitle>
      </CardHeader>
      <CardContent className="space-y-3">
        <p className="text-sm text-muted-foreground">Two side-by-side sections showcasing key training areas:</p>
        <div className="grid sm:grid-cols-2 gap-4">
          <div className="border border-border rounded-md p-4">
            <h4 className="font-medium text-foreground mb-1">Smart Awards Training</h4>
            <p className="text-xs text-muted-foreground">Fibre optics, telecoms, NOPS card</p>
          </div>
          <div className="border border-border rounded-md p-4">
            <h4 className="font-medium text-foreground mb-1">CABWI NRSWA Training</h4>
            <p className="text-xs text-muted-foreground">Street works, excavation, SWQR card</p>
          </div>
        </div>
      </CardContent>
    </Card>

    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Why Choose Us — 4 Pillars</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { title: 'Cutting-Edge Curriculum', desc: 'Industry expert developed programs' },
            { title: 'Hands-On Learning', desc: 'Real-world equipment and simulations' },
            { title: 'Expert Instructors', desc: 'Seasoned industry professionals' },
            { title: 'Flexible Options', desc: 'On-site, weekend, modular courses' },
          ].map(({ title, desc }) => (
            <div key={title} className="border border-border rounded-md p-3">
              <p className="text-sm font-medium text-foreground">{title}</p>
              <p className="text-xs text-muted-foreground">{desc}</p>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  </div>
);

const NavigationTab = () => (
  <div className="space-y-6">
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Main Navigation Structure</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-sm text-muted-foreground mb-4">
          The Locktel Academy navigation includes dropdown menus matching the live site structure.
          Navigation items are currently configured in code — future updates will make these editable here.
        </p>
        <div className="space-y-3">
          {[
            { label: 'Home', type: 'link', href: '/' },
            { label: 'Training Courses', type: 'dropdown', items: 'All Courses, Plant Machinery, Traffic Management, Health & Safety' },
            { label: 'Smart Awards', type: 'dropdown', items: 'All Smart Awards, Fibre Optics, Telecoms Safety' },
            { label: 'NRSWA Courses', type: 'dropdown', items: 'All NRSWA, Operative, Supervisor' },
            { label: 'E-Learning', type: 'link', href: '/courses?cat=e-learning' },
            { label: 'About', type: 'link', href: '/about' },
            { label: 'Contact', type: 'link', href: '/contact' },
          ].map((item) => (
            <div key={item.label} className="flex items-center justify-between border border-border rounded-md p-3">
              <div>
                <p className="text-sm font-medium text-foreground">{item.label}</p>
                {item.type === 'dropdown' && (
                  <p className="text-xs text-muted-foreground mt-0.5">Dropdown: {item.items}</p>
                )}
              </div>
              <Badge variant="secondary" className="text-xs">{item.type}</Badge>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>

    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Footer Links</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-sm text-muted-foreground mb-3">
          The footer includes Quick Links, Policy Pages (11 policies), Contact Details, and a Newsletter signup form.
        </p>
        <div className="grid sm:grid-cols-2 gap-4">
          <div className="border border-border rounded-md p-3">
            <p className="text-sm font-medium text-foreground mb-1">Quick Links</p>
            <p className="text-xs text-muted-foreground">Home, Courses, About Us, Contact, FAQs</p>
          </div>
          <div className="border border-border rounded-md p-3">
            <p className="text-sm font-medium text-foreground mb-1">Policy Pages</p>
            <p className="text-xs text-muted-foreground">11 policy links (Privacy, H&S, Equality, etc.)</p>
          </div>
        </div>
      </CardContent>
    </Card>
  </div>
);

const DomainSettingsTab = () => (
  <div className="space-y-6">
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Domain Configuration</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <p className="text-sm text-muted-foreground">
          The Locktel Academy frontend can be served from its own domain. The domain-to-tenant mapping
          is configured in the application code and will activate when domains are connected via Project Settings → Domains.
        </p>
        <div className="space-y-3">
          <div className="border border-border rounded-md p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-foreground">locktelacademy.co.uk</p>
                <p className="text-xs text-muted-foreground">Maps to → Locktel Academy frontend</p>
              </div>
              <Badge variant="outline">Configured</Badge>
            </div>
          </div>
          <div className="border border-border rounded-md p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-foreground">utilitytrainingcentre.co.uk</p>
                <p className="text-xs text-muted-foreground">Maps to → UTC Marketplace</p>
              </div>
              <Badge variant="outline">Configured</Badge>
            </div>
          </div>
          <div className="border border-border rounded-md p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-foreground">yuta.utilitytrainingcentre.co.uk</p>
                <p className="text-xs text-muted-foreground">Maps to → YUTA tenant (generic white-label)</p>
              </div>
              <Badge variant="outline">Planned</Badge>
            </div>
          </div>
        </div>
        <div className="bg-muted/50 rounded-md p-4 mt-4">
          <p className="text-sm text-muted-foreground">
            <strong>Preview testing:</strong> Use <code className="text-xs bg-muted px-1 py-0.5 rounded">?tenant=locktel-academy</code> query parameter
            to preview the Locktel frontend without connecting a domain.
          </p>
        </div>
      </CardContent>
    </Card>
  </div>
);

LocktelCMSPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default LocktelCMSPage;
