import React from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../../ui/dialog';
import { Button } from '../../ui/button';
import { Label } from '../../ui/label';
import { Input } from '../../ui/input';
import { Textarea } from '../../ui/textarea';
import { Switch } from '../../ui/switch';
import { Loader2, Play, Info, Copy, CheckCircle2, Settings, Edit2 } from 'lucide-react';
import { Badge } from '../../ui/badge';

interface TemplateDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingTemplate: any;
  setEditingTemplate: (template: any) => void;
  testDataInput: string;
  setTestDataInput: (data: string) => void;
  previewLoading: boolean;
  handlePreviewTemplate: () => void;
  previewContent: any;
  handleSaveTemplate: () => void;
}

export const TemplateDialog: React.FC<TemplateDialogProps> = ({
  isOpen, onOpenChange, editingTemplate, setEditingTemplate, 
  testDataInput, setTestDataInput, previewLoading, handlePreviewTemplate, 
  previewContent, handleSaveTemplate
}) => {
  const textareaRef = React.useRef<HTMLTextAreaElement>(null);

  const insertPlaceholder = (placeholder: string) => {
    if (!textareaRef.current) return;
    const { selectionStart, selectionEnd } = textareaRef.current;
    const text = editingTemplate?.body || '';
    const newText = text.substring(0, selectionStart) + `{{${placeholder}}}` + text.substring(selectionEnd);
    setEditingTemplate({ ...editingTemplate!, body: newText });
    
    // Set focus back and move cursor
    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus();
        textareaRef.current.setSelectionRange(selectionStart + placeholder.length + 4, selectionStart + placeholder.length + 4);
      }
    }, 0);
  };

  const placeholders = editingTemplate?.placeholders || [];

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-7xl w-full max-h-[95vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{editingTemplate?.id ? 'Edit Email Template' : 'Add Email Template'}</DialogTitle>
          <DialogDescription>Configure automated email template with dynamic content</DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Left Column: Template Configuration */}
          <div className="lg:col-span-4 space-y-6">
            <div className="space-y-4">
              <div className="bg-slate-50 p-4 rounded-lg border border-slate-200 space-y-4">
                <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                  <Settings className="w-4 h-4 text-amber-600" />
                  General Settings
                </h3>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Template Name</Label>
                  <Input
                    placeholder="e.g., Application Received"
                    className="mt-1.5 bg-white"
                    value={editingTemplate?.name || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, name: e.target.value })}
                  />
                </div>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Trigger Code</Label>
                  <Input
                    placeholder="e.g., APPLICATION_RECEIVED"
                    className="mt-1.5 bg-white font-mono text-xs"
                    value={editingTemplate?.templateCode || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, templateCode: e.target.value })}
                  />
                </div>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Description</Label>
                  <Input
                    placeholder="Brief purpose of this email"
                    className="mt-1.5 bg-white"
                    value={editingTemplate?.description || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, description: e.target.value })}
                  />
                </div>
                <div className="flex items-center justify-between pt-2 border-t mt-2">
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="active"
                      checked={editingTemplate?.isActive ?? true}
                      onCheckedChange={(checked) => setEditingTemplate({ ...editingTemplate!, isActive: checked })}
                    />
                    <Label htmlFor="active" className="text-sm cursor-pointer">Active</Label>
                  </div>
                  <Badge className={editingTemplate?.isActive ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"}>
                    {editingTemplate?.isActive ? 'Template Enabled' : 'Template Disabled'}
                  </Badge>
                </div>
              </div>

              {/* Placeholders Library */}
              <div className="bg-amber-50 p-4 rounded-lg border border-amber-100">
                <h3 className="text-sm font-semibold text-amber-900 flex items-center gap-2 mb-3">
                  <Info className="w-4 h-4" />
                  Available Placeholders
                </h3>
                <p className="text-[10px] text-amber-700 mb-4 leading-relaxed">
                  Click on a placeholder below to insert it at your current cursor position in the editor.
                </p>
                <div className="flex flex-wrap gap-2">
                  {placeholders.length > 0 ? placeholders.map((p: string) => (
                    <button
                      key={p}
                      onClick={() => insertPlaceholder(p)}
                      className="px-2 py-1 bg-white border border-amber-200 rounded text-[11px] font-mono text-amber-800 hover:bg-amber-600 hover:text-white hover:border-amber-600 transition-all flex items-center gap-1 shadow-sm"
                    >
                      {`{{${p}}}`}
                    </button>
                  )) : (
                    <div className="w-full py-4 text-center border-2 border-dashed border-amber-200 rounded-lg">
                       <p className="text-[10px] text-amber-600">No placeholders defined for this trigger</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Middle Column: Editor */}
          <div className="lg:col-span-4 space-y-4 flex flex-col h-full min-h-[600px]">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold text-slate-900 flex items-center gap-2">
                <Edit2 className="w-4 h-4 text-amber-600" />
                Template Designer
              </h3>
            </div>
            
            <div className="flex-1 flex flex-col space-y-4">
              <div>
                <Label className="text-xs font-semibold">Subject Line</Label>
                <Input
                  placeholder="Subject line with {{variables}}"
                  className="mt-1.5 text-slate-900 font-medium"
                  value={editingTemplate?.subject || ''}
                  onChange={(e) => setEditingTemplate({ ...editingTemplate!, subject: e.target.value })}
                />
              </div>

              <div className="flex-1 flex flex-col">
                <Label className="text-xs font-semibold mb-1.5">Email Body (HTML/Handlebars)</Label>
                <div className="relative flex-1">
                  <Textarea
                    ref={textareaRef}
                    placeholder="Hello {{applicant_name}}, ..."
                    className="h-full min-h-[450px] font-mono text-sm text-slate-900 bg-slate-900/5 focus:bg-white transition-colors p-4 resize-none"
                    value={editingTemplate?.body || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, body: e.target.value })}
                  />
                  <div className="absolute bottom-3 right-3 opacity-30 pointer-events-none text-[10px] font-mono">
                    HTML Support Enabled
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Right Column: Preview & Simulation */}
          <div className="lg:col-span-4 space-y-6 lg:border-l lg:pl-8 flex flex-col h-full">
            <div>
              <h3 className="font-semibold text-slate-900 flex items-center gap-2 mb-4">
                <Play className="w-4 h-4 text-green-600" />
                Live Simulation
              </h3>
              
              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <Label className="text-xs font-semibold">Mock Test Data (JSON)</Label>
                    <button 
                      onClick={() => setTestDataInput('{"applicantName": "Rajesh Kumar", "location": "Mumbai South", "applicationId": "APP-2026-X12"}')}
                      className="text-[10px] text-amber-600 hover:underline"
                    >
                      Reset to Sample
                    </button>
                  </div>
                  <Textarea
                    placeholder='{"applicant_name": "John Doe"}'
                    className="font-mono text-[11px] text-slate-900 bg-slate-50"
                    rows={6}
                    value={testDataInput}
                    onChange={(e) => setTestDataInput(e.target.value)}
                  />
                </div>
                
                <Button
                  variant="default"
                  className="w-full bg-green-600 hover:bg-green-700 shadow-md"
                  onClick={handlePreviewTemplate}
                  disabled={previewLoading}
                >
                  {previewLoading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Play className="w-4 h-4 mr-2" />}
                  Generate Mock Preview
                </Button>
              </div>
            </div>

            <div className="flex-1 flex flex-col">
              <Label className="text-xs font-semibold mb-2">Simulated Output</Label>
              <div className="flex-1 border rounded-xl overflow-hidden flex flex-col bg-slate-50 shadow-inner">
                {previewContent ? (
                  <>
                    <div className="bg-white p-3 border-b text-[11px] font-semibold text-slate-700 flex items-center justify-between">
                      <div className="truncate shrink">
                        <span className="text-slate-400 mr-2">Subject:</span> {previewContent.subject}
                      </div>
                      <Badge variant="outline" className="bg-green-50 text-green-600 text-[9px] whitespace-nowrap ml-2">
                        <CheckCircle2 className="w-3 h-3 mr-1" /> Compiled
                      </Badge>
                    </div>
                    <div className="p-6 bg-white overflow-auto flex-1 shadow-sm">
                      <div className="max-w-none text-sm text-slate-800 email-preview-container" 
                           dangerouslySetInnerHTML={{ __html: previewContent.html }} />
                    </div>
                  </>
                ) : (
                  <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-slate-400 space-y-3">
                    <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center">
                      <Play className="w-8 h-8 opacity-20" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-slate-500">Ready for Preview</p>
                      <p className="text-[11px]">Click "Generate Mock Preview" to see how your placeholders resolve with the test data.</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="flex gap-3 pt-4 border-t mt-4">
          <Button variant="outline" className="flex-1" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button className="flex-1 bg-amber-600 hover:bg-amber-700" onClick={handleSaveTemplate}>
            Save Template
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};
