import React, { useState } from 'react';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
  Alert,
  AlertDescription,
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
  AlertTitle,
  Avatar,
  AvatarFallback,
  AvatarImage,
  Badge,
  Button,
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
  Checkbox,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  Input,
  Label,
  PageHeader,
  Progress,
  RadioGroup,
  RadioGroupItem,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Separator,
  Slider,
  StatsCard,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Textarea,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from 'xertica-ui/ui';
import { Header } from 'xertica-ui/layout';
import { useLayout } from 'xertica-ui/hooks';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import {
  Activity,
  DollarSign,
  Mail,
  Search,
  Settings,
  ThumbsUp,
  Users,
} from 'lucide-react';

interface MockUser {
  id: string;
  name: string;
  email: string;
  status: 'active' | 'invited' | 'inactive';
}

const MOCK_USERS: MockUser[] = [
  { id: '1', name: 'Ana Souza', email: 'ana.souza@example.com', status: 'active' },
  { id: '2', name: 'Bruno Lima', email: 'bruno.lima@example.com', status: 'invited' },
  { id: '3', name: 'Carla Dias', email: 'carla.dias@example.com', status: 'active' },
  { id: '4', name: 'Diego Alves', email: 'diego.alves@example.com', status: 'inactive' },
];

/**
 * Template page content — Design System showcase.
 *
 * Curated overview of the most common `xertica-ui/ui` primitives, grouped by
 * category. Replace this with your own page content — keep the `Header` +
 * `useLayout()` wiring below if you want the sidebar-aware layout to keep
 * working.
 */
