'use client';

import { useMutation } from '@tanstack/react-query';
import { Database, TestTube, Trash2, RefreshCw } from 'lucide-react';

import { settingsApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';

export default function SettingsPage() {
  const seedLookupsMutation = useMutation({
    mutationFn: settingsApi.seedLookups,
    onSuccess: (data) => {
      toast.success(data.message);
    },
    onError: () => {
      toast.error('Failed to seed lookup data');
    },
  });

  const seedTestDataMutation = useMutation({
    mutationFn: settingsApi.seedTestData,
    onSuccess: (data) => {
      toast.success(data.message);
    },
    onError: () => {
      toast.error('Failed to seed test data');
    },
  });

  const clearAllDataMutation = useMutation({
    mutationFn: settingsApi.clearAllData,
    onSuccess: (data) => {
      toast.success(`${data.message} (${data.users_deleted} users deleted, ${data.preserved_users} superadmin accounts preserved)`);
    },
    onError: () => {
      toast.error('Failed to clear data');
    },
  });

  const clearStuckJobsMutation = useMutation({
    mutationFn: settingsApi.clearStuckJobs,
    onSuccess: (data) => {
      if (data.keys_deleted > 0) {
        toast.success(`${data.message} (${data.keys_deleted} keys cleared)`);
      } else {
        toast.info('No stuck jobs found');
      }
    },
    onError: () => {
      toast.error('Failed to clear stuck jobs');
    },
  });

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Settings</h1>
        <p className="text-muted-foreground">
          Manage system settings and seed data
        </p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Seed Lookup Data */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Database className="h-5 w-5" />
              Seed Lookup Data
            </CardTitle>
            <CardDescription>
              Populate or refresh static lookup tables and task templates
            </CardDescription>
          </CardHeader>
          <CardContent>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="outline"
                  disabled={seedLookupsMutation.isPending}
                >
                  {seedLookupsMutation.isPending ? 'Seeding...' : 'Seed Lookup Data'}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Seed Lookup Data?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This will insert or update all lookup tables including:
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Residence types</li>
                      <li>Task categories, priorities, frequencies</li>
                      <li>Contractor specialties</li>
                      <li>Subscription tiers and feature benefits</li>
                      <li><strong>Task templates (60+ predefined tasks)</strong></li>
                    </ul>
                    Existing data will be preserved or updated.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction onClick={() => seedLookupsMutation.mutate()}>
                    Seed Data
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </CardContent>
        </Card>

        {/* Seed Test Data */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TestTube className="h-5 w-5" />
              Seed Test Data
            </CardTitle>
            <CardDescription>
              Populate the database with sample users, residences, and tasks for testing
            </CardDescription>
          </CardHeader>
          <CardContent>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="outline"
                  disabled={seedTestDataMutation.isPending}
                >
                  {seedTestDataMutation.isPending ? 'Seeding...' : 'Seed Test Data'}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Seed Test Data?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This will create sample data for testing including:
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Test users</li>
                      <li>Sample residences</li>
                      <li>Example tasks and completions</li>
                    </ul>
                    <strong className="text-destructive block mt-2">
                      Warning: This should only be used in development/testing environments.
                    </strong>
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => seedTestDataMutation.mutate()}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    Seed Test Data
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </CardContent>
        </Card>

        {/* Clear Stuck Jobs */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <RefreshCw className="h-5 w-5" />
              Clear Stuck Jobs
            </CardTitle>
            <CardDescription>
              Clear stuck or failed background worker jobs from Redis
            </CardDescription>
          </CardHeader>
          <CardContent>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="outline"
                  disabled={clearStuckJobsMutation.isPending}
                >
                  {clearStuckJobsMutation.isPending ? 'Clearing...' : 'Clear Stuck Jobs'}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Clear Stuck Jobs?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This will clear stuck/failed worker jobs from Redis including:
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Jobs in the retry queue</li>
                      <li>Archived/dead letter jobs</li>
                      <li>Orphaned task metadata</li>
                    </ul>
                    <span className="block mt-2">
                      This is safe to run and can fix issues with notifications not running at expected times.
                    </span>
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction onClick={() => clearStuckJobsMutation.mutate()}>
                    Clear Stuck Jobs
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </CardContent>
        </Card>

        {/* Clear All Data */}
        <Card className="border-destructive">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <Trash2 className="h-5 w-5" />
              Clear All Data
            </CardTitle>
            <CardDescription>
              Delete all data from the database except superadmin accounts and lookup tables
            </CardDescription>
          </CardHeader>
          <CardContent>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="destructive"
                  disabled={clearAllDataMutation.isPending}
                >
                  {clearAllDataMutation.isPending ? 'Clearing...' : 'Clear All Data'}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Clear All Data?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This will permanently delete:
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>All regular users (non-superadmin)</li>
                      <li>All residences</li>
                      <li>All tasks and completions</li>
                      <li>All contractors and documents</li>
                      <li>All notifications and devices</li>
                    </ul>
                    <strong className="text-destructive block mt-2">
                      Superadmin accounts and lookup tables will be preserved.
                    </strong>
                    <strong className="text-destructive block mt-2">
                      THIS ACTION CANNOT BE UNDONE!
                    </strong>
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => clearAllDataMutation.mutate()}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    Yes, Clear All Data
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
