import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Plus, Edit2, Trash2, GripVertical, ToggleLeft, ToggleRight, Save, X, Type, Hash, Calendar, ToggleRight as Toggle, List } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import type { Database } from '@/integrations/supabase/types';

type CustomField = Database['public']['Tables']['custom_fields']['Row'];
type CustomFieldType = Database['public']['Enums']['custom_field_type'];

const fieldTypeIcons: Record<CustomFieldType, React.ReactNode> = {
  text: <Type className="h-4 w-4" />,
  number: <Hash className="h-4 w-4" />,
  date: <Calendar className="h-4 w-4" />,
  boolean: <Toggle className="h-4 w-4" />,
  select: <List className="h-4 w-4" />,
};

const fieldTypeLabels: Record<CustomFieldType, string> = {
  text: 'Text',
  number: 'Number',
  date: 'Date',
  boolean: 'Yes/No',
  select: 'Dropdown',
};

export default function CustomFieldsSettings() {
  const [fields, setFields] = useState<CustomField[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingField, setEditingField] = useState<CustomField | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    label: '',
    field_type: 'text' as CustomFieldType,
    options: '',
    is_required: false,
    is_active: true,
  });
  const { toast } = useToast();

  useEffect(() => {
    fetchFields();
  }, []);

  const fetchFields = async () => {
    const { data, error } = await supabase
      .from('custom_fields')
      .select('*')
      .eq('entity_type', 'contact')
      .order('sort_order');

    if (error) {
      toast({
        title: 'Error',
        description: 'Failed to load custom fields',
        variant: 'destructive',
      });
    } else {
      setFields(data || []);
    }
    setIsLoading(false);
  };

  const openCreateDialog = () => {
    setEditingField(null);
    setFormData({
      name: '',
      label: '',
      field_type: 'text',
      options: '',
      is_required: false,
      is_active: true,
    });
    setIsDialogOpen(true);
  };

  const openEditDialog = (field: CustomField) => {
    setEditingField(field);
    setFormData({
      name: field.name,
      label: field.label,
      field_type: field.field_type,
      options: Array.isArray(field.options) ? (field.options as string[]).join('\n') : '',
      is_required: field.is_required,
      is_active: field.is_active,
    });
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    if (!formData.name || !formData.label) {
      toast({
        title: 'Validation error',
        description: 'Name and label are required',
        variant: 'destructive',
      });
      return;
    }

    const fieldData = {
      name: formData.name.toLowerCase().replace(/\s+/g, '_'),
      label: formData.label,
      field_type: formData.field_type,
      options: formData.field_type === 'select' 
        ? formData.options.split('\n').filter(o => o.trim()) 
        : null,
      is_required: formData.is_required,
      is_active: formData.is_active,
      entity_type: 'contact',
      sort_order: editingField ? editingField.sort_order : fields.length,
    };

    if (editingField) {
      const { error } = await supabase
        .from('custom_fields')
        .update(fieldData)
        .eq('id', editingField.id);

      if (error) {
        toast({ title: 'Error', description: 'Failed to update field', variant: 'destructive' });
      } else {
        toast({ title: 'Success', description: 'Field updated successfully' });
        fetchFields();
      }
    } else {
      const { error } = await supabase
        .from('custom_fields')
        .insert(fieldData);

      if (error) {
        toast({ title: 'Error', description: 'Failed to create field', variant: 'destructive' });
      } else {
        toast({ title: 'Success', description: 'Field created successfully' });
        fetchFields();
      }
    }

    setIsDialogOpen(false);
  };

  const handleDelete = async (field: CustomField) => {
    const { error } = await supabase
      .from('custom_fields')
      .delete()
      .eq('id', field.id);

    if (error) {
      toast({ title: 'Error', description: 'Failed to delete field', variant: 'destructive' });
    } else {
      toast({ title: 'Success', description: 'Field deleted successfully' });
      fetchFields();
    }
  };

  const toggleActive = async (field: CustomField) => {
    const { error } = await supabase
      .from('custom_fields')
      .update({ is_active: !field.is_active })
      .eq('id', field.id);

    if (error) {
      toast({ title: 'Error', description: 'Failed to update field', variant: 'destructive' });
    } else {
      fetchFields();
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 flex items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold">Custom Fields</h1>
            <p className="text-muted-foreground mt-1">
              Define additional fields for your contacts
            </p>
          </div>
          <Button onClick={openCreateDialog} className="gap-2">
            <Plus className="h-4 w-4" />
            Add Field
          </Button>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Contact Fields</CardTitle>
            <CardDescription>
              These fields will appear on all contact records
            </CardDescription>
          </CardHeader>
          <CardContent>
            {fields.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <List className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No custom fields defined yet</p>
                <p className="text-sm mt-1">Create your first custom field to get started</p>
              </div>
            ) : (
              <div className="space-y-2">
                <AnimatePresence>
                  {fields.map((field) => (
                    <motion.div
                      key={field.id}
                      layout
                      initial={{ opacity: 0, y: -10 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -10 }}
                      className={`flex items-center gap-4 p-4 rounded-lg border ${
                        field.is_active ? 'bg-card' : 'bg-muted/50 opacity-60'
                      }`}
                    >
                      <GripVertical className="h-5 w-5 text-muted-foreground cursor-grab" />
                      
                      <div className="flex items-center gap-2 min-w-[100px]">
                        {fieldTypeIcons[field.field_type]}
                        <span className="text-sm text-muted-foreground">
                          {fieldTypeLabels[field.field_type]}
                        </span>
                      </div>

                      <div className="flex-1">
                        <div className="font-medium">{field.label}</div>
                        <div className="text-sm text-muted-foreground">{field.name}</div>
                      </div>

                      <div className="flex items-center gap-2">
                        {field.is_required && (
                          <Badge variant="secondary">Required</Badge>
                        )}
                        {field.field_type === 'select' && field.options && (
                          <Badge variant="outline">
                            {(field.options as string[]).length} options
                          </Badge>
                        )}
                      </div>

                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => toggleActive(field)}
                          title={field.is_active ? 'Deactivate' : 'Activate'}
                        >
                          {field.is_active ? (
                            <ToggleRight className="h-5 w-5 text-success" />
                          ) : (
                            <ToggleLeft className="h-5 w-5 text-muted-foreground" />
                          )}
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => openEditDialog(field)}
                        >
                          <Edit2 className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDelete(field)}
                          className="text-destructive hover:text-destructive"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </motion.div>
                  ))}
                </AnimatePresence>
              </div>
            )}
          </CardContent>
        </Card>
      </motion.div>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>
              {editingField ? 'Edit Custom Field' : 'Create Custom Field'}
            </DialogTitle>
            <DialogDescription>
              {editingField
                ? 'Update the field properties'
                : 'Define a new custom field for contacts'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="label">Label</Label>
              <Input
                id="label"
                placeholder="e.g., Industry"
                value={formData.label}
                onChange={(e) => setFormData({ ...formData, label: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="name">Field Name</Label>
              <Input
                id="name"
                placeholder="e.g., industry"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
              <p className="text-xs text-muted-foreground">
                Internal identifier (lowercase, no spaces)
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="type">Field Type</Label>
              <Select
                value={formData.field_type}
                onValueChange={(value) => setFormData({ ...formData, field_type: value as CustomFieldType })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(fieldTypeLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>
                      <div className="flex items-center gap-2">
                        {fieldTypeIcons[value as CustomFieldType]}
                        {label}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {formData.field_type === 'select' && (
              <div className="space-y-2">
                <Label htmlFor="options">Options (one per line)</Label>
                <Textarea
                  id="options"
                  placeholder="Option 1&#10;Option 2&#10;Option 3"
                  value={formData.options}
                  onChange={(e) => setFormData({ ...formData, options: e.target.value })}
                  rows={4}
                />
              </div>
            )}

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="required">Required</Label>
                <p className="text-xs text-muted-foreground">
                  Must be filled when creating contacts
                </p>
              </div>
              <Switch
                id="required"
                checked={formData.is_required}
                onCheckedChange={(checked) => setFormData({ ...formData, is_required: checked })}
              />
            </div>

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="active">Active</Label>
                <p className="text-xs text-muted-foreground">
                  Show this field on contact forms
                </p>
              </div>
              <Switch
                id="active"
                checked={formData.is_active}
                onCheckedChange={(checked) => setFormData({ ...formData, is_active: checked })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
              <X className="h-4 w-4 mr-2" />
              Cancel
            </Button>
            <Button onClick={handleSave}>
              <Save className="h-4 w-4 mr-2" />
              {editingField ? 'Update' : 'Create'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