export function TemplateContent() {
  const { t } = useTranslation();
  const { sidebarExpanded, sidebarWidth } = useLayout();

  const [progress, setProgress] = useState(45);
  const [volume, setVolume] = useState([60]);
  const [tableFilter, setTableFilter] = useState('');

  const filteredUsers = MOCK_USERS.filter(user =>
    `${user.name} ${user.email}`.toLowerCase().includes(tableFilter.toLowerCase())
  );

  const handleFormSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    toast.success(t('templates.forms.submitSuccess'));
  };

  return (
    <div
      style={{
        paddingLeft: sidebarExpanded ? `${sidebarWidth}px` : '80px',
      }}
      className="flex-1 flex flex-col overflow-hidden transition-all duration-300"
    >
      <Header
        showThemeToggle={true}
        showLanguageSelector={true}
        breadcrumbs={[
          { label: t('nav.designSystem'), href: '/home' },
          { label: t('templates.breadcrumb') },
        ]}
        renderLink={(href: string, props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
          <Link to={href} {...props} />
        )}
      />

      <main className="flex-1 overflow-hidden bg-muted">
        <div className="h-full" style={{ overflowY: 'auto', overflowX: 'hidden' }}>
          <div className="p-5 sm:p-4 md:p-6">
            <div className="max-w-6xl mx-auto space-y-8">
              <PageHeader title={t('templates.title')} subtitle={t('templates.subtitle')} />

              {/* Replace this with your own page content — everything below is a Design System showcase */}

              {/* Overview */}
              <section>
                <h3 className="mb-4">{t('templates.sections.overview')}</h3>
                <div className="grid gap-4 md:grid-cols-3">
                  <StatsCard
                    title={t('templates.overview.activeUsers')}
                    value="1,234"
                    icon={<Users className="size-5" />}
                    iconColor="text-primary"
                    iconBg="bg-primary/10"
                    trend={{ value: 12 }}
                  />
                  <StatsCard
                    title={t('templates.overview.revenue')}
                    value="$45.2k"
                    icon={<DollarSign className="size-5" />}
                    iconColor="text-success"
                    iconBg="bg-success/10"
                    trend={{ value: 8 }}
                  />
                  <StatsCard
                    title={t('templates.overview.engagement')}
                    value="3.2%"
                    icon={<Activity className="size-5" />}
                    iconColor="text-info"
                    iconBg="bg-info/10"
                    trend={{ value: -2 }}
                  />
                </div>
              </section>

              <Separator className="my-8" />

              {/* Buttons */}
              <section>
                <h3 className="mb-4">{t('templates.sections.buttons')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.buttons.title')}</CardTitle>
                    <CardDescription>{t('templates.buttons.description')}</CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="space-y-3">
                      <Label>{t('templates.buttons.variants')}</Label>
                      <div className="flex flex-wrap gap-3">
                        <Button variant="default">Default</Button>
                        <Button variant="secondary">Secondary</Button>
                        <Button variant="outline">Outline</Button>
                        <Button variant="ghost">Ghost</Button>
                        <Button variant="link">Link</Button>
                        <Button variant="destructive">Destructive</Button>
                        <Button variant="success">Success</Button>
                        <Button variant="info">Info</Button>
                        <Button variant="warning">Warning</Button>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-3">
                      <Label>{t('templates.buttons.sizes')}</Label>
                      <div className="flex flex-wrap items-center gap-3">
                        <Button size="sm">Small</Button>
                        <Button size="default">Default</Button>
                        <Button size="lg">Large</Button>
                        <Button size="icon" aria-label={t('nav.settings')}>
                          <Settings className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-3">
                      <Label>{t('templates.buttons.withIcons')}</Label>
                      <div className="flex flex-wrap gap-3">
                        <Button>
                          <Mail className="mr-2 h-4 w-4" />
                          {t('templates.buttons.sendEmail')}
                        </Button>
                        <Button variant="outline" loading>
                          {t('templates.buttons.loading')}
                        </Button>
                        <Button disabled>{t('templates.buttons.disabled')}</Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </section>

              <Separator className="my-8" />

              {/* Badges */}
              <section>
                <h3 className="mb-4">{t('templates.sections.badges')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.badges.title')}</CardTitle>
                    <CardDescription>{t('templates.badges.description')}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-3">
                      <Badge variant="default">Default</Badge>
                      <Badge variant="secondary">Secondary</Badge>
                      <Badge variant="outline">Outline</Badge>
                      <Badge variant="destructive">Destructive</Badge>
                      <Badge className="bg-success text-success-foreground">Success</Badge>
                      <Badge className="bg-warning text-warning-foreground">Warning</Badge>
                      <Badge className="bg-info text-info-foreground">Info</Badge>
                    </div>
                  </CardContent>
                </Card>
              </section>

              <Separator className="my-8" />

              {/* Alerts */}
              <section>
                <h3 className="mb-4">{t('templates.sections.alerts')}</h3>
                <div className="grid gap-4 md:grid-cols-2">
                  <Alert variant="info">
                    <AlertTitle>{t('templates.alerts.infoTitle')}</AlertTitle>
                    <AlertDescription>{t('templates.alerts.infoDescription')}</AlertDescription>
                  </Alert>
                  <Alert variant="success">
                    <AlertTitle>{t('templates.alerts.successTitle')}</AlertTitle>
                    <AlertDescription>{t('templates.alerts.successDescription')}</AlertDescription>
                  </Alert>
                  <Alert variant="warning">
                    <AlertTitle>{t('templates.alerts.warningTitle')}</AlertTitle>
                    <AlertDescription>{t('templates.alerts.warningDescription')}</AlertDescription>
                  </Alert>
                  <Alert variant="destructive">
                    <AlertTitle>{t('templates.alerts.errorTitle')}</AlertTitle>
                    <AlertDescription>{t('templates.alerts.errorDescription')}</AlertDescription>
                  </Alert>
                </div>
              </section>

              <Separator className="my-8" />

              {/* Form Elements */}
              <section>
                <h3 className="mb-4">{t('templates.sections.forms')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.forms.title')}</CardTitle>
                    <CardDescription>{t('templates.forms.description')}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <form onSubmit={handleFormSubmit} className="space-y-4">
                      <div className="grid gap-4 md:grid-cols-2">
                        <div className="space-y-2">
                          <Label htmlFor="tpl-name">{t('templates.forms.name')}</Label>
                          <Input id="tpl-name" placeholder={t('templates.forms.namePlaceholder')} />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="tpl-role">{t('templates.forms.role')}</Label>
                          <Select>
                            <SelectTrigger id="tpl-role">
                              <SelectValue placeholder={t('templates.forms.rolePlaceholder')} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="developer">
                                {t('templates.forms.roles.developer')}
                              </SelectItem>
                              <SelectItem value="designer">
                                {t('templates.forms.roles.designer')}
                              </SelectItem>
                              <SelectItem value="manager">
                                {t('templates.forms.roles.manager')}
                              </SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="tpl-bio">{t('templates.forms.bio')}</Label>
                        <Textarea
                          id="tpl-bio"
                          placeholder={t('templates.forms.bioPlaceholder')}
                          rows={3}
                        />
                      </div>

                      <Separator />

                      <div className="space-y-3">
                        <div className="flex items-center space-x-2">
                          <Checkbox id="tpl-newsletter" />
                          <Label htmlFor="tpl-newsletter" className="font-normal">
                            {t('templates.forms.newsletter')}
                          </Label>
                        </div>

                        <div className="flex items-center justify-between">
                          <Label htmlFor="tpl-notifications" className="font-normal">
                            {t('templates.forms.pushNotifications')}
                          </Label>
                          <Switch id="tpl-notifications" defaultChecked />
                        </div>
                      </div>

                      <Separator />

                      <div className="space-y-3">
                        <Label>{t('templates.forms.accountType')}</Label>
                        <RadioGroup defaultValue="personal" aria-label={t('templates.forms.accountType')}>
                          <div className="flex items-center space-x-2">
                            <RadioGroupItem value="personal" id="tpl-personal" />
                            <Label htmlFor="tpl-personal" className="font-normal">
                              {t('templates.forms.accountPersonal')}
                            </Label>
                          </div>
                          <div className="flex items-center space-x-2">
                            <RadioGroupItem value="business" id="tpl-business" />
                            <Label htmlFor="tpl-business" className="font-normal">
                              {t('templates.forms.accountBusiness')}
                            </Label>
                          </div>
                        </RadioGroup>
                      </div>
                    </form>
                  </CardContent>
                  <CardFooter className="flex justify-between">
                    <Button variant="outline">{t('templates.forms.cancel')}</Button>
                    <Button onClick={handleFormSubmit}>{t('templates.forms.submit')}</Button>
                  </CardFooter>
                </Card>
              </section>

              <Separator className="my-8" />

              {/* Data Table */}
              <section>
                <h3 className="mb-4">{t('templates.sections.data')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.data.title')}</CardTitle>
                    <CardDescription>{t('templates.data.description')}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="mb-4 relative">
                      <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                      <Input
                        value={tableFilter}
                        onChange={event => setTableFilter(event.target.value)}
                        placeholder={t('templates.data.searchPlaceholder')}
                        aria-label={t('templates.data.searchPlaceholder')}
                        className="pl-10"
                      />
                    </div>

                    <div className="rounded-[var(--radius-lg)] border border-border overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t('templates.data.columns.name')}</TableHead>
                            <TableHead>{t('templates.data.columns.email')}</TableHead>
                            <TableHead className="text-right">
                              {t('templates.data.columns.status')}
                            </TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {filteredUsers.map(user => (
                            <TableRow key={user.id}>
                              <TableCell>{user.name}</TableCell>
                              <TableCell>{user.email}</TableCell>
                              <TableCell className="text-right">
                                <Badge
                                  variant={
                                    user.status === 'active'
                                      ? 'default'
                                      : user.status === 'invited'
                                        ? 'secondary'
                                        : 'outline'
                                  }
                                >
                                  {t(`templates.data.status.${user.status}`)}
                                </Badge>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </CardContent>
                </Card>
              </section>

              <Separator className="my-8" />

              {/* Dialogs */}
              <section>
                <h3 className="mb-4">{t('templates.sections.dialogs')}</h3>
                <div className="grid gap-4 md:grid-cols-2">
                  <Card>
                    <CardHeader>
                      <CardTitle>{t('templates.dialogs.dialogTitle')}</CardTitle>
                      <CardDescription>{t('templates.dialogs.dialogDescription')}</CardDescription>
                    </CardHeader>
                    <CardContent className="flex justify-center py-6">
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button variant="outline">{t('templates.dialogs.editProfile')}</Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-[425px]">
                          <DialogHeader>
                            <DialogTitle>{t('templates.dialogs.editProfile')}</DialogTitle>
                            <DialogDescription>
                              {t('templates.dialogs.editProfileDescription')}
                            </DialogDescription>
                          </DialogHeader>
                          <div className="grid gap-4 py-4">
                            <div className="space-y-2">
                              <Label htmlFor="tpl-dialog-name">{t('templates.dialogs.name')}</Label>
                              <Input id="tpl-dialog-name" defaultValue="Ana Souza" />
                            </div>
                          </div>
                          <DialogFooter>
                            <Button type="submit">{t('templates.dialogs.update')}</Button>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>{t('templates.dialogs.alertDialogTitle')}</CardTitle>
                      <CardDescription>
                        {t('templates.dialogs.alertDialogDescription')}
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="flex justify-center py-6">
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button variant="destructive">
                            {t('templates.dialogs.deleteAccount')}
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent className="sm:max-w-[425px]">
                          <AlertDialogHeader>
                            <AlertDialogTitle>{t('templates.dialogs.areYouSure')}</AlertDialogTitle>
                            <AlertDialogDescription>
                              {t('templates.dialogs.deleteWarning')}
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>{t('templates.dialogs.cancel')}</AlertDialogCancel>
                            <AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                              {t('templates.dialogs.continue')}
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </CardContent>
                  </Card>
                </div>
              </section>

              <Separator className="my-8" />

              {/* Overlays & Feedback */}
              <section>
                <h3 className="mb-4">{t('templates.sections.overlays')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.overlays.title')}</CardTitle>
                    <CardDescription>{t('templates.overlays.description')}</CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="flex flex-wrap items-center gap-6">
                      <div className="flex items-center gap-3">
                        <Avatar>
                          <AvatarImage src="https://github.com/shadcn.png" alt="Avatar" />
                          <AvatarFallback>AS</AvatarFallback>
                        </Avatar>
                        <span className="text-muted-foreground">{t('templates.overlays.avatarLabel')}</span>
                      </div>

                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button variant="outline" size="icon" aria-label={t('templates.overlays.tooltipLabel')}>
                            <ThumbsUp className="h-4 w-4" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>{t('templates.overlays.tooltipContent')}</TooltipContent>
                      </Tooltip>
                    </div>

                    <Separator />

                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <Label>{t('templates.overlays.progressLabel')}</Label>
                        <span className="text-sm text-muted-foreground">{progress}%</span>
                      </div>
                      <Progress value={progress} className="w-full" />
                      <div className="flex gap-2">
                        <Button size="sm" onClick={() => setProgress(value => Math.max(0, value - 10))}>
                          -10%
                        </Button>
                        <Button size="sm" onClick={() => setProgress(value => Math.min(100, value + 10))}>
                          +10%
                        </Button>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <Label>{t('templates.overlays.sliderLabel')}</Label>
                        <span className="text-sm text-muted-foreground">{volume[0]}%</span>
                      </div>
                      <Slider
                        value={volume}
                        onValueChange={setVolume}
                        min={0}
                        max={100}
                        step={1}
                        className="w-full"
                        aria-label={t('templates.overlays.sliderLabel')}
                      />
                    </div>
                  </CardContent>
                </Card>
              </section>

              <Separator className="my-8" />

              {/* Accordion */}
              <section>
                <h3 className="mb-4">{t('templates.sections.accordion')}</h3>
                <Card>
                  <CardHeader>
                    <CardTitle>{t('templates.accordion.title')}</CardTitle>
                    <CardDescription>{t('templates.accordion.description')}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Accordion type="single" collapsible>
                      <AccordionItem value="item-1">
                        <AccordionTrigger>{t('templates.accordion.q1')}</AccordionTrigger>
                        <AccordionContent>{t('templates.accordion.a1')}</AccordionContent>
                      </AccordionItem>
                      <AccordionItem value="item-2">
                        <AccordionTrigger>{t('templates.accordion.q2')}</AccordionTrigger>
                        <AccordionContent>{t('templates.accordion.a2')}</AccordionContent>
                      </AccordionItem>
                      <AccordionItem value="item-3">
                        <AccordionTrigger>{t('templates.accordion.q3')}</AccordionTrigger>
                        <AccordionContent>{t('templates.accordion.a3')}</AccordionContent>
                      </AccordionItem>
                    </Accordion>
                  </CardContent>
                </Card>
              </section>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
